Completed
Push — master ( f59db4...6d0d83 )
by
unknown
34:29 queued 07:13
created
apps/dav/lib/CalDAV/CalDavBackend.php 1 patch
Indentation   +3582 added lines, -3582 removed lines patch added patch discarded remove patch
@@ -105,3587 +105,3587 @@
 block discarded – undo
105 105
  * }
106 106
  */
107 107
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
108
-	use TTransactional;
109
-
110
-	public const CALENDAR_TYPE_CALENDAR = 0;
111
-	public const CALENDAR_TYPE_SUBSCRIPTION = 1;
112
-
113
-	public const PERSONAL_CALENDAR_URI = 'personal';
114
-	public const PERSONAL_CALENDAR_NAME = 'Personal';
115
-
116
-	public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
117
-	public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
118
-
119
-	/**
120
-	 * We need to specify a max date, because we need to stop *somewhere*
121
-	 *
122
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
123
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
124
-	 * in 2038-01-19 to avoid problems when the date is converted
125
-	 * to a unix timestamp.
126
-	 */
127
-	public const MAX_DATE = '2038-01-01';
128
-
129
-	public const ACCESS_PUBLIC = 4;
130
-	public const CLASSIFICATION_PUBLIC = 0;
131
-	public const CLASSIFICATION_PRIVATE = 1;
132
-	public const CLASSIFICATION_CONFIDENTIAL = 2;
133
-
134
-	/**
135
-	 * List of CalDAV properties, and how they map to database field names and their type
136
-	 * Add your own properties by simply adding on to this array.
137
-	 *
138
-	 * @var array
139
-	 * @psalm-var array<string, string[]>
140
-	 */
141
-	public array $propertyMap = [
142
-		'{DAV:}displayname' => ['displayname', 'string'],
143
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => ['description', 'string'],
144
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone' => ['timezone', 'string'],
145
-		'{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
146
-		'{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
147
-		'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => ['deleted_at', 'int'],
148
-	];
149
-
150
-	/**
151
-	 * List of subscription properties, and how they map to database field names.
152
-	 *
153
-	 * @var array
154
-	 */
155
-	public array $subscriptionPropertyMap = [
156
-		'{DAV:}displayname' => ['displayname', 'string'],
157
-		'{http://apple.com/ns/ical/}refreshrate' => ['refreshrate', 'string'],
158
-		'{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
159
-		'{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
160
-		'{http://calendarserver.org/ns/}subscribed-strip-todos' => ['striptodos', 'bool'],
161
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms' => ['stripalarms', 'string'],
162
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => ['stripattachments', 'string'],
163
-	];
164
-
165
-	/**
166
-	 * properties to index
167
-	 *
168
-	 * This list has to be kept in sync with ICalendarQuery::SEARCH_PROPERTY_*
169
-	 *
170
-	 * @see \OCP\Calendar\ICalendarQuery
171
-	 */
172
-	private const INDEXED_PROPERTIES = [
173
-		'CATEGORIES',
174
-		'COMMENT',
175
-		'DESCRIPTION',
176
-		'LOCATION',
177
-		'RESOURCES',
178
-		'STATUS',
179
-		'SUMMARY',
180
-		'ATTENDEE',
181
-		'CONTACT',
182
-		'ORGANIZER'
183
-	];
184
-
185
-	/** @var array parameters to index */
186
-	public static array $indexParameters = [
187
-		'ATTENDEE' => ['CN'],
188
-		'ORGANIZER' => ['CN'],
189
-	];
190
-
191
-	/**
192
-	 * @var string[] Map of uid => display name
193
-	 */
194
-	protected array $userDisplayNames;
195
-
196
-	private string $dbObjectsTable = 'calendarobjects';
197
-	private string $dbObjectPropertiesTable = 'calendarobjects_props';
198
-	private string $dbObjectInvitationsTable = 'calendar_invitations';
199
-	private array $cachedObjects = [];
200
-
201
-	public function __construct(
202
-		private IDBConnection $db,
203
-		private Principal $principalBackend,
204
-		private IUserManager $userManager,
205
-		private ISecureRandom $random,
206
-		private LoggerInterface $logger,
207
-		private IEventDispatcher $dispatcher,
208
-		private IConfig $config,
209
-		private Sharing\Backend $calendarSharingBackend,
210
-		private bool $legacyEndpoint = false,
211
-	) {
212
-	}
213
-
214
-	/**
215
-	 * Return the number of calendars for a principal
216
-	 *
217
-	 * By default this excludes the automatically generated birthday calendar
218
-	 *
219
-	 * @param $principalUri
220
-	 * @param bool $excludeBirthday
221
-	 * @return int
222
-	 */
223
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
224
-		$principalUri = $this->convertPrincipal($principalUri, true);
225
-		$query = $this->db->getQueryBuilder();
226
-		$query->select($query->func()->count('*'))
227
-			->from('calendars');
228
-
229
-		if ($principalUri === '') {
230
-			$query->where($query->expr()->emptyString('principaluri'));
231
-		} else {
232
-			$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
233
-		}
234
-
235
-		if ($excludeBirthday) {
236
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
237
-		}
238
-
239
-		$result = $query->executeQuery();
240
-		$column = (int)$result->fetchOne();
241
-		$result->closeCursor();
242
-		return $column;
243
-	}
244
-
245
-	/**
246
-	 * Return the number of subscriptions for a principal
247
-	 */
248
-	public function getSubscriptionsForUserCount(string $principalUri): int {
249
-		$principalUri = $this->convertPrincipal($principalUri, true);
250
-		$query = $this->db->getQueryBuilder();
251
-		$query->select($query->func()->count('*'))
252
-			->from('calendarsubscriptions');
253
-
254
-		if ($principalUri === '') {
255
-			$query->where($query->expr()->emptyString('principaluri'));
256
-		} else {
257
-			$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
258
-		}
259
-
260
-		$result = $query->executeQuery();
261
-		$column = (int)$result->fetchOne();
262
-		$result->closeCursor();
263
-		return $column;
264
-	}
265
-
266
-	/**
267
-	 * @return array{id: int, deleted_at: int}[]
268
-	 */
269
-	public function getDeletedCalendars(int $deletedBefore): array {
270
-		$qb = $this->db->getQueryBuilder();
271
-		$qb->select(['id', 'deleted_at'])
272
-			->from('calendars')
273
-			->where($qb->expr()->isNotNull('deleted_at'))
274
-			->andWhere($qb->expr()->lt('deleted_at', $qb->createNamedParameter($deletedBefore)));
275
-		$result = $qb->executeQuery();
276
-		$calendars = [];
277
-		while (($row = $result->fetch()) !== false) {
278
-			$calendars[] = [
279
-				'id' => (int)$row['id'],
280
-				'deleted_at' => (int)$row['deleted_at'],
281
-			];
282
-		}
283
-		$result->closeCursor();
284
-		return $calendars;
285
-	}
286
-
287
-	/**
288
-	 * Returns a list of calendars for a principal.
289
-	 *
290
-	 * Every project is an array with the following keys:
291
-	 *  * id, a unique id that will be used by other functions to modify the
292
-	 *    calendar. This can be the same as the uri or a database key.
293
-	 *  * uri, which the basename of the uri with which the calendar is
294
-	 *    accessed.
295
-	 *  * principaluri. The owner of the calendar. Almost always the same as
296
-	 *    principalUri passed to this method.
297
-	 *
298
-	 * Furthermore it can contain webdav properties in clark notation. A very
299
-	 * common one is '{DAV:}displayname'.
300
-	 *
301
-	 * Many clients also require:
302
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
303
-	 * For this property, you can just return an instance of
304
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
305
-	 *
306
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
307
-	 * ACL will automatically be put in read-only mode.
308
-	 *
309
-	 * @param string $principalUri
310
-	 * @return array
311
-	 */
312
-	public function getCalendarsForUser($principalUri) {
313
-		return $this->atomic(function () use ($principalUri) {
314
-			$principalUriOriginal = $principalUri;
315
-			$principalUri = $this->convertPrincipal($principalUri, true);
316
-			$fields = array_column($this->propertyMap, 0);
317
-			$fields[] = 'id';
318
-			$fields[] = 'uri';
319
-			$fields[] = 'synctoken';
320
-			$fields[] = 'components';
321
-			$fields[] = 'principaluri';
322
-			$fields[] = 'transparent';
323
-
324
-			// Making fields a comma-delimited list
325
-			$query = $this->db->getQueryBuilder();
326
-			$query->select($fields)
327
-				->from('calendars')
328
-				->orderBy('calendarorder', 'ASC');
329
-
330
-			if ($principalUri === '') {
331
-				$query->where($query->expr()->emptyString('principaluri'));
332
-			} else {
333
-				$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
334
-			}
335
-
336
-			$result = $query->executeQuery();
337
-
338
-			$calendars = [];
339
-			while ($row = $result->fetch()) {
340
-				$row['principaluri'] = (string)$row['principaluri'];
341
-				$components = [];
342
-				if ($row['components']) {
343
-					$components = explode(',', $row['components']);
344
-				}
345
-
346
-				$calendar = [
347
-					'id' => $row['id'],
348
-					'uri' => $row['uri'],
349
-					'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
350
-					'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
351
-					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
352
-					'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
353
-					'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
354
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
355
-				];
356
-
357
-				$calendar = $this->rowToCalendar($row, $calendar);
358
-				$calendar = $this->addOwnerPrincipalToCalendar($calendar);
359
-				$calendar = $this->addResourceTypeToCalendar($row, $calendar);
360
-
361
-				if (!isset($calendars[$calendar['id']])) {
362
-					$calendars[$calendar['id']] = $calendar;
363
-				}
364
-			}
365
-			$result->closeCursor();
366
-
367
-			// query for shared calendars
368
-			$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
369
-			$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
370
-			$principals[] = $principalUri;
371
-
372
-			$fields = array_column($this->propertyMap, 0);
373
-			$fields = array_map(function (string $field) {
374
-				return 'a.' . $field;
375
-			}, $fields);
376
-			$fields[] = 'a.id';
377
-			$fields[] = 'a.uri';
378
-			$fields[] = 'a.synctoken';
379
-			$fields[] = 'a.components';
380
-			$fields[] = 'a.principaluri';
381
-			$fields[] = 'a.transparent';
382
-			$fields[] = 's.access';
383
-
384
-			$select = $this->db->getQueryBuilder();
385
-			$subSelect = $this->db->getQueryBuilder();
386
-
387
-			$subSelect->select('resourceid')
388
-				->from('dav_shares', 'd')
389
-				->where($subSelect->expr()->eq('d.access', $select->createNamedParameter(Backend::ACCESS_UNSHARED, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
390
-				->andWhere($subSelect->expr()->eq('d.principaluri', $select->createNamedParameter($principalUri, IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR));
391
-
392
-			$select->select($fields)
393
-				->from('dav_shares', 's')
394
-				->join('s', 'calendars', 'a', $select->expr()->eq('s.resourceid', 'a.id', IQueryBuilder::PARAM_INT))
395
-				->where($select->expr()->in('s.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
396
-				->andWhere($select->expr()->eq('s.type', $select->createNamedParameter('calendar', IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR))
397
-				->andWhere($select->expr()->notIn('a.id', $select->createFunction($subSelect->getSQL()), IQueryBuilder::PARAM_INT_ARRAY));
398
-
399
-			$results = $select->executeQuery();
400
-
401
-			$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
402
-			while ($row = $results->fetch()) {
403
-				$row['principaluri'] = (string)$row['principaluri'];
404
-				if ($row['principaluri'] === $principalUri) {
405
-					continue;
406
-				}
407
-
408
-				$readOnly = (int)$row['access'] === Backend::ACCESS_READ;
409
-				if (isset($calendars[$row['id']])) {
410
-					if ($readOnly) {
411
-						// New share can not have more permissions than the old one.
412
-						continue;
413
-					}
414
-					if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
415
-						$calendars[$row['id']][$readOnlyPropertyName] === 0) {
416
-						// Old share is already read-write, no more permissions can be gained
417
-						continue;
418
-					}
419
-				}
420
-
421
-				[, $name] = Uri\split($row['principaluri']);
422
-				$uri = $row['uri'] . '_shared_by_' . $name;
423
-				$row['displayname'] = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? ($name ?? '')) . ')';
424
-				$components = [];
425
-				if ($row['components']) {
426
-					$components = explode(',', $row['components']);
427
-				}
428
-				$calendar = [
429
-					'id' => $row['id'],
430
-					'uri' => $uri,
431
-					'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
432
-					'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
433
-					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
434
-					'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
435
-					'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
436
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
437
-					$readOnlyPropertyName => $readOnly,
438
-				];
439
-
440
-				$calendar = $this->rowToCalendar($row, $calendar);
441
-				$calendar = $this->addOwnerPrincipalToCalendar($calendar);
442
-				$calendar = $this->addResourceTypeToCalendar($row, $calendar);
443
-
444
-				$calendars[$calendar['id']] = $calendar;
445
-			}
446
-			$result->closeCursor();
447
-
448
-			return array_values($calendars);
449
-		}, $this->db);
450
-	}
451
-
452
-	/**
453
-	 * @param $principalUri
454
-	 * @return array
455
-	 */
456
-	public function getUsersOwnCalendars($principalUri) {
457
-		$principalUri = $this->convertPrincipal($principalUri, true);
458
-		$fields = array_column($this->propertyMap, 0);
459
-		$fields[] = 'id';
460
-		$fields[] = 'uri';
461
-		$fields[] = 'synctoken';
462
-		$fields[] = 'components';
463
-		$fields[] = 'principaluri';
464
-		$fields[] = 'transparent';
465
-		// Making fields a comma-delimited list
466
-		$query = $this->db->getQueryBuilder();
467
-		$query->select($fields)->from('calendars')
468
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
469
-			->orderBy('calendarorder', 'ASC');
470
-		$stmt = $query->executeQuery();
471
-		$calendars = [];
472
-		while ($row = $stmt->fetch()) {
473
-			$row['principaluri'] = (string)$row['principaluri'];
474
-			$components = [];
475
-			if ($row['components']) {
476
-				$components = explode(',', $row['components']);
477
-			}
478
-			$calendar = [
479
-				'id' => $row['id'],
480
-				'uri' => $row['uri'],
481
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
482
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
483
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
484
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
486
-			];
487
-
488
-			$calendar = $this->rowToCalendar($row, $calendar);
489
-			$calendar = $this->addOwnerPrincipalToCalendar($calendar);
490
-			$calendar = $this->addResourceTypeToCalendar($row, $calendar);
491
-
492
-			if (!isset($calendars[$calendar['id']])) {
493
-				$calendars[$calendar['id']] = $calendar;
494
-			}
495
-		}
496
-		$stmt->closeCursor();
497
-		return array_values($calendars);
498
-	}
499
-
500
-	/**
501
-	 * @return array
502
-	 */
503
-	public function getPublicCalendars() {
504
-		$fields = array_column($this->propertyMap, 0);
505
-		$fields[] = 'a.id';
506
-		$fields[] = 'a.uri';
507
-		$fields[] = 'a.synctoken';
508
-		$fields[] = 'a.components';
509
-		$fields[] = 'a.principaluri';
510
-		$fields[] = 'a.transparent';
511
-		$fields[] = 's.access';
512
-		$fields[] = 's.publicuri';
513
-		$calendars = [];
514
-		$query = $this->db->getQueryBuilder();
515
-		$result = $query->select($fields)
516
-			->from('dav_shares', 's')
517
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
518
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
519
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
520
-			->executeQuery();
521
-
522
-		while ($row = $result->fetch()) {
523
-			$row['principaluri'] = (string)$row['principaluri'];
524
-			[, $name] = Uri\split($row['principaluri']);
525
-			$row['displayname'] = $row['displayname'] . "($name)";
526
-			$components = [];
527
-			if ($row['components']) {
528
-				$components = explode(',', $row['components']);
529
-			}
530
-			$calendar = [
531
-				'id' => $row['id'],
532
-				'uri' => $row['publicuri'],
533
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
534
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
535
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
536
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
537
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
538
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
539
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
540
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
541
-			];
542
-
543
-			$calendar = $this->rowToCalendar($row, $calendar);
544
-			$calendar = $this->addOwnerPrincipalToCalendar($calendar);
545
-			$calendar = $this->addResourceTypeToCalendar($row, $calendar);
546
-
547
-			if (!isset($calendars[$calendar['id']])) {
548
-				$calendars[$calendar['id']] = $calendar;
549
-			}
550
-		}
551
-		$result->closeCursor();
552
-
553
-		return array_values($calendars);
554
-	}
555
-
556
-	/**
557
-	 * @param string $uri
558
-	 * @return array
559
-	 * @throws NotFound
560
-	 */
561
-	public function getPublicCalendar($uri) {
562
-		$fields = array_column($this->propertyMap, 0);
563
-		$fields[] = 'a.id';
564
-		$fields[] = 'a.uri';
565
-		$fields[] = 'a.synctoken';
566
-		$fields[] = 'a.components';
567
-		$fields[] = 'a.principaluri';
568
-		$fields[] = 'a.transparent';
569
-		$fields[] = 's.access';
570
-		$fields[] = 's.publicuri';
571
-		$query = $this->db->getQueryBuilder();
572
-		$result = $query->select($fields)
573
-			->from('dav_shares', 's')
574
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
575
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
576
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
577
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
578
-			->executeQuery();
579
-
580
-		$row = $result->fetch();
581
-
582
-		$result->closeCursor();
583
-
584
-		if ($row === false) {
585
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
586
-		}
587
-
588
-		$row['principaluri'] = (string)$row['principaluri'];
589
-		[, $name] = Uri\split($row['principaluri']);
590
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
591
-		$components = [];
592
-		if ($row['components']) {
593
-			$components = explode(',', $row['components']);
594
-		}
595
-		$calendar = [
596
-			'id' => $row['id'],
597
-			'uri' => $row['publicuri'],
598
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
599
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
600
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
601
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
602
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
603
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
604
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
605
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
606
-		];
607
-
608
-		$calendar = $this->rowToCalendar($row, $calendar);
609
-		$calendar = $this->addOwnerPrincipalToCalendar($calendar);
610
-		$calendar = $this->addResourceTypeToCalendar($row, $calendar);
611
-
612
-		return $calendar;
613
-	}
614
-
615
-	/**
616
-	 * @param string $principal
617
-	 * @param string $uri
618
-	 * @return array|null
619
-	 */
620
-	public function getCalendarByUri($principal, $uri) {
621
-		$fields = array_column($this->propertyMap, 0);
622
-		$fields[] = 'id';
623
-		$fields[] = 'uri';
624
-		$fields[] = 'synctoken';
625
-		$fields[] = 'components';
626
-		$fields[] = 'principaluri';
627
-		$fields[] = 'transparent';
628
-
629
-		// Making fields a comma-delimited list
630
-		$query = $this->db->getQueryBuilder();
631
-		$query->select($fields)->from('calendars')
632
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
633
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
634
-			->setMaxResults(1);
635
-		$stmt = $query->executeQuery();
636
-
637
-		$row = $stmt->fetch();
638
-		$stmt->closeCursor();
639
-		if ($row === false) {
640
-			return null;
641
-		}
642
-
643
-		$row['principaluri'] = (string)$row['principaluri'];
644
-		$components = [];
645
-		if ($row['components']) {
646
-			$components = explode(',', $row['components']);
647
-		}
648
-
649
-		$calendar = [
650
-			'id' => $row['id'],
651
-			'uri' => $row['uri'],
652
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
653
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
654
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
655
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
656
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
657
-		];
658
-
659
-		$calendar = $this->rowToCalendar($row, $calendar);
660
-		$calendar = $this->addOwnerPrincipalToCalendar($calendar);
661
-		$calendar = $this->addResourceTypeToCalendar($row, $calendar);
662
-
663
-		return $calendar;
664
-	}
665
-
666
-	/**
667
-	 * @psalm-return CalendarInfo|null
668
-	 * @return array|null
669
-	 */
670
-	public function getCalendarById(int $calendarId): ?array {
671
-		$fields = array_column($this->propertyMap, 0);
672
-		$fields[] = 'id';
673
-		$fields[] = 'uri';
674
-		$fields[] = 'synctoken';
675
-		$fields[] = 'components';
676
-		$fields[] = 'principaluri';
677
-		$fields[] = 'transparent';
678
-
679
-		// Making fields a comma-delimited list
680
-		$query = $this->db->getQueryBuilder();
681
-		$query->select($fields)->from('calendars')
682
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
683
-			->setMaxResults(1);
684
-		$stmt = $query->executeQuery();
685
-
686
-		$row = $stmt->fetch();
687
-		$stmt->closeCursor();
688
-		if ($row === false) {
689
-			return null;
690
-		}
691
-
692
-		$row['principaluri'] = (string)$row['principaluri'];
693
-		$components = [];
694
-		if ($row['components']) {
695
-			$components = explode(',', $row['components']);
696
-		}
697
-
698
-		$calendar = [
699
-			'id' => $row['id'],
700
-			'uri' => $row['uri'],
701
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
702
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
703
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?? 0,
704
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
705
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
706
-		];
707
-
708
-		$calendar = $this->rowToCalendar($row, $calendar);
709
-		$calendar = $this->addOwnerPrincipalToCalendar($calendar);
710
-		$calendar = $this->addResourceTypeToCalendar($row, $calendar);
711
-
712
-		return $calendar;
713
-	}
714
-
715
-	/**
716
-	 * @param $subscriptionId
717
-	 */
718
-	public function getSubscriptionById($subscriptionId) {
719
-		$fields = array_column($this->subscriptionPropertyMap, 0);
720
-		$fields[] = 'id';
721
-		$fields[] = 'uri';
722
-		$fields[] = 'source';
723
-		$fields[] = 'synctoken';
724
-		$fields[] = 'principaluri';
725
-		$fields[] = 'lastmodified';
726
-
727
-		$query = $this->db->getQueryBuilder();
728
-		$query->select($fields)
729
-			->from('calendarsubscriptions')
730
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
731
-			->orderBy('calendarorder', 'asc');
732
-		$stmt = $query->executeQuery();
733
-
734
-		$row = $stmt->fetch();
735
-		$stmt->closeCursor();
736
-		if ($row === false) {
737
-			return null;
738
-		}
739
-
740
-		$row['principaluri'] = (string)$row['principaluri'];
741
-		$subscription = [
742
-			'id' => $row['id'],
743
-			'uri' => $row['uri'],
744
-			'principaluri' => $row['principaluri'],
745
-			'source' => $row['source'],
746
-			'lastmodified' => $row['lastmodified'],
747
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
748
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
749
-		];
750
-
751
-		return $this->rowToSubscription($row, $subscription);
752
-	}
753
-
754
-	public function getSubscriptionByUri(string $principal, string $uri): ?array {
755
-		$fields = array_column($this->subscriptionPropertyMap, 0);
756
-		$fields[] = 'id';
757
-		$fields[] = 'uri';
758
-		$fields[] = 'source';
759
-		$fields[] = 'synctoken';
760
-		$fields[] = 'principaluri';
761
-		$fields[] = 'lastmodified';
762
-
763
-		$query = $this->db->getQueryBuilder();
764
-		$query->select($fields)
765
-			->from('calendarsubscriptions')
766
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
767
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
768
-			->setMaxResults(1);
769
-		$stmt = $query->executeQuery();
770
-
771
-		$row = $stmt->fetch();
772
-		$stmt->closeCursor();
773
-		if ($row === false) {
774
-			return null;
775
-		}
776
-
777
-		$row['principaluri'] = (string)$row['principaluri'];
778
-		$subscription = [
779
-			'id' => $row['id'],
780
-			'uri' => $row['uri'],
781
-			'principaluri' => $row['principaluri'],
782
-			'source' => $row['source'],
783
-			'lastmodified' => $row['lastmodified'],
784
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
785
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
786
-		];
787
-
788
-		return $this->rowToSubscription($row, $subscription);
789
-	}
790
-
791
-	/**
792
-	 * Creates a new calendar for a principal.
793
-	 *
794
-	 * If the creation was a success, an id must be returned that can be used to reference
795
-	 * this calendar in other methods, such as updateCalendar.
796
-	 *
797
-	 * @param string $principalUri
798
-	 * @param string $calendarUri
799
-	 * @param array $properties
800
-	 * @return int
801
-	 *
802
-	 * @throws CalendarException
803
-	 */
804
-	public function createCalendar($principalUri, $calendarUri, array $properties) {
805
-		if (strlen($calendarUri) > 255) {
806
-			throw new CalendarException('URI too long. Calendar not created');
807
-		}
808
-
809
-		$values = [
810
-			'principaluri' => $this->convertPrincipal($principalUri, true),
811
-			'uri' => $calendarUri,
812
-			'synctoken' => 1,
813
-			'transparent' => 0,
814
-			'components' => 'VEVENT,VTODO,VJOURNAL',
815
-			'displayname' => $calendarUri
816
-		];
817
-
818
-		// Default value
819
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
820
-		if (isset($properties[$sccs])) {
821
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
822
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
823
-			}
824
-			$values['components'] = implode(',', $properties[$sccs]->getValue());
825
-		} elseif (isset($properties['components'])) {
826
-			// Allow to provide components internally without having
827
-			// to create a SupportedCalendarComponentSet object
828
-			$values['components'] = $properties['components'];
829
-		}
830
-
831
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
832
-		if (isset($properties[$transp])) {
833
-			$values['transparent'] = (int)($properties[$transp]->getValue() === 'transparent');
834
-		}
835
-
836
-		foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
837
-			if (isset($properties[$xmlName])) {
838
-				$values[$dbName] = $properties[$xmlName];
839
-			}
840
-		}
841
-
842
-		[$calendarId, $calendarData] = $this->atomic(function () use ($values) {
843
-			$query = $this->db->getQueryBuilder();
844
-			$query->insert('calendars');
845
-			foreach ($values as $column => $value) {
846
-				$query->setValue($column, $query->createNamedParameter($value));
847
-			}
848
-			$query->executeStatement();
849
-			$calendarId = $query->getLastInsertId();
850
-
851
-			$calendarData = $this->getCalendarById($calendarId);
852
-			return [$calendarId, $calendarData];
853
-		}, $this->db);
854
-
855
-		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
856
-
857
-		return $calendarId;
858
-	}
859
-
860
-	/**
861
-	 * Updates properties for a calendar.
862
-	 *
863
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
864
-	 * To do the actual updates, you must tell this object which properties
865
-	 * you're going to process with the handle() method.
866
-	 *
867
-	 * Calling the handle method is like telling the PropPatch object "I
868
-	 * promise I can handle updating this property".
869
-	 *
870
-	 * Read the PropPatch documentation for more info and examples.
871
-	 *
872
-	 * @param mixed $calendarId
873
-	 * @param PropPatch $propPatch
874
-	 * @return void
875
-	 */
876
-	public function updateCalendar($calendarId, PropPatch $propPatch) {
877
-		$supportedProperties = array_keys($this->propertyMap);
878
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
879
-
880
-		$propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
881
-			$newValues = [];
882
-			foreach ($mutations as $propertyName => $propertyValue) {
883
-				switch ($propertyName) {
884
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
885
-						$fieldName = 'transparent';
886
-						$newValues[$fieldName] = (int)($propertyValue->getValue() === 'transparent');
887
-						break;
888
-					default:
889
-						$fieldName = $this->propertyMap[$propertyName][0];
890
-						$newValues[$fieldName] = $propertyValue;
891
-						break;
892
-				}
893
-			}
894
-			[$calendarData, $shares] = $this->atomic(function () use ($calendarId, $newValues) {
895
-				$query = $this->db->getQueryBuilder();
896
-				$query->update('calendars');
897
-				foreach ($newValues as $fieldName => $value) {
898
-					$query->set($fieldName, $query->createNamedParameter($value));
899
-				}
900
-				$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
901
-				$query->executeStatement();
902
-
903
-				$this->addChanges($calendarId, [''], 2);
904
-
905
-				$calendarData = $this->getCalendarById($calendarId);
906
-				$shares = $this->getShares($calendarId);
907
-				return [$calendarData, $shares];
908
-			}, $this->db);
909
-
910
-			$this->dispatcher->dispatchTyped(new CalendarUpdatedEvent($calendarId, $calendarData, $shares, $mutations));
911
-
912
-			return true;
913
-		});
914
-	}
915
-
916
-	/**
917
-	 * Delete a calendar and all it's objects
918
-	 *
919
-	 * @param mixed $calendarId
920
-	 * @return void
921
-	 */
922
-	public function deleteCalendar($calendarId, bool $forceDeletePermanently = false) {
923
-		$this->atomic(function () use ($calendarId, $forceDeletePermanently): void {
924
-			// The calendar is deleted right away if this is either enforced by the caller
925
-			// or the special contacts birthday calendar or when the preference of an empty
926
-			// retention (0 seconds) is set, which signals a disabled trashbin.
927
-			$calendarData = $this->getCalendarById($calendarId);
928
-			$isBirthdayCalendar = isset($calendarData['uri']) && $calendarData['uri'] === BirthdayService::BIRTHDAY_CALENDAR_URI;
929
-			$trashbinDisabled = $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0';
930
-			if ($forceDeletePermanently || $isBirthdayCalendar || $trashbinDisabled) {
931
-				$calendarData = $this->getCalendarById($calendarId);
932
-				$shares = $this->getShares($calendarId);
933
-
934
-				$this->purgeCalendarInvitations($calendarId);
935
-
936
-				$qbDeleteCalendarObjectProps = $this->db->getQueryBuilder();
937
-				$qbDeleteCalendarObjectProps->delete($this->dbObjectPropertiesTable)
938
-					->where($qbDeleteCalendarObjectProps->expr()->eq('calendarid', $qbDeleteCalendarObjectProps->createNamedParameter($calendarId)))
939
-					->andWhere($qbDeleteCalendarObjectProps->expr()->eq('calendartype', $qbDeleteCalendarObjectProps->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
940
-					->executeStatement();
941
-
942
-				$qbDeleteCalendarObjects = $this->db->getQueryBuilder();
943
-				$qbDeleteCalendarObjects->delete('calendarobjects')
944
-					->where($qbDeleteCalendarObjects->expr()->eq('calendarid', $qbDeleteCalendarObjects->createNamedParameter($calendarId)))
945
-					->andWhere($qbDeleteCalendarObjects->expr()->eq('calendartype', $qbDeleteCalendarObjects->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
946
-					->executeStatement();
947
-
948
-				$qbDeleteCalendarChanges = $this->db->getQueryBuilder();
949
-				$qbDeleteCalendarChanges->delete('calendarchanges')
950
-					->where($qbDeleteCalendarChanges->expr()->eq('calendarid', $qbDeleteCalendarChanges->createNamedParameter($calendarId)))
951
-					->andWhere($qbDeleteCalendarChanges->expr()->eq('calendartype', $qbDeleteCalendarChanges->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
952
-					->executeStatement();
953
-
954
-				$this->calendarSharingBackend->deleteAllShares($calendarId);
955
-
956
-				$qbDeleteCalendar = $this->db->getQueryBuilder();
957
-				$qbDeleteCalendar->delete('calendars')
958
-					->where($qbDeleteCalendar->expr()->eq('id', $qbDeleteCalendar->createNamedParameter($calendarId)))
959
-					->executeStatement();
960
-
961
-				// Only dispatch if we actually deleted anything
962
-				if ($calendarData) {
963
-					$this->dispatcher->dispatchTyped(new CalendarDeletedEvent($calendarId, $calendarData, $shares));
964
-				}
965
-			} else {
966
-				$qbMarkCalendarDeleted = $this->db->getQueryBuilder();
967
-				$qbMarkCalendarDeleted->update('calendars')
968
-					->set('deleted_at', $qbMarkCalendarDeleted->createNamedParameter(time()))
969
-					->where($qbMarkCalendarDeleted->expr()->eq('id', $qbMarkCalendarDeleted->createNamedParameter($calendarId)))
970
-					->executeStatement();
971
-
972
-				$calendarData = $this->getCalendarById($calendarId);
973
-				$shares = $this->getShares($calendarId);
974
-				if ($calendarData) {
975
-					$this->dispatcher->dispatchTyped(new CalendarMovedToTrashEvent(
976
-						$calendarId,
977
-						$calendarData,
978
-						$shares
979
-					));
980
-				}
981
-			}
982
-		}, $this->db);
983
-	}
984
-
985
-	public function restoreCalendar(int $id): void {
986
-		$this->atomic(function () use ($id): void {
987
-			$qb = $this->db->getQueryBuilder();
988
-			$update = $qb->update('calendars')
989
-				->set('deleted_at', $qb->createNamedParameter(null))
990
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
991
-			$update->executeStatement();
992
-
993
-			$calendarData = $this->getCalendarById($id);
994
-			$shares = $this->getShares($id);
995
-			if ($calendarData === null) {
996
-				throw new RuntimeException('Calendar data that was just written can\'t be read back. Check your database configuration.');
997
-			}
998
-			$this->dispatcher->dispatchTyped(new CalendarRestoredEvent(
999
-				$id,
1000
-				$calendarData,
1001
-				$shares
1002
-			));
1003
-		}, $this->db);
1004
-	}
1005
-
1006
-	/**
1007
-	 * Returns all calendar entries as a stream of data
1008
-	 *
1009
-	 * @since 32.0.0
1010
-	 *
1011
-	 * @return Generator<array>
1012
-	 */
1013
-	public function exportCalendar(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR, ?CalendarExportOptions $options = null): Generator {
1014
-		// extract options
1015
-		$rangeStart = $options?->getRangeStart();
1016
-		$rangeCount = $options?->getRangeCount();
1017
-		// construct query
1018
-		$qb = $this->db->getQueryBuilder();
1019
-		$qb->select('*')
1020
-			->from('calendarobjects')
1021
-			->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1022
-			->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1023
-			->andWhere($qb->expr()->isNull('deleted_at'));
1024
-		if ($rangeStart !== null) {
1025
-			$qb->andWhere($qb->expr()->gt('uid', $qb->createNamedParameter($rangeStart)));
1026
-		}
1027
-		if ($rangeCount !== null) {
1028
-			$qb->setMaxResults($rangeCount);
1029
-		}
1030
-		if ($rangeStart !== null || $rangeCount !== null) {
1031
-			$qb->orderBy('uid', 'ASC');
1032
-		}
1033
-		$rs = $qb->executeQuery();
1034
-		// iterate through results
1035
-		try {
1036
-			while (($row = $rs->fetch()) !== false) {
1037
-				yield $row;
1038
-			}
1039
-		} finally {
1040
-			$rs->closeCursor();
1041
-		}
1042
-	}
108
+    use TTransactional;
109
+
110
+    public const CALENDAR_TYPE_CALENDAR = 0;
111
+    public const CALENDAR_TYPE_SUBSCRIPTION = 1;
112
+
113
+    public const PERSONAL_CALENDAR_URI = 'personal';
114
+    public const PERSONAL_CALENDAR_NAME = 'Personal';
115
+
116
+    public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
117
+    public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
118
+
119
+    /**
120
+     * We need to specify a max date, because we need to stop *somewhere*
121
+     *
122
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
123
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
124
+     * in 2038-01-19 to avoid problems when the date is converted
125
+     * to a unix timestamp.
126
+     */
127
+    public const MAX_DATE = '2038-01-01';
128
+
129
+    public const ACCESS_PUBLIC = 4;
130
+    public const CLASSIFICATION_PUBLIC = 0;
131
+    public const CLASSIFICATION_PRIVATE = 1;
132
+    public const CLASSIFICATION_CONFIDENTIAL = 2;
133
+
134
+    /**
135
+     * List of CalDAV properties, and how they map to database field names and their type
136
+     * Add your own properties by simply adding on to this array.
137
+     *
138
+     * @var array
139
+     * @psalm-var array<string, string[]>
140
+     */
141
+    public array $propertyMap = [
142
+        '{DAV:}displayname' => ['displayname', 'string'],
143
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => ['description', 'string'],
144
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => ['timezone', 'string'],
145
+        '{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
146
+        '{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
147
+        '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => ['deleted_at', 'int'],
148
+    ];
149
+
150
+    /**
151
+     * List of subscription properties, and how they map to database field names.
152
+     *
153
+     * @var array
154
+     */
155
+    public array $subscriptionPropertyMap = [
156
+        '{DAV:}displayname' => ['displayname', 'string'],
157
+        '{http://apple.com/ns/ical/}refreshrate' => ['refreshrate', 'string'],
158
+        '{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
159
+        '{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
160
+        '{http://calendarserver.org/ns/}subscribed-strip-todos' => ['striptodos', 'bool'],
161
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms' => ['stripalarms', 'string'],
162
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => ['stripattachments', 'string'],
163
+    ];
164
+
165
+    /**
166
+     * properties to index
167
+     *
168
+     * This list has to be kept in sync with ICalendarQuery::SEARCH_PROPERTY_*
169
+     *
170
+     * @see \OCP\Calendar\ICalendarQuery
171
+     */
172
+    private const INDEXED_PROPERTIES = [
173
+        'CATEGORIES',
174
+        'COMMENT',
175
+        'DESCRIPTION',
176
+        'LOCATION',
177
+        'RESOURCES',
178
+        'STATUS',
179
+        'SUMMARY',
180
+        'ATTENDEE',
181
+        'CONTACT',
182
+        'ORGANIZER'
183
+    ];
184
+
185
+    /** @var array parameters to index */
186
+    public static array $indexParameters = [
187
+        'ATTENDEE' => ['CN'],
188
+        'ORGANIZER' => ['CN'],
189
+    ];
190
+
191
+    /**
192
+     * @var string[] Map of uid => display name
193
+     */
194
+    protected array $userDisplayNames;
195
+
196
+    private string $dbObjectsTable = 'calendarobjects';
197
+    private string $dbObjectPropertiesTable = 'calendarobjects_props';
198
+    private string $dbObjectInvitationsTable = 'calendar_invitations';
199
+    private array $cachedObjects = [];
200
+
201
+    public function __construct(
202
+        private IDBConnection $db,
203
+        private Principal $principalBackend,
204
+        private IUserManager $userManager,
205
+        private ISecureRandom $random,
206
+        private LoggerInterface $logger,
207
+        private IEventDispatcher $dispatcher,
208
+        private IConfig $config,
209
+        private Sharing\Backend $calendarSharingBackend,
210
+        private bool $legacyEndpoint = false,
211
+    ) {
212
+    }
213
+
214
+    /**
215
+     * Return the number of calendars for a principal
216
+     *
217
+     * By default this excludes the automatically generated birthday calendar
218
+     *
219
+     * @param $principalUri
220
+     * @param bool $excludeBirthday
221
+     * @return int
222
+     */
223
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
224
+        $principalUri = $this->convertPrincipal($principalUri, true);
225
+        $query = $this->db->getQueryBuilder();
226
+        $query->select($query->func()->count('*'))
227
+            ->from('calendars');
228
+
229
+        if ($principalUri === '') {
230
+            $query->where($query->expr()->emptyString('principaluri'));
231
+        } else {
232
+            $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
233
+        }
234
+
235
+        if ($excludeBirthday) {
236
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
237
+        }
238
+
239
+        $result = $query->executeQuery();
240
+        $column = (int)$result->fetchOne();
241
+        $result->closeCursor();
242
+        return $column;
243
+    }
244
+
245
+    /**
246
+     * Return the number of subscriptions for a principal
247
+     */
248
+    public function getSubscriptionsForUserCount(string $principalUri): int {
249
+        $principalUri = $this->convertPrincipal($principalUri, true);
250
+        $query = $this->db->getQueryBuilder();
251
+        $query->select($query->func()->count('*'))
252
+            ->from('calendarsubscriptions');
253
+
254
+        if ($principalUri === '') {
255
+            $query->where($query->expr()->emptyString('principaluri'));
256
+        } else {
257
+            $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
258
+        }
259
+
260
+        $result = $query->executeQuery();
261
+        $column = (int)$result->fetchOne();
262
+        $result->closeCursor();
263
+        return $column;
264
+    }
265
+
266
+    /**
267
+     * @return array{id: int, deleted_at: int}[]
268
+     */
269
+    public function getDeletedCalendars(int $deletedBefore): array {
270
+        $qb = $this->db->getQueryBuilder();
271
+        $qb->select(['id', 'deleted_at'])
272
+            ->from('calendars')
273
+            ->where($qb->expr()->isNotNull('deleted_at'))
274
+            ->andWhere($qb->expr()->lt('deleted_at', $qb->createNamedParameter($deletedBefore)));
275
+        $result = $qb->executeQuery();
276
+        $calendars = [];
277
+        while (($row = $result->fetch()) !== false) {
278
+            $calendars[] = [
279
+                'id' => (int)$row['id'],
280
+                'deleted_at' => (int)$row['deleted_at'],
281
+            ];
282
+        }
283
+        $result->closeCursor();
284
+        return $calendars;
285
+    }
286
+
287
+    /**
288
+     * Returns a list of calendars for a principal.
289
+     *
290
+     * Every project is an array with the following keys:
291
+     *  * id, a unique id that will be used by other functions to modify the
292
+     *    calendar. This can be the same as the uri or a database key.
293
+     *  * uri, which the basename of the uri with which the calendar is
294
+     *    accessed.
295
+     *  * principaluri. The owner of the calendar. Almost always the same as
296
+     *    principalUri passed to this method.
297
+     *
298
+     * Furthermore it can contain webdav properties in clark notation. A very
299
+     * common one is '{DAV:}displayname'.
300
+     *
301
+     * Many clients also require:
302
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
303
+     * For this property, you can just return an instance of
304
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
305
+     *
306
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
307
+     * ACL will automatically be put in read-only mode.
308
+     *
309
+     * @param string $principalUri
310
+     * @return array
311
+     */
312
+    public function getCalendarsForUser($principalUri) {
313
+        return $this->atomic(function () use ($principalUri) {
314
+            $principalUriOriginal = $principalUri;
315
+            $principalUri = $this->convertPrincipal($principalUri, true);
316
+            $fields = array_column($this->propertyMap, 0);
317
+            $fields[] = 'id';
318
+            $fields[] = 'uri';
319
+            $fields[] = 'synctoken';
320
+            $fields[] = 'components';
321
+            $fields[] = 'principaluri';
322
+            $fields[] = 'transparent';
323
+
324
+            // Making fields a comma-delimited list
325
+            $query = $this->db->getQueryBuilder();
326
+            $query->select($fields)
327
+                ->from('calendars')
328
+                ->orderBy('calendarorder', 'ASC');
329
+
330
+            if ($principalUri === '') {
331
+                $query->where($query->expr()->emptyString('principaluri'));
332
+            } else {
333
+                $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
334
+            }
335
+
336
+            $result = $query->executeQuery();
337
+
338
+            $calendars = [];
339
+            while ($row = $result->fetch()) {
340
+                $row['principaluri'] = (string)$row['principaluri'];
341
+                $components = [];
342
+                if ($row['components']) {
343
+                    $components = explode(',', $row['components']);
344
+                }
345
+
346
+                $calendar = [
347
+                    'id' => $row['id'],
348
+                    'uri' => $row['uri'],
349
+                    'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
350
+                    '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
351
+                    '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
352
+                    '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
353
+                    '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
354
+                    '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
355
+                ];
356
+
357
+                $calendar = $this->rowToCalendar($row, $calendar);
358
+                $calendar = $this->addOwnerPrincipalToCalendar($calendar);
359
+                $calendar = $this->addResourceTypeToCalendar($row, $calendar);
360
+
361
+                if (!isset($calendars[$calendar['id']])) {
362
+                    $calendars[$calendar['id']] = $calendar;
363
+                }
364
+            }
365
+            $result->closeCursor();
366
+
367
+            // query for shared calendars
368
+            $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
369
+            $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
370
+            $principals[] = $principalUri;
371
+
372
+            $fields = array_column($this->propertyMap, 0);
373
+            $fields = array_map(function (string $field) {
374
+                return 'a.' . $field;
375
+            }, $fields);
376
+            $fields[] = 'a.id';
377
+            $fields[] = 'a.uri';
378
+            $fields[] = 'a.synctoken';
379
+            $fields[] = 'a.components';
380
+            $fields[] = 'a.principaluri';
381
+            $fields[] = 'a.transparent';
382
+            $fields[] = 's.access';
383
+
384
+            $select = $this->db->getQueryBuilder();
385
+            $subSelect = $this->db->getQueryBuilder();
386
+
387
+            $subSelect->select('resourceid')
388
+                ->from('dav_shares', 'd')
389
+                ->where($subSelect->expr()->eq('d.access', $select->createNamedParameter(Backend::ACCESS_UNSHARED, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
390
+                ->andWhere($subSelect->expr()->eq('d.principaluri', $select->createNamedParameter($principalUri, IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR));
391
+
392
+            $select->select($fields)
393
+                ->from('dav_shares', 's')
394
+                ->join('s', 'calendars', 'a', $select->expr()->eq('s.resourceid', 'a.id', IQueryBuilder::PARAM_INT))
395
+                ->where($select->expr()->in('s.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
396
+                ->andWhere($select->expr()->eq('s.type', $select->createNamedParameter('calendar', IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR))
397
+                ->andWhere($select->expr()->notIn('a.id', $select->createFunction($subSelect->getSQL()), IQueryBuilder::PARAM_INT_ARRAY));
398
+
399
+            $results = $select->executeQuery();
400
+
401
+            $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
402
+            while ($row = $results->fetch()) {
403
+                $row['principaluri'] = (string)$row['principaluri'];
404
+                if ($row['principaluri'] === $principalUri) {
405
+                    continue;
406
+                }
407
+
408
+                $readOnly = (int)$row['access'] === Backend::ACCESS_READ;
409
+                if (isset($calendars[$row['id']])) {
410
+                    if ($readOnly) {
411
+                        // New share can not have more permissions than the old one.
412
+                        continue;
413
+                    }
414
+                    if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
415
+                        $calendars[$row['id']][$readOnlyPropertyName] === 0) {
416
+                        // Old share is already read-write, no more permissions can be gained
417
+                        continue;
418
+                    }
419
+                }
420
+
421
+                [, $name] = Uri\split($row['principaluri']);
422
+                $uri = $row['uri'] . '_shared_by_' . $name;
423
+                $row['displayname'] = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? ($name ?? '')) . ')';
424
+                $components = [];
425
+                if ($row['components']) {
426
+                    $components = explode(',', $row['components']);
427
+                }
428
+                $calendar = [
429
+                    'id' => $row['id'],
430
+                    'uri' => $uri,
431
+                    'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
432
+                    '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
433
+                    '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
434
+                    '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
435
+                    '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
436
+                    '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
437
+                    $readOnlyPropertyName => $readOnly,
438
+                ];
439
+
440
+                $calendar = $this->rowToCalendar($row, $calendar);
441
+                $calendar = $this->addOwnerPrincipalToCalendar($calendar);
442
+                $calendar = $this->addResourceTypeToCalendar($row, $calendar);
443
+
444
+                $calendars[$calendar['id']] = $calendar;
445
+            }
446
+            $result->closeCursor();
447
+
448
+            return array_values($calendars);
449
+        }, $this->db);
450
+    }
451
+
452
+    /**
453
+     * @param $principalUri
454
+     * @return array
455
+     */
456
+    public function getUsersOwnCalendars($principalUri) {
457
+        $principalUri = $this->convertPrincipal($principalUri, true);
458
+        $fields = array_column($this->propertyMap, 0);
459
+        $fields[] = 'id';
460
+        $fields[] = 'uri';
461
+        $fields[] = 'synctoken';
462
+        $fields[] = 'components';
463
+        $fields[] = 'principaluri';
464
+        $fields[] = 'transparent';
465
+        // Making fields a comma-delimited list
466
+        $query = $this->db->getQueryBuilder();
467
+        $query->select($fields)->from('calendars')
468
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
469
+            ->orderBy('calendarorder', 'ASC');
470
+        $stmt = $query->executeQuery();
471
+        $calendars = [];
472
+        while ($row = $stmt->fetch()) {
473
+            $row['principaluri'] = (string)$row['principaluri'];
474
+            $components = [];
475
+            if ($row['components']) {
476
+                $components = explode(',', $row['components']);
477
+            }
478
+            $calendar = [
479
+                'id' => $row['id'],
480
+                'uri' => $row['uri'],
481
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
482
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
483
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
484
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
485
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
486
+            ];
487
+
488
+            $calendar = $this->rowToCalendar($row, $calendar);
489
+            $calendar = $this->addOwnerPrincipalToCalendar($calendar);
490
+            $calendar = $this->addResourceTypeToCalendar($row, $calendar);
491
+
492
+            if (!isset($calendars[$calendar['id']])) {
493
+                $calendars[$calendar['id']] = $calendar;
494
+            }
495
+        }
496
+        $stmt->closeCursor();
497
+        return array_values($calendars);
498
+    }
499
+
500
+    /**
501
+     * @return array
502
+     */
503
+    public function getPublicCalendars() {
504
+        $fields = array_column($this->propertyMap, 0);
505
+        $fields[] = 'a.id';
506
+        $fields[] = 'a.uri';
507
+        $fields[] = 'a.synctoken';
508
+        $fields[] = 'a.components';
509
+        $fields[] = 'a.principaluri';
510
+        $fields[] = 'a.transparent';
511
+        $fields[] = 's.access';
512
+        $fields[] = 's.publicuri';
513
+        $calendars = [];
514
+        $query = $this->db->getQueryBuilder();
515
+        $result = $query->select($fields)
516
+            ->from('dav_shares', 's')
517
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
518
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
519
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
520
+            ->executeQuery();
521
+
522
+        while ($row = $result->fetch()) {
523
+            $row['principaluri'] = (string)$row['principaluri'];
524
+            [, $name] = Uri\split($row['principaluri']);
525
+            $row['displayname'] = $row['displayname'] . "($name)";
526
+            $components = [];
527
+            if ($row['components']) {
528
+                $components = explode(',', $row['components']);
529
+            }
530
+            $calendar = [
531
+                'id' => $row['id'],
532
+                'uri' => $row['publicuri'],
533
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
534
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
535
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
536
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
537
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
538
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
539
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
540
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
541
+            ];
542
+
543
+            $calendar = $this->rowToCalendar($row, $calendar);
544
+            $calendar = $this->addOwnerPrincipalToCalendar($calendar);
545
+            $calendar = $this->addResourceTypeToCalendar($row, $calendar);
546
+
547
+            if (!isset($calendars[$calendar['id']])) {
548
+                $calendars[$calendar['id']] = $calendar;
549
+            }
550
+        }
551
+        $result->closeCursor();
552
+
553
+        return array_values($calendars);
554
+    }
555
+
556
+    /**
557
+     * @param string $uri
558
+     * @return array
559
+     * @throws NotFound
560
+     */
561
+    public function getPublicCalendar($uri) {
562
+        $fields = array_column($this->propertyMap, 0);
563
+        $fields[] = 'a.id';
564
+        $fields[] = 'a.uri';
565
+        $fields[] = 'a.synctoken';
566
+        $fields[] = 'a.components';
567
+        $fields[] = 'a.principaluri';
568
+        $fields[] = 'a.transparent';
569
+        $fields[] = 's.access';
570
+        $fields[] = 's.publicuri';
571
+        $query = $this->db->getQueryBuilder();
572
+        $result = $query->select($fields)
573
+            ->from('dav_shares', 's')
574
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
575
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
576
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
577
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
578
+            ->executeQuery();
579
+
580
+        $row = $result->fetch();
581
+
582
+        $result->closeCursor();
583
+
584
+        if ($row === false) {
585
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
586
+        }
587
+
588
+        $row['principaluri'] = (string)$row['principaluri'];
589
+        [, $name] = Uri\split($row['principaluri']);
590
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
591
+        $components = [];
592
+        if ($row['components']) {
593
+            $components = explode(',', $row['components']);
594
+        }
595
+        $calendar = [
596
+            'id' => $row['id'],
597
+            'uri' => $row['publicuri'],
598
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
599
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
600
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
601
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
602
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
603
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
604
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
605
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
606
+        ];
607
+
608
+        $calendar = $this->rowToCalendar($row, $calendar);
609
+        $calendar = $this->addOwnerPrincipalToCalendar($calendar);
610
+        $calendar = $this->addResourceTypeToCalendar($row, $calendar);
611
+
612
+        return $calendar;
613
+    }
614
+
615
+    /**
616
+     * @param string $principal
617
+     * @param string $uri
618
+     * @return array|null
619
+     */
620
+    public function getCalendarByUri($principal, $uri) {
621
+        $fields = array_column($this->propertyMap, 0);
622
+        $fields[] = 'id';
623
+        $fields[] = 'uri';
624
+        $fields[] = 'synctoken';
625
+        $fields[] = 'components';
626
+        $fields[] = 'principaluri';
627
+        $fields[] = 'transparent';
628
+
629
+        // Making fields a comma-delimited list
630
+        $query = $this->db->getQueryBuilder();
631
+        $query->select($fields)->from('calendars')
632
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
633
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
634
+            ->setMaxResults(1);
635
+        $stmt = $query->executeQuery();
636
+
637
+        $row = $stmt->fetch();
638
+        $stmt->closeCursor();
639
+        if ($row === false) {
640
+            return null;
641
+        }
642
+
643
+        $row['principaluri'] = (string)$row['principaluri'];
644
+        $components = [];
645
+        if ($row['components']) {
646
+            $components = explode(',', $row['components']);
647
+        }
648
+
649
+        $calendar = [
650
+            'id' => $row['id'],
651
+            'uri' => $row['uri'],
652
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
653
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
654
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
655
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
656
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
657
+        ];
658
+
659
+        $calendar = $this->rowToCalendar($row, $calendar);
660
+        $calendar = $this->addOwnerPrincipalToCalendar($calendar);
661
+        $calendar = $this->addResourceTypeToCalendar($row, $calendar);
662
+
663
+        return $calendar;
664
+    }
665
+
666
+    /**
667
+     * @psalm-return CalendarInfo|null
668
+     * @return array|null
669
+     */
670
+    public function getCalendarById(int $calendarId): ?array {
671
+        $fields = array_column($this->propertyMap, 0);
672
+        $fields[] = 'id';
673
+        $fields[] = 'uri';
674
+        $fields[] = 'synctoken';
675
+        $fields[] = 'components';
676
+        $fields[] = 'principaluri';
677
+        $fields[] = 'transparent';
678
+
679
+        // Making fields a comma-delimited list
680
+        $query = $this->db->getQueryBuilder();
681
+        $query->select($fields)->from('calendars')
682
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
683
+            ->setMaxResults(1);
684
+        $stmt = $query->executeQuery();
685
+
686
+        $row = $stmt->fetch();
687
+        $stmt->closeCursor();
688
+        if ($row === false) {
689
+            return null;
690
+        }
691
+
692
+        $row['principaluri'] = (string)$row['principaluri'];
693
+        $components = [];
694
+        if ($row['components']) {
695
+            $components = explode(',', $row['components']);
696
+        }
697
+
698
+        $calendar = [
699
+            'id' => $row['id'],
700
+            'uri' => $row['uri'],
701
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
702
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
703
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?? 0,
704
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
705
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
706
+        ];
707
+
708
+        $calendar = $this->rowToCalendar($row, $calendar);
709
+        $calendar = $this->addOwnerPrincipalToCalendar($calendar);
710
+        $calendar = $this->addResourceTypeToCalendar($row, $calendar);
711
+
712
+        return $calendar;
713
+    }
714
+
715
+    /**
716
+     * @param $subscriptionId
717
+     */
718
+    public function getSubscriptionById($subscriptionId) {
719
+        $fields = array_column($this->subscriptionPropertyMap, 0);
720
+        $fields[] = 'id';
721
+        $fields[] = 'uri';
722
+        $fields[] = 'source';
723
+        $fields[] = 'synctoken';
724
+        $fields[] = 'principaluri';
725
+        $fields[] = 'lastmodified';
726
+
727
+        $query = $this->db->getQueryBuilder();
728
+        $query->select($fields)
729
+            ->from('calendarsubscriptions')
730
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
731
+            ->orderBy('calendarorder', 'asc');
732
+        $stmt = $query->executeQuery();
733
+
734
+        $row = $stmt->fetch();
735
+        $stmt->closeCursor();
736
+        if ($row === false) {
737
+            return null;
738
+        }
739
+
740
+        $row['principaluri'] = (string)$row['principaluri'];
741
+        $subscription = [
742
+            'id' => $row['id'],
743
+            'uri' => $row['uri'],
744
+            'principaluri' => $row['principaluri'],
745
+            'source' => $row['source'],
746
+            'lastmodified' => $row['lastmodified'],
747
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
748
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
749
+        ];
750
+
751
+        return $this->rowToSubscription($row, $subscription);
752
+    }
753
+
754
+    public function getSubscriptionByUri(string $principal, string $uri): ?array {
755
+        $fields = array_column($this->subscriptionPropertyMap, 0);
756
+        $fields[] = 'id';
757
+        $fields[] = 'uri';
758
+        $fields[] = 'source';
759
+        $fields[] = 'synctoken';
760
+        $fields[] = 'principaluri';
761
+        $fields[] = 'lastmodified';
762
+
763
+        $query = $this->db->getQueryBuilder();
764
+        $query->select($fields)
765
+            ->from('calendarsubscriptions')
766
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
767
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
768
+            ->setMaxResults(1);
769
+        $stmt = $query->executeQuery();
770
+
771
+        $row = $stmt->fetch();
772
+        $stmt->closeCursor();
773
+        if ($row === false) {
774
+            return null;
775
+        }
776
+
777
+        $row['principaluri'] = (string)$row['principaluri'];
778
+        $subscription = [
779
+            'id' => $row['id'],
780
+            'uri' => $row['uri'],
781
+            'principaluri' => $row['principaluri'],
782
+            'source' => $row['source'],
783
+            'lastmodified' => $row['lastmodified'],
784
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
785
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
786
+        ];
787
+
788
+        return $this->rowToSubscription($row, $subscription);
789
+    }
790
+
791
+    /**
792
+     * Creates a new calendar for a principal.
793
+     *
794
+     * If the creation was a success, an id must be returned that can be used to reference
795
+     * this calendar in other methods, such as updateCalendar.
796
+     *
797
+     * @param string $principalUri
798
+     * @param string $calendarUri
799
+     * @param array $properties
800
+     * @return int
801
+     *
802
+     * @throws CalendarException
803
+     */
804
+    public function createCalendar($principalUri, $calendarUri, array $properties) {
805
+        if (strlen($calendarUri) > 255) {
806
+            throw new CalendarException('URI too long. Calendar not created');
807
+        }
808
+
809
+        $values = [
810
+            'principaluri' => $this->convertPrincipal($principalUri, true),
811
+            'uri' => $calendarUri,
812
+            'synctoken' => 1,
813
+            'transparent' => 0,
814
+            'components' => 'VEVENT,VTODO,VJOURNAL',
815
+            'displayname' => $calendarUri
816
+        ];
817
+
818
+        // Default value
819
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
820
+        if (isset($properties[$sccs])) {
821
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
822
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
823
+            }
824
+            $values['components'] = implode(',', $properties[$sccs]->getValue());
825
+        } elseif (isset($properties['components'])) {
826
+            // Allow to provide components internally without having
827
+            // to create a SupportedCalendarComponentSet object
828
+            $values['components'] = $properties['components'];
829
+        }
830
+
831
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
832
+        if (isset($properties[$transp])) {
833
+            $values['transparent'] = (int)($properties[$transp]->getValue() === 'transparent');
834
+        }
835
+
836
+        foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
837
+            if (isset($properties[$xmlName])) {
838
+                $values[$dbName] = $properties[$xmlName];
839
+            }
840
+        }
841
+
842
+        [$calendarId, $calendarData] = $this->atomic(function () use ($values) {
843
+            $query = $this->db->getQueryBuilder();
844
+            $query->insert('calendars');
845
+            foreach ($values as $column => $value) {
846
+                $query->setValue($column, $query->createNamedParameter($value));
847
+            }
848
+            $query->executeStatement();
849
+            $calendarId = $query->getLastInsertId();
850
+
851
+            $calendarData = $this->getCalendarById($calendarId);
852
+            return [$calendarId, $calendarData];
853
+        }, $this->db);
854
+
855
+        $this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
856
+
857
+        return $calendarId;
858
+    }
859
+
860
+    /**
861
+     * Updates properties for a calendar.
862
+     *
863
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
864
+     * To do the actual updates, you must tell this object which properties
865
+     * you're going to process with the handle() method.
866
+     *
867
+     * Calling the handle method is like telling the PropPatch object "I
868
+     * promise I can handle updating this property".
869
+     *
870
+     * Read the PropPatch documentation for more info and examples.
871
+     *
872
+     * @param mixed $calendarId
873
+     * @param PropPatch $propPatch
874
+     * @return void
875
+     */
876
+    public function updateCalendar($calendarId, PropPatch $propPatch) {
877
+        $supportedProperties = array_keys($this->propertyMap);
878
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
879
+
880
+        $propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
881
+            $newValues = [];
882
+            foreach ($mutations as $propertyName => $propertyValue) {
883
+                switch ($propertyName) {
884
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
885
+                        $fieldName = 'transparent';
886
+                        $newValues[$fieldName] = (int)($propertyValue->getValue() === 'transparent');
887
+                        break;
888
+                    default:
889
+                        $fieldName = $this->propertyMap[$propertyName][0];
890
+                        $newValues[$fieldName] = $propertyValue;
891
+                        break;
892
+                }
893
+            }
894
+            [$calendarData, $shares] = $this->atomic(function () use ($calendarId, $newValues) {
895
+                $query = $this->db->getQueryBuilder();
896
+                $query->update('calendars');
897
+                foreach ($newValues as $fieldName => $value) {
898
+                    $query->set($fieldName, $query->createNamedParameter($value));
899
+                }
900
+                $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
901
+                $query->executeStatement();
902
+
903
+                $this->addChanges($calendarId, [''], 2);
904
+
905
+                $calendarData = $this->getCalendarById($calendarId);
906
+                $shares = $this->getShares($calendarId);
907
+                return [$calendarData, $shares];
908
+            }, $this->db);
909
+
910
+            $this->dispatcher->dispatchTyped(new CalendarUpdatedEvent($calendarId, $calendarData, $shares, $mutations));
911
+
912
+            return true;
913
+        });
914
+    }
915
+
916
+    /**
917
+     * Delete a calendar and all it's objects
918
+     *
919
+     * @param mixed $calendarId
920
+     * @return void
921
+     */
922
+    public function deleteCalendar($calendarId, bool $forceDeletePermanently = false) {
923
+        $this->atomic(function () use ($calendarId, $forceDeletePermanently): void {
924
+            // The calendar is deleted right away if this is either enforced by the caller
925
+            // or the special contacts birthday calendar or when the preference of an empty
926
+            // retention (0 seconds) is set, which signals a disabled trashbin.
927
+            $calendarData = $this->getCalendarById($calendarId);
928
+            $isBirthdayCalendar = isset($calendarData['uri']) && $calendarData['uri'] === BirthdayService::BIRTHDAY_CALENDAR_URI;
929
+            $trashbinDisabled = $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0';
930
+            if ($forceDeletePermanently || $isBirthdayCalendar || $trashbinDisabled) {
931
+                $calendarData = $this->getCalendarById($calendarId);
932
+                $shares = $this->getShares($calendarId);
933
+
934
+                $this->purgeCalendarInvitations($calendarId);
935
+
936
+                $qbDeleteCalendarObjectProps = $this->db->getQueryBuilder();
937
+                $qbDeleteCalendarObjectProps->delete($this->dbObjectPropertiesTable)
938
+                    ->where($qbDeleteCalendarObjectProps->expr()->eq('calendarid', $qbDeleteCalendarObjectProps->createNamedParameter($calendarId)))
939
+                    ->andWhere($qbDeleteCalendarObjectProps->expr()->eq('calendartype', $qbDeleteCalendarObjectProps->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
940
+                    ->executeStatement();
941
+
942
+                $qbDeleteCalendarObjects = $this->db->getQueryBuilder();
943
+                $qbDeleteCalendarObjects->delete('calendarobjects')
944
+                    ->where($qbDeleteCalendarObjects->expr()->eq('calendarid', $qbDeleteCalendarObjects->createNamedParameter($calendarId)))
945
+                    ->andWhere($qbDeleteCalendarObjects->expr()->eq('calendartype', $qbDeleteCalendarObjects->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
946
+                    ->executeStatement();
947
+
948
+                $qbDeleteCalendarChanges = $this->db->getQueryBuilder();
949
+                $qbDeleteCalendarChanges->delete('calendarchanges')
950
+                    ->where($qbDeleteCalendarChanges->expr()->eq('calendarid', $qbDeleteCalendarChanges->createNamedParameter($calendarId)))
951
+                    ->andWhere($qbDeleteCalendarChanges->expr()->eq('calendartype', $qbDeleteCalendarChanges->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
952
+                    ->executeStatement();
953
+
954
+                $this->calendarSharingBackend->deleteAllShares($calendarId);
955
+
956
+                $qbDeleteCalendar = $this->db->getQueryBuilder();
957
+                $qbDeleteCalendar->delete('calendars')
958
+                    ->where($qbDeleteCalendar->expr()->eq('id', $qbDeleteCalendar->createNamedParameter($calendarId)))
959
+                    ->executeStatement();
960
+
961
+                // Only dispatch if we actually deleted anything
962
+                if ($calendarData) {
963
+                    $this->dispatcher->dispatchTyped(new CalendarDeletedEvent($calendarId, $calendarData, $shares));
964
+                }
965
+            } else {
966
+                $qbMarkCalendarDeleted = $this->db->getQueryBuilder();
967
+                $qbMarkCalendarDeleted->update('calendars')
968
+                    ->set('deleted_at', $qbMarkCalendarDeleted->createNamedParameter(time()))
969
+                    ->where($qbMarkCalendarDeleted->expr()->eq('id', $qbMarkCalendarDeleted->createNamedParameter($calendarId)))
970
+                    ->executeStatement();
971
+
972
+                $calendarData = $this->getCalendarById($calendarId);
973
+                $shares = $this->getShares($calendarId);
974
+                if ($calendarData) {
975
+                    $this->dispatcher->dispatchTyped(new CalendarMovedToTrashEvent(
976
+                        $calendarId,
977
+                        $calendarData,
978
+                        $shares
979
+                    ));
980
+                }
981
+            }
982
+        }, $this->db);
983
+    }
984
+
985
+    public function restoreCalendar(int $id): void {
986
+        $this->atomic(function () use ($id): void {
987
+            $qb = $this->db->getQueryBuilder();
988
+            $update = $qb->update('calendars')
989
+                ->set('deleted_at', $qb->createNamedParameter(null))
990
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
991
+            $update->executeStatement();
992
+
993
+            $calendarData = $this->getCalendarById($id);
994
+            $shares = $this->getShares($id);
995
+            if ($calendarData === null) {
996
+                throw new RuntimeException('Calendar data that was just written can\'t be read back. Check your database configuration.');
997
+            }
998
+            $this->dispatcher->dispatchTyped(new CalendarRestoredEvent(
999
+                $id,
1000
+                $calendarData,
1001
+                $shares
1002
+            ));
1003
+        }, $this->db);
1004
+    }
1005
+
1006
+    /**
1007
+     * Returns all calendar entries as a stream of data
1008
+     *
1009
+     * @since 32.0.0
1010
+     *
1011
+     * @return Generator<array>
1012
+     */
1013
+    public function exportCalendar(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR, ?CalendarExportOptions $options = null): Generator {
1014
+        // extract options
1015
+        $rangeStart = $options?->getRangeStart();
1016
+        $rangeCount = $options?->getRangeCount();
1017
+        // construct query
1018
+        $qb = $this->db->getQueryBuilder();
1019
+        $qb->select('*')
1020
+            ->from('calendarobjects')
1021
+            ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1022
+            ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1023
+            ->andWhere($qb->expr()->isNull('deleted_at'));
1024
+        if ($rangeStart !== null) {
1025
+            $qb->andWhere($qb->expr()->gt('uid', $qb->createNamedParameter($rangeStart)));
1026
+        }
1027
+        if ($rangeCount !== null) {
1028
+            $qb->setMaxResults($rangeCount);
1029
+        }
1030
+        if ($rangeStart !== null || $rangeCount !== null) {
1031
+            $qb->orderBy('uid', 'ASC');
1032
+        }
1033
+        $rs = $qb->executeQuery();
1034
+        // iterate through results
1035
+        try {
1036
+            while (($row = $rs->fetch()) !== false) {
1037
+                yield $row;
1038
+            }
1039
+        } finally {
1040
+            $rs->closeCursor();
1041
+        }
1042
+    }
1043 1043
 	
1044
-	/**
1045
-	 * Returns all calendar objects with limited metadata for a calendar
1046
-	 *
1047
-	 * Every item contains an array with the following keys:
1048
-	 *   * id - the table row id
1049
-	 *   * etag - An arbitrary string
1050
-	 *   * uri - a unique key which will be used to construct the uri. This can
1051
-	 *     be any arbitrary string.
1052
-	 *   * calendardata - The iCalendar-compatible calendar data
1053
-	 *
1054
-	 * @param mixed $calendarId
1055
-	 * @param int $calendarType
1056
-	 * @return array
1057
-	 */
1058
-	public function getLimitedCalendarObjects(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1059
-		$query = $this->db->getQueryBuilder();
1060
-		$query->select(['id','uid', 'etag', 'uri', 'calendardata'])
1061
-			->from('calendarobjects')
1062
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1063
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1064
-			->andWhere($query->expr()->isNull('deleted_at'));
1065
-		$stmt = $query->executeQuery();
1066
-
1067
-		$result = [];
1068
-		while (($row = $stmt->fetch()) !== false) {
1069
-			$result[$row['uid']] = [
1070
-				'id' => $row['id'],
1071
-				'etag' => $row['etag'],
1072
-				'uri' => $row['uri'],
1073
-				'calendardata' => $row['calendardata'],
1074
-			];
1075
-		}
1076
-		$stmt->closeCursor();
1077
-
1078
-		return $result;
1079
-	}
1080
-
1081
-	/**
1082
-	 * Delete all of an user's shares
1083
-	 *
1084
-	 * @param string $principaluri
1085
-	 * @return void
1086
-	 */
1087
-	public function deleteAllSharesByUser($principaluri) {
1088
-		$this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
1089
-	}
1090
-
1091
-	/**
1092
-	 * Returns all calendar objects within a calendar.
1093
-	 *
1094
-	 * Every item contains an array with the following keys:
1095
-	 *   * calendardata - The iCalendar-compatible calendar data
1096
-	 *   * uri - a unique key which will be used to construct the uri. This can
1097
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
1098
-	 *     good idea. This is only the basename, or filename, not the full
1099
-	 *     path.
1100
-	 *   * lastmodified - a timestamp of the last modification time
1101
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
1102
-	 *   '"abcdef"')
1103
-	 *   * size - The size of the calendar objects, in bytes.
1104
-	 *   * component - optional, a string containing the type of object, such
1105
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
1106
-	 *     the Content-Type header.
1107
-	 *
1108
-	 * Note that the etag is optional, but it's highly encouraged to return for
1109
-	 * speed reasons.
1110
-	 *
1111
-	 * The calendardata is also optional. If it's not returned
1112
-	 * 'getCalendarObject' will be called later, which *is* expected to return
1113
-	 * calendardata.
1114
-	 *
1115
-	 * If neither etag or size are specified, the calendardata will be
1116
-	 * used/fetched to determine these numbers. If both are specified the
1117
-	 * amount of times this is needed is reduced by a great degree.
1118
-	 *
1119
-	 * @param mixed $calendarId
1120
-	 * @param int $calendarType
1121
-	 * @return array
1122
-	 */
1123
-	public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1124
-		$query = $this->db->getQueryBuilder();
1125
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
1126
-			->from('calendarobjects')
1127
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1128
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1129
-			->andWhere($query->expr()->isNull('deleted_at'));
1130
-		$stmt = $query->executeQuery();
1131
-
1132
-		$result = [];
1133
-		while (($row = $stmt->fetch()) !== false) {
1134
-			$result[] = [
1135
-				'id' => $row['id'],
1136
-				'uri' => $row['uri'],
1137
-				'lastmodified' => $row['lastmodified'],
1138
-				'etag' => '"' . $row['etag'] . '"',
1139
-				'calendarid' => $row['calendarid'],
1140
-				'size' => (int)$row['size'],
1141
-				'component' => strtolower($row['componenttype']),
1142
-				'classification' => (int)$row['classification']
1143
-			];
1144
-		}
1145
-		$stmt->closeCursor();
1146
-
1147
-		return $result;
1148
-	}
1149
-
1150
-	public function getDeletedCalendarObjects(int $deletedBefore): array {
1151
-		$query = $this->db->getQueryBuilder();
1152
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.calendartype', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1153
-			->from('calendarobjects', 'co')
1154
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1155
-			->where($query->expr()->isNotNull('co.deleted_at'))
1156
-			->andWhere($query->expr()->lt('co.deleted_at', $query->createNamedParameter($deletedBefore)));
1157
-		$stmt = $query->executeQuery();
1158
-
1159
-		$result = [];
1160
-		while (($row = $stmt->fetch()) !== false) {
1161
-			$result[] = [
1162
-				'id' => $row['id'],
1163
-				'uri' => $row['uri'],
1164
-				'lastmodified' => $row['lastmodified'],
1165
-				'etag' => '"' . $row['etag'] . '"',
1166
-				'calendarid' => (int)$row['calendarid'],
1167
-				'calendartype' => (int)$row['calendartype'],
1168
-				'size' => (int)$row['size'],
1169
-				'component' => strtolower($row['componenttype']),
1170
-				'classification' => (int)$row['classification'],
1171
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1172
-			];
1173
-		}
1174
-		$stmt->closeCursor();
1175
-
1176
-		return $result;
1177
-	}
1178
-
1179
-	/**
1180
-	 * Return all deleted calendar objects by the given principal that are not
1181
-	 * in deleted calendars.
1182
-	 *
1183
-	 * @param string $principalUri
1184
-	 * @return array
1185
-	 * @throws Exception
1186
-	 */
1187
-	public function getDeletedCalendarObjectsByPrincipal(string $principalUri): array {
1188
-		$query = $this->db->getQueryBuilder();
1189
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1190
-			->selectAlias('c.uri', 'calendaruri')
1191
-			->from('calendarobjects', 'co')
1192
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1193
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1194
-			->andWhere($query->expr()->isNotNull('co.deleted_at'))
1195
-			->andWhere($query->expr()->isNull('c.deleted_at'));
1196
-		$stmt = $query->executeQuery();
1197
-
1198
-		$result = [];
1199
-		while ($row = $stmt->fetch()) {
1200
-			$result[] = [
1201
-				'id' => $row['id'],
1202
-				'uri' => $row['uri'],
1203
-				'lastmodified' => $row['lastmodified'],
1204
-				'etag' => '"' . $row['etag'] . '"',
1205
-				'calendarid' => $row['calendarid'],
1206
-				'calendaruri' => $row['calendaruri'],
1207
-				'size' => (int)$row['size'],
1208
-				'component' => strtolower($row['componenttype']),
1209
-				'classification' => (int)$row['classification'],
1210
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1211
-			];
1212
-		}
1213
-		$stmt->closeCursor();
1214
-
1215
-		return $result;
1216
-	}
1217
-
1218
-	/**
1219
-	 * Returns information from a single calendar object, based on it's object
1220
-	 * uri.
1221
-	 *
1222
-	 * The object uri is only the basename, or filename and not a full path.
1223
-	 *
1224
-	 * The returned array must have the same keys as getCalendarObjects. The
1225
-	 * 'calendardata' object is required here though, while it's not required
1226
-	 * for getCalendarObjects.
1227
-	 *
1228
-	 * This method must return null if the object did not exist.
1229
-	 *
1230
-	 * @param mixed $calendarId
1231
-	 * @param string $objectUri
1232
-	 * @param int $calendarType
1233
-	 * @return array|null
1234
-	 */
1235
-	public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1236
-		$key = $calendarId . '::' . $objectUri . '::' . $calendarType;
1237
-		if (isset($this->cachedObjects[$key])) {
1238
-			return $this->cachedObjects[$key];
1239
-		}
1240
-		$query = $this->db->getQueryBuilder();
1241
-		$query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1242
-			->from('calendarobjects')
1243
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1244
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1245
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1246
-		$stmt = $query->executeQuery();
1247
-		$row = $stmt->fetch();
1248
-		$stmt->closeCursor();
1249
-
1250
-		if (!$row) {
1251
-			return null;
1252
-		}
1253
-
1254
-		$object = $this->rowToCalendarObject($row);
1255
-		$this->cachedObjects[$key] = $object;
1256
-		return $object;
1257
-	}
1258
-
1259
-	private function rowToCalendarObject(array $row): array {
1260
-		return [
1261
-			'id' => $row['id'],
1262
-			'uri' => $row['uri'],
1263
-			'uid' => $row['uid'],
1264
-			'lastmodified' => $row['lastmodified'],
1265
-			'etag' => '"' . $row['etag'] . '"',
1266
-			'calendarid' => $row['calendarid'],
1267
-			'size' => (int)$row['size'],
1268
-			'calendardata' => $this->readBlob($row['calendardata']),
1269
-			'component' => strtolower($row['componenttype']),
1270
-			'classification' => (int)$row['classification'],
1271
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1272
-		];
1273
-	}
1274
-
1275
-	/**
1276
-	 * Returns a list of calendar objects.
1277
-	 *
1278
-	 * This method should work identical to getCalendarObject, but instead
1279
-	 * return all the calendar objects in the list as an array.
1280
-	 *
1281
-	 * If the backend supports this, it may allow for some speed-ups.
1282
-	 *
1283
-	 * @param mixed $calendarId
1284
-	 * @param string[] $uris
1285
-	 * @param int $calendarType
1286
-	 * @return array
1287
-	 */
1288
-	public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1289
-		if (empty($uris)) {
1290
-			return [];
1291
-		}
1292
-
1293
-		$chunks = array_chunk($uris, 100);
1294
-		$objects = [];
1295
-
1296
-		$query = $this->db->getQueryBuilder();
1297
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1298
-			->from('calendarobjects')
1299
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1300
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1301
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1302
-			->andWhere($query->expr()->isNull('deleted_at'));
1303
-
1304
-		foreach ($chunks as $uris) {
1305
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1306
-			$result = $query->executeQuery();
1307
-
1308
-			while ($row = $result->fetch()) {
1309
-				$objects[] = [
1310
-					'id' => $row['id'],
1311
-					'uri' => $row['uri'],
1312
-					'lastmodified' => $row['lastmodified'],
1313
-					'etag' => '"' . $row['etag'] . '"',
1314
-					'calendarid' => $row['calendarid'],
1315
-					'size' => (int)$row['size'],
1316
-					'calendardata' => $this->readBlob($row['calendardata']),
1317
-					'component' => strtolower($row['componenttype']),
1318
-					'classification' => (int)$row['classification']
1319
-				];
1320
-			}
1321
-			$result->closeCursor();
1322
-		}
1323
-
1324
-		return $objects;
1325
-	}
1326
-
1327
-	/**
1328
-	 * Creates a new calendar object.
1329
-	 *
1330
-	 * The object uri is only the basename, or filename and not a full path.
1331
-	 *
1332
-	 * It is possible return an etag from this function, which will be used in
1333
-	 * the response to this PUT request. Note that the ETag must be surrounded
1334
-	 * by double-quotes.
1335
-	 *
1336
-	 * However, you should only really return this ETag if you don't mangle the
1337
-	 * calendar-data. If the result of a subsequent GET to this object is not
1338
-	 * the exact same as this request body, you should omit the ETag.
1339
-	 *
1340
-	 * @param mixed $calendarId
1341
-	 * @param string $objectUri
1342
-	 * @param string $calendarData
1343
-	 * @param int $calendarType
1344
-	 * @return string
1345
-	 */
1346
-	public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1347
-		$this->cachedObjects = [];
1348
-		$extraData = $this->getDenormalizedData($calendarData);
1349
-
1350
-		return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1351
-			// Try to detect duplicates
1352
-			$qb = $this->db->getQueryBuilder();
1353
-			$qb->select($qb->func()->count('*'))
1354
-				->from('calendarobjects')
1355
-				->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1356
-				->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($extraData['uid'])))
1357
-				->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1358
-				->andWhere($qb->expr()->isNull('deleted_at'));
1359
-			$result = $qb->executeQuery();
1360
-			$count = (int)$result->fetchOne();
1361
-			$result->closeCursor();
1362
-
1363
-			if ($count !== 0) {
1364
-				throw new BadRequest('Calendar object with uid already exists in this calendar collection.');
1365
-			}
1366
-			// For a more specific error message we also try to explicitly look up the UID but as a deleted entry
1367
-			$qbDel = $this->db->getQueryBuilder();
1368
-			$qbDel->select('*')
1369
-				->from('calendarobjects')
1370
-				->where($qbDel->expr()->eq('calendarid', $qbDel->createNamedParameter($calendarId)))
1371
-				->andWhere($qbDel->expr()->eq('uid', $qbDel->createNamedParameter($extraData['uid'])))
1372
-				->andWhere($qbDel->expr()->eq('calendartype', $qbDel->createNamedParameter($calendarType)))
1373
-				->andWhere($qbDel->expr()->isNotNull('deleted_at'));
1374
-			$result = $qbDel->executeQuery();
1375
-			$found = $result->fetch();
1376
-			$result->closeCursor();
1377
-			if ($found !== false) {
1378
-				// the object existed previously but has been deleted
1379
-				// remove the trashbin entry and continue as if it was a new object
1380
-				$this->deleteCalendarObject($calendarId, $found['uri']);
1381
-			}
1382
-
1383
-			$query = $this->db->getQueryBuilder();
1384
-			$query->insert('calendarobjects')
1385
-				->values([
1386
-					'calendarid' => $query->createNamedParameter($calendarId),
1387
-					'uri' => $query->createNamedParameter($objectUri),
1388
-					'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1389
-					'lastmodified' => $query->createNamedParameter(time()),
1390
-					'etag' => $query->createNamedParameter($extraData['etag']),
1391
-					'size' => $query->createNamedParameter($extraData['size']),
1392
-					'componenttype' => $query->createNamedParameter($extraData['componentType']),
1393
-					'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1394
-					'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1395
-					'classification' => $query->createNamedParameter($extraData['classification']),
1396
-					'uid' => $query->createNamedParameter($extraData['uid']),
1397
-					'calendartype' => $query->createNamedParameter($calendarType),
1398
-				])
1399
-				->executeStatement();
1400
-
1401
-			$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1402
-			$this->addChanges($calendarId, [$objectUri], 1, $calendarType);
1403
-
1404
-			$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1405
-			assert($objectRow !== null);
1406
-
1407
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1408
-				$calendarRow = $this->getCalendarById($calendarId);
1409
-				$shares = $this->getShares($calendarId);
1410
-
1411
-				$this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1412
-			} else {
1413
-				$subscriptionRow = $this->getSubscriptionById($calendarId);
1414
-
1415
-				$this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1416
-			}
1417
-
1418
-			return '"' . $extraData['etag'] . '"';
1419
-		}, $this->db);
1420
-	}
1421
-
1422
-	/**
1423
-	 * Updates an existing calendarobject, based on it's uri.
1424
-	 *
1425
-	 * The object uri is only the basename, or filename and not a full path.
1426
-	 *
1427
-	 * It is possible return an etag from this function, which will be used in
1428
-	 * the response to this PUT request. Note that the ETag must be surrounded
1429
-	 * by double-quotes.
1430
-	 *
1431
-	 * However, you should only really return this ETag if you don't mangle the
1432
-	 * calendar-data. If the result of a subsequent GET to this object is not
1433
-	 * the exact same as this request body, you should omit the ETag.
1434
-	 *
1435
-	 * @param mixed $calendarId
1436
-	 * @param string $objectUri
1437
-	 * @param string $calendarData
1438
-	 * @param int $calendarType
1439
-	 * @return string
1440
-	 */
1441
-	public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1442
-		$this->cachedObjects = [];
1443
-		$extraData = $this->getDenormalizedData($calendarData);
1444
-
1445
-		return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1446
-			$query = $this->db->getQueryBuilder();
1447
-			$query->update('calendarobjects')
1448
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1449
-				->set('lastmodified', $query->createNamedParameter(time()))
1450
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1451
-				->set('size', $query->createNamedParameter($extraData['size']))
1452
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1453
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1454
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1455
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1456
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1457
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1458
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1459
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1460
-				->executeStatement();
1461
-
1462
-			$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1463
-			$this->addChanges($calendarId, [$objectUri], 2, $calendarType);
1464
-
1465
-			$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1466
-			if (is_array($objectRow)) {
1467
-				if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1468
-					$calendarRow = $this->getCalendarById($calendarId);
1469
-					$shares = $this->getShares($calendarId);
1470
-
1471
-					$this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1472
-				} else {
1473
-					$subscriptionRow = $this->getSubscriptionById($calendarId);
1474
-
1475
-					$this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1476
-				}
1477
-			}
1478
-
1479
-			return '"' . $extraData['etag'] . '"';
1480
-		}, $this->db);
1481
-	}
1482
-
1483
-	/**
1484
-	 * Moves a calendar object from calendar to calendar.
1485
-	 *
1486
-	 * @param string $sourcePrincipalUri
1487
-	 * @param int $sourceObjectId
1488
-	 * @param string $targetPrincipalUri
1489
-	 * @param int $targetCalendarId
1490
-	 * @param string $tragetObjectUri
1491
-	 * @param int $calendarType
1492
-	 * @return bool
1493
-	 * @throws Exception
1494
-	 */
1495
-	public function moveCalendarObject(string $sourcePrincipalUri, int $sourceObjectId, string $targetPrincipalUri, int $targetCalendarId, string $tragetObjectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR): bool {
1496
-		$this->cachedObjects = [];
1497
-		return $this->atomic(function () use ($sourcePrincipalUri, $sourceObjectId, $targetPrincipalUri, $targetCalendarId, $tragetObjectUri, $calendarType) {
1498
-			$object = $this->getCalendarObjectById($sourcePrincipalUri, $sourceObjectId);
1499
-			if (empty($object)) {
1500
-				return false;
1501
-			}
1502
-
1503
-			$sourceCalendarId = $object['calendarid'];
1504
-			$sourceObjectUri = $object['uri'];
1505
-
1506
-			$query = $this->db->getQueryBuilder();
1507
-			$query->update('calendarobjects')
1508
-				->set('calendarid', $query->createNamedParameter($targetCalendarId, IQueryBuilder::PARAM_INT))
1509
-				->set('uri', $query->createNamedParameter($tragetObjectUri, IQueryBuilder::PARAM_STR))
1510
-				->where($query->expr()->eq('id', $query->createNamedParameter($sourceObjectId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
1511
-				->executeStatement();
1512
-
1513
-			$this->purgeProperties($sourceCalendarId, $sourceObjectId);
1514
-			$this->updateProperties($targetCalendarId, $tragetObjectUri, $object['calendardata'], $calendarType);
1515
-
1516
-			$this->addChanges($sourceCalendarId, [$sourceObjectUri], 3, $calendarType);
1517
-			$this->addChanges($targetCalendarId, [$tragetObjectUri], 1, $calendarType);
1518
-
1519
-			$object = $this->getCalendarObjectById($targetPrincipalUri, $sourceObjectId);
1520
-			// Calendar Object wasn't found - possibly because it was deleted in the meantime by a different client
1521
-			if (empty($object)) {
1522
-				return false;
1523
-			}
1524
-
1525
-			$targetCalendarRow = $this->getCalendarById($targetCalendarId);
1526
-			// the calendar this event is being moved to does not exist any longer
1527
-			if (empty($targetCalendarRow)) {
1528
-				return false;
1529
-			}
1530
-
1531
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1532
-				$sourceShares = $this->getShares($sourceCalendarId);
1533
-				$targetShares = $this->getShares($targetCalendarId);
1534
-				$sourceCalendarRow = $this->getCalendarById($sourceCalendarId);
1535
-				$this->dispatcher->dispatchTyped(new CalendarObjectMovedEvent($sourceCalendarId, $sourceCalendarRow, $targetCalendarId, $targetCalendarRow, $sourceShares, $targetShares, $object));
1536
-			}
1537
-			return true;
1538
-		}, $this->db);
1539
-	}
1540
-
1541
-	/**
1542
-	 * Deletes an existing calendar object.
1543
-	 *
1544
-	 * The object uri is only the basename, or filename and not a full path.
1545
-	 *
1546
-	 * @param mixed $calendarId
1547
-	 * @param string $objectUri
1548
-	 * @param int $calendarType
1549
-	 * @param bool $forceDeletePermanently
1550
-	 * @return void
1551
-	 */
1552
-	public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
1553
-		$this->cachedObjects = [];
1554
-		$this->atomic(function () use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently): void {
1555
-			$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1556
-
1557
-			if ($data === null) {
1558
-				// Nothing to delete
1559
-				return;
1560
-			}
1561
-
1562
-			if ($forceDeletePermanently || $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0') {
1563
-				$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1564
-				$stmt->execute([$calendarId, $objectUri, $calendarType]);
1565
-
1566
-				$this->purgeProperties($calendarId, $data['id']);
1567
-
1568
-				$this->purgeObjectInvitations($data['uid']);
1569
-
1570
-				if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1571
-					$calendarRow = $this->getCalendarById($calendarId);
1572
-					$shares = $this->getShares($calendarId);
1573
-
1574
-					$this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent($calendarId, $calendarRow, $shares, $data));
1575
-				} else {
1576
-					$subscriptionRow = $this->getSubscriptionById($calendarId);
1577
-
1578
-					$this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent($calendarId, $subscriptionRow, [], $data));
1579
-				}
1580
-			} else {
1581
-				$pathInfo = pathinfo($data['uri']);
1582
-				if (!empty($pathInfo['extension'])) {
1583
-					// Append a suffix to "free" the old URI for recreation
1584
-					$newUri = sprintf(
1585
-						'%s-deleted.%s',
1586
-						$pathInfo['filename'],
1587
-						$pathInfo['extension']
1588
-					);
1589
-				} else {
1590
-					$newUri = sprintf(
1591
-						'%s-deleted',
1592
-						$pathInfo['filename']
1593
-					);
1594
-				}
1595
-
1596
-				// Try to detect conflicts before the DB does
1597
-				// As unlikely as it seems, this can happen when the user imports, then deletes, imports and deletes again
1598
-				$newObject = $this->getCalendarObject($calendarId, $newUri, $calendarType);
1599
-				if ($newObject !== null) {
1600
-					throw new Forbidden("A calendar object with URI $newUri already exists in calendar $calendarId, therefore this object can't be moved into the trashbin");
1601
-				}
1602
-
1603
-				$qb = $this->db->getQueryBuilder();
1604
-				$markObjectDeletedQuery = $qb->update('calendarobjects')
1605
-					->set('deleted_at', $qb->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
1606
-					->set('uri', $qb->createNamedParameter($newUri))
1607
-					->where(
1608
-						$qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
1609
-						$qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
1610
-						$qb->expr()->eq('uri', $qb->createNamedParameter($objectUri))
1611
-					);
1612
-				$markObjectDeletedQuery->executeStatement();
1613
-
1614
-				$calendarData = $this->getCalendarById($calendarId);
1615
-				if ($calendarData !== null) {
1616
-					$this->dispatcher->dispatchTyped(
1617
-						new CalendarObjectMovedToTrashEvent(
1618
-							$calendarId,
1619
-							$calendarData,
1620
-							$this->getShares($calendarId),
1621
-							$data
1622
-						)
1623
-					);
1624
-				}
1625
-			}
1626
-
1627
-			$this->addChanges($calendarId, [$objectUri], 3, $calendarType);
1628
-		}, $this->db);
1629
-	}
1630
-
1631
-	/**
1632
-	 * @param mixed $objectData
1633
-	 *
1634
-	 * @throws Forbidden
1635
-	 */
1636
-	public function restoreCalendarObject(array $objectData): void {
1637
-		$this->cachedObjects = [];
1638
-		$this->atomic(function () use ($objectData): void {
1639
-			$id = (int)$objectData['id'];
1640
-			$restoreUri = str_replace('-deleted.ics', '.ics', $objectData['uri']);
1641
-			$targetObject = $this->getCalendarObject(
1642
-				$objectData['calendarid'],
1643
-				$restoreUri
1644
-			);
1645
-			if ($targetObject !== null) {
1646
-				throw new Forbidden("Can not restore calendar $id because a calendar object with the URI $restoreUri already exists");
1647
-			}
1648
-
1649
-			$qb = $this->db->getQueryBuilder();
1650
-			$update = $qb->update('calendarobjects')
1651
-				->set('uri', $qb->createNamedParameter($restoreUri))
1652
-				->set('deleted_at', $qb->createNamedParameter(null))
1653
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1654
-			$update->executeStatement();
1655
-
1656
-			// Make sure this change is tracked in the changes table
1657
-			$qb2 = $this->db->getQueryBuilder();
1658
-			$selectObject = $qb2->select('calendardata', 'uri', 'calendarid', 'calendartype')
1659
-				->selectAlias('componenttype', 'component')
1660
-				->from('calendarobjects')
1661
-				->where($qb2->expr()->eq('id', $qb2->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1662
-			$result = $selectObject->executeQuery();
1663
-			$row = $result->fetch();
1664
-			$result->closeCursor();
1665
-			if ($row === false) {
1666
-				// Welp, this should possibly not have happened, but let's ignore
1667
-				return;
1668
-			}
1669
-			$this->addChanges($row['calendarid'], [$row['uri']], 1, (int)$row['calendartype']);
1670
-
1671
-			$calendarRow = $this->getCalendarById((int)$row['calendarid']);
1672
-			if ($calendarRow === null) {
1673
-				throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
1674
-			}
1675
-			$this->dispatcher->dispatchTyped(
1676
-				new CalendarObjectRestoredEvent(
1677
-					(int)$objectData['calendarid'],
1678
-					$calendarRow,
1679
-					$this->getShares((int)$row['calendarid']),
1680
-					$row
1681
-				)
1682
-			);
1683
-		}, $this->db);
1684
-	}
1685
-
1686
-	/**
1687
-	 * Performs a calendar-query on the contents of this calendar.
1688
-	 *
1689
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1690
-	 * calendar-query it is possible for a client to request a specific set of
1691
-	 * object, based on contents of iCalendar properties, date-ranges and
1692
-	 * iCalendar component types (VTODO, VEVENT).
1693
-	 *
1694
-	 * This method should just return a list of (relative) urls that match this
1695
-	 * query.
1696
-	 *
1697
-	 * The list of filters are specified as an array. The exact array is
1698
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1699
-	 *
1700
-	 * Note that it is extremely likely that getCalendarObject for every path
1701
-	 * returned from this method will be called almost immediately after. You
1702
-	 * may want to anticipate this to speed up these requests.
1703
-	 *
1704
-	 * This method provides a default implementation, which parses *all* the
1705
-	 * iCalendar objects in the specified calendar.
1706
-	 *
1707
-	 * This default may well be good enough for personal use, and calendars
1708
-	 * that aren't very large. But if you anticipate high usage, big calendars
1709
-	 * or high loads, you are strongly advised to optimize certain paths.
1710
-	 *
1711
-	 * The best way to do so is override this method and to optimize
1712
-	 * specifically for 'common filters'.
1713
-	 *
1714
-	 * Requests that are extremely common are:
1715
-	 *   * requests for just VEVENTS
1716
-	 *   * requests for just VTODO
1717
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1718
-	 *
1719
-	 * ..and combinations of these requests. It may not be worth it to try to
1720
-	 * handle every possible situation and just rely on the (relatively
1721
-	 * easy to use) CalendarQueryValidator to handle the rest.
1722
-	 *
1723
-	 * Note that especially time-range-filters may be difficult to parse. A
1724
-	 * time-range filter specified on a VEVENT must for instance also handle
1725
-	 * recurrence rules correctly.
1726
-	 * A good example of how to interpret all these filters can also simply
1727
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1728
-	 * as possible, so it gives you a good idea on what type of stuff you need
1729
-	 * to think of.
1730
-	 *
1731
-	 * @param mixed $calendarId
1732
-	 * @param array $filters
1733
-	 * @param int $calendarType
1734
-	 * @return array
1735
-	 */
1736
-	public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1737
-		$componentType = null;
1738
-		$requirePostFilter = true;
1739
-		$timeRange = null;
1740
-
1741
-		// if no filters were specified, we don't need to filter after a query
1742
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1743
-			$requirePostFilter = false;
1744
-		}
1745
-
1746
-		// Figuring out if there's a component filter
1747
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1748
-			$componentType = $filters['comp-filters'][0]['name'];
1749
-
1750
-			// Checking if we need post-filters
1751
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1752
-				$requirePostFilter = false;
1753
-			}
1754
-			// There was a time-range filter
1755
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
1756
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1757
-
1758
-				// If start time OR the end time is not specified, we can do a
1759
-				// 100% accurate mysql query.
1760
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1761
-					$requirePostFilter = false;
1762
-				}
1763
-			}
1764
-		}
1765
-		$query = $this->db->getQueryBuilder();
1766
-		$query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1767
-			->from('calendarobjects')
1768
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1769
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1770
-			->andWhere($query->expr()->isNull('deleted_at'));
1771
-
1772
-		if ($componentType) {
1773
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1774
-		}
1775
-
1776
-		if ($timeRange && $timeRange['start']) {
1777
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1778
-		}
1779
-		if ($timeRange && $timeRange['end']) {
1780
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1781
-		}
1782
-
1783
-		$stmt = $query->executeQuery();
1784
-
1785
-		$result = [];
1786
-		while ($row = $stmt->fetch()) {
1787
-			// if we leave it as a blob we can't read it both from the post filter and the rowToCalendarObject
1788
-			if (isset($row['calendardata'])) {
1789
-				$row['calendardata'] = $this->readBlob($row['calendardata']);
1790
-			}
1791
-
1792
-			if ($requirePostFilter) {
1793
-				// validateFilterForObject will parse the calendar data
1794
-				// catch parsing errors
1795
-				try {
1796
-					$matches = $this->validateFilterForObject($row, $filters);
1797
-				} catch (ParseException $ex) {
1798
-					$this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1799
-						'app' => 'dav',
1800
-						'exception' => $ex,
1801
-					]);
1802
-					continue;
1803
-				} catch (InvalidDataException $ex) {
1804
-					$this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1805
-						'app' => 'dav',
1806
-						'exception' => $ex,
1807
-					]);
1808
-					continue;
1809
-				} catch (MaxInstancesExceededException $ex) {
1810
-					$this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
1811
-						'app' => 'dav',
1812
-						'exception' => $ex,
1813
-					]);
1814
-					continue;
1815
-				}
1816
-
1817
-				if (!$matches) {
1818
-					continue;
1819
-				}
1820
-			}
1821
-			$result[] = $row['uri'];
1822
-			$key = $calendarId . '::' . $row['uri'] . '::' . $calendarType;
1823
-			$this->cachedObjects[$key] = $this->rowToCalendarObject($row);
1824
-		}
1825
-
1826
-		return $result;
1827
-	}
1828
-
1829
-	/**
1830
-	 * custom Nextcloud search extension for CalDAV
1831
-	 *
1832
-	 * TODO - this should optionally cover cached calendar objects as well
1833
-	 *
1834
-	 * @param string $principalUri
1835
-	 * @param array $filters
1836
-	 * @param integer|null $limit
1837
-	 * @param integer|null $offset
1838
-	 * @return array
1839
-	 */
1840
-	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1841
-		return $this->atomic(function () use ($principalUri, $filters, $limit, $offset) {
1842
-			$calendars = $this->getCalendarsForUser($principalUri);
1843
-			$ownCalendars = [];
1844
-			$sharedCalendars = [];
1845
-
1846
-			$uriMapper = [];
1847
-
1848
-			foreach ($calendars as $calendar) {
1849
-				if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1850
-					$ownCalendars[] = $calendar['id'];
1851
-				} else {
1852
-					$sharedCalendars[] = $calendar['id'];
1853
-				}
1854
-				$uriMapper[$calendar['id']] = $calendar['uri'];
1855
-			}
1856
-			if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1857
-				return [];
1858
-			}
1859
-
1860
-			$query = $this->db->getQueryBuilder();
1861
-			// Calendar id expressions
1862
-			$calendarExpressions = [];
1863
-			foreach ($ownCalendars as $id) {
1864
-				$calendarExpressions[] = $query->expr()->andX(
1865
-					$query->expr()->eq('c.calendarid',
1866
-						$query->createNamedParameter($id)),
1867
-					$query->expr()->eq('c.calendartype',
1868
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1869
-			}
1870
-			foreach ($sharedCalendars as $id) {
1871
-				$calendarExpressions[] = $query->expr()->andX(
1872
-					$query->expr()->eq('c.calendarid',
1873
-						$query->createNamedParameter($id)),
1874
-					$query->expr()->eq('c.classification',
1875
-						$query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1876
-					$query->expr()->eq('c.calendartype',
1877
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1878
-			}
1879
-
1880
-			if (count($calendarExpressions) === 1) {
1881
-				$calExpr = $calendarExpressions[0];
1882
-			} else {
1883
-				$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1884
-			}
1885
-
1886
-			// Component expressions
1887
-			$compExpressions = [];
1888
-			foreach ($filters['comps'] as $comp) {
1889
-				$compExpressions[] = $query->expr()
1890
-					->eq('c.componenttype', $query->createNamedParameter($comp));
1891
-			}
1892
-
1893
-			if (count($compExpressions) === 1) {
1894
-				$compExpr = $compExpressions[0];
1895
-			} else {
1896
-				$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1897
-			}
1898
-
1899
-			if (!isset($filters['props'])) {
1900
-				$filters['props'] = [];
1901
-			}
1902
-			if (!isset($filters['params'])) {
1903
-				$filters['params'] = [];
1904
-			}
1905
-
1906
-			$propParamExpressions = [];
1907
-			foreach ($filters['props'] as $prop) {
1908
-				$propParamExpressions[] = $query->expr()->andX(
1909
-					$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1910
-					$query->expr()->isNull('i.parameter')
1911
-				);
1912
-			}
1913
-			foreach ($filters['params'] as $param) {
1914
-				$propParamExpressions[] = $query->expr()->andX(
1915
-					$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1916
-					$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1917
-				);
1918
-			}
1919
-
1920
-			if (count($propParamExpressions) === 1) {
1921
-				$propParamExpr = $propParamExpressions[0];
1922
-			} else {
1923
-				$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1924
-			}
1925
-
1926
-			$query->select(['c.calendarid', 'c.uri'])
1927
-				->from($this->dbObjectPropertiesTable, 'i')
1928
-				->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1929
-				->where($calExpr)
1930
-				->andWhere($compExpr)
1931
-				->andWhere($propParamExpr)
1932
-				->andWhere($query->expr()->iLike('i.value',
1933
-					$query->createNamedParameter('%' . $this->db->escapeLikeParameter($filters['search-term']) . '%')))
1934
-				->andWhere($query->expr()->isNull('deleted_at'));
1935
-
1936
-			if ($offset) {
1937
-				$query->setFirstResult($offset);
1938
-			}
1939
-			if ($limit) {
1940
-				$query->setMaxResults($limit);
1941
-			}
1942
-
1943
-			$stmt = $query->executeQuery();
1944
-
1945
-			$result = [];
1946
-			while ($row = $stmt->fetch()) {
1947
-				$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1948
-				if (!in_array($path, $result)) {
1949
-					$result[] = $path;
1950
-				}
1951
-			}
1952
-
1953
-			return $result;
1954
-		}, $this->db);
1955
-	}
1956
-
1957
-	/**
1958
-	 * used for Nextcloud's calendar API
1959
-	 *
1960
-	 * @param array $calendarInfo
1961
-	 * @param string $pattern
1962
-	 * @param array $searchProperties
1963
-	 * @param array $options
1964
-	 * @param integer|null $limit
1965
-	 * @param integer|null $offset
1966
-	 *
1967
-	 * @return array
1968
-	 */
1969
-	public function search(
1970
-		array $calendarInfo,
1971
-		$pattern,
1972
-		array $searchProperties,
1973
-		array $options,
1974
-		$limit,
1975
-		$offset,
1976
-	) {
1977
-		$outerQuery = $this->db->getQueryBuilder();
1978
-		$innerQuery = $this->db->getQueryBuilder();
1979
-
1980
-		if (isset($calendarInfo['source'])) {
1981
-			$calendarType = self::CALENDAR_TYPE_SUBSCRIPTION;
1982
-		} else {
1983
-			$calendarType = self::CALENDAR_TYPE_CALENDAR;
1984
-		}
1985
-
1986
-		$innerQuery->selectDistinct('op.objectid')
1987
-			->from($this->dbObjectPropertiesTable, 'op')
1988
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
1989
-				$outerQuery->createNamedParameter($calendarInfo['id'])))
1990
-			->andWhere($innerQuery->expr()->eq('op.calendartype',
1991
-				$outerQuery->createNamedParameter($calendarType)));
1992
-
1993
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1994
-			->from('calendarobjects', 'c')
1995
-			->where($outerQuery->expr()->isNull('deleted_at'));
1996
-
1997
-		// only return public items for shared calendars for now
1998
-		if (isset($calendarInfo['{http://owncloud.org/ns}owner-principal']) === false || $calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1999
-			$outerQuery->andWhere($outerQuery->expr()->eq('c.classification',
2000
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2001
-		}
2002
-
2003
-		if (!empty($searchProperties)) {
2004
-			$or = [];
2005
-			foreach ($searchProperties as $searchProperty) {
2006
-				$or[] = $innerQuery->expr()->eq('op.name',
2007
-					$outerQuery->createNamedParameter($searchProperty));
2008
-			}
2009
-			$innerQuery->andWhere($innerQuery->expr()->orX(...$or));
2010
-		}
2011
-
2012
-		if ($pattern !== '') {
2013
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
2014
-				$outerQuery->createNamedParameter('%' .
2015
-					$this->db->escapeLikeParameter($pattern) . '%')));
2016
-		}
2017
-
2018
-		$start = null;
2019
-		$end = null;
2020
-
2021
-		$hasLimit = is_int($limit);
2022
-		$hasTimeRange = false;
2023
-
2024
-		if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2025
-			/** @var DateTimeInterface $start */
2026
-			$start = $options['timerange']['start'];
2027
-			$outerQuery->andWhere(
2028
-				$outerQuery->expr()->gt(
2029
-					'lastoccurence',
2030
-					$outerQuery->createNamedParameter($start->getTimestamp())
2031
-				)
2032
-			);
2033
-			$hasTimeRange = true;
2034
-		}
2035
-
2036
-		if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2037
-			/** @var DateTimeInterface $end */
2038
-			$end = $options['timerange']['end'];
2039
-			$outerQuery->andWhere(
2040
-				$outerQuery->expr()->lt(
2041
-					'firstoccurence',
2042
-					$outerQuery->createNamedParameter($end->getTimestamp())
2043
-				)
2044
-			);
2045
-			$hasTimeRange = true;
2046
-		}
2047
-
2048
-		if (isset($options['uid'])) {
2049
-			$outerQuery->andWhere($outerQuery->expr()->eq('uid', $outerQuery->createNamedParameter($options['uid'])));
2050
-		}
2051
-
2052
-		if (!empty($options['types'])) {
2053
-			$or = [];
2054
-			foreach ($options['types'] as $type) {
2055
-				$or[] = $outerQuery->expr()->eq('componenttype',
2056
-					$outerQuery->createNamedParameter($type));
2057
-			}
2058
-			$outerQuery->andWhere($outerQuery->expr()->orX(...$or));
2059
-		}
2060
-
2061
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id', $outerQuery->createFunction($innerQuery->getSQL())));
2062
-
2063
-		// Without explicit order by its undefined in which order the SQL server returns the events.
2064
-		// For the pagination with hasLimit and hasTimeRange, a stable ordering is helpful.
2065
-		$outerQuery->addOrderBy('id');
2066
-
2067
-		$offset = (int)$offset;
2068
-		$outerQuery->setFirstResult($offset);
2069
-
2070
-		$calendarObjects = [];
2071
-
2072
-		if ($hasLimit && $hasTimeRange) {
2073
-			/**
2074
-			 * Event recurrences are evaluated at runtime because the database only knows the first and last occurrence.
2075
-			 *
2076
-			 * Given, a user created 8 events with a yearly reoccurrence and two for events tomorrow.
2077
-			 * The upcoming event widget asks the CalDAV backend for 7 events within the next 14 days.
2078
-			 *
2079
-			 * If limit 7 is applied to the SQL query, we find the 7 events with a yearly reoccurrence
2080
-			 * and discard the events after evaluating the reoccurrence rules because they are not due within
2081
-			 * the next 14 days and end up with an empty result even if there are two events to show.
2082
-			 *
2083
-			 * The workaround for search requests with a limit and time range is asking for more row than requested
2084
-			 * and retrying if we have not reached the limit.
2085
-			 *
2086
-			 * 25 rows and 3 retries is entirely arbitrary.
2087
-			 */
2088
-			$maxResults = (int)max($limit, 25);
2089
-			$outerQuery->setMaxResults($maxResults);
2090
-
2091
-			for ($attempt = $objectsCount = 0; $attempt < 3 && $objectsCount < $limit; $attempt++) {
2092
-				$objectsCount = array_push($calendarObjects, ...$this->searchCalendarObjects($outerQuery, $start, $end));
2093
-				$outerQuery->setFirstResult($offset += $maxResults);
2094
-			}
2095
-
2096
-			$calendarObjects = array_slice($calendarObjects, 0, $limit, false);
2097
-		} else {
2098
-			$outerQuery->setMaxResults($limit);
2099
-			$calendarObjects = $this->searchCalendarObjects($outerQuery, $start, $end);
2100
-		}
2101
-
2102
-		$calendarObjects = array_map(function ($o) use ($options) {
2103
-			$calendarData = Reader::read($o['calendardata']);
2104
-
2105
-			// Expand recurrences if an explicit time range is requested
2106
-			if ($calendarData instanceof VCalendar
2107
-				&& isset($options['timerange']['start'], $options['timerange']['end'])) {
2108
-				$calendarData = $calendarData->expand(
2109
-					$options['timerange']['start'],
2110
-					$options['timerange']['end'],
2111
-				);
2112
-			}
2113
-
2114
-			$comps = $calendarData->getComponents();
2115
-			$objects = [];
2116
-			$timezones = [];
2117
-			foreach ($comps as $comp) {
2118
-				if ($comp instanceof VTimeZone) {
2119
-					$timezones[] = $comp;
2120
-				} else {
2121
-					$objects[] = $comp;
2122
-				}
2123
-			}
2124
-
2125
-			return [
2126
-				'id' => $o['id'],
2127
-				'type' => $o['componenttype'],
2128
-				'uid' => $o['uid'],
2129
-				'uri' => $o['uri'],
2130
-				'objects' => array_map(function ($c) {
2131
-					return $this->transformSearchData($c);
2132
-				}, $objects),
2133
-				'timezones' => array_map(function ($c) {
2134
-					return $this->transformSearchData($c);
2135
-				}, $timezones),
2136
-			];
2137
-		}, $calendarObjects);
2138
-
2139
-		usort($calendarObjects, function (array $a, array $b) {
2140
-			/** @var DateTimeImmutable $startA */
2141
-			$startA = $a['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2142
-			/** @var DateTimeImmutable $startB */
2143
-			$startB = $b['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2144
-
2145
-			return $startA->getTimestamp() <=> $startB->getTimestamp();
2146
-		});
2147
-
2148
-		return $calendarObjects;
2149
-	}
2150
-
2151
-	private function searchCalendarObjects(IQueryBuilder $query, ?DateTimeInterface $start, ?DateTimeInterface $end): array {
2152
-		$calendarObjects = [];
2153
-		$filterByTimeRange = ($start instanceof DateTimeInterface) || ($end instanceof DateTimeInterface);
2154
-
2155
-		$result = $query->executeQuery();
2156
-
2157
-		while (($row = $result->fetch()) !== false) {
2158
-			if ($filterByTimeRange === false) {
2159
-				// No filter required
2160
-				$calendarObjects[] = $row;
2161
-				continue;
2162
-			}
2163
-
2164
-			try {
2165
-				$isValid = $this->validateFilterForObject($row, [
2166
-					'name' => 'VCALENDAR',
2167
-					'comp-filters' => [
2168
-						[
2169
-							'name' => 'VEVENT',
2170
-							'comp-filters' => [],
2171
-							'prop-filters' => [],
2172
-							'is-not-defined' => false,
2173
-							'time-range' => [
2174
-								'start' => $start,
2175
-								'end' => $end,
2176
-							],
2177
-						],
2178
-					],
2179
-					'prop-filters' => [],
2180
-					'is-not-defined' => false,
2181
-					'time-range' => null,
2182
-				]);
2183
-			} catch (MaxInstancesExceededException $ex) {
2184
-				$this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
2185
-					'app' => 'dav',
2186
-					'exception' => $ex,
2187
-				]);
2188
-				continue;
2189
-			}
2190
-
2191
-			if (is_resource($row['calendardata'])) {
2192
-				// Put the stream back to the beginning so it can be read another time
2193
-				rewind($row['calendardata']);
2194
-			}
2195
-
2196
-			if ($isValid) {
2197
-				$calendarObjects[] = $row;
2198
-			}
2199
-		}
2200
-
2201
-		$result->closeCursor();
2202
-
2203
-		return $calendarObjects;
2204
-	}
2205
-
2206
-	/**
2207
-	 * @param Component $comp
2208
-	 * @return array
2209
-	 */
2210
-	private function transformSearchData(Component $comp) {
2211
-		$data = [];
2212
-		/** @var Component[] $subComponents */
2213
-		$subComponents = $comp->getComponents();
2214
-		/** @var Property[] $properties */
2215
-		$properties = array_filter($comp->children(), function ($c) {
2216
-			return $c instanceof Property;
2217
-		});
2218
-		$validationRules = $comp->getValidationRules();
2219
-
2220
-		foreach ($subComponents as $subComponent) {
2221
-			$name = $subComponent->name;
2222
-			if (!isset($data[$name])) {
2223
-				$data[$name] = [];
2224
-			}
2225
-			$data[$name][] = $this->transformSearchData($subComponent);
2226
-		}
2227
-
2228
-		foreach ($properties as $property) {
2229
-			$name = $property->name;
2230
-			if (!isset($validationRules[$name])) {
2231
-				$validationRules[$name] = '*';
2232
-			}
2233
-
2234
-			$rule = $validationRules[$property->name];
2235
-			if ($rule === '+' || $rule === '*') { // multiple
2236
-				if (!isset($data[$name])) {
2237
-					$data[$name] = [];
2238
-				}
2239
-
2240
-				$data[$name][] = $this->transformSearchProperty($property);
2241
-			} else { // once
2242
-				$data[$name] = $this->transformSearchProperty($property);
2243
-			}
2244
-		}
2245
-
2246
-		return $data;
2247
-	}
2248
-
2249
-	/**
2250
-	 * @param Property $prop
2251
-	 * @return array
2252
-	 */
2253
-	private function transformSearchProperty(Property $prop) {
2254
-		// No need to check Date, as it extends DateTime
2255
-		if ($prop instanceof Property\ICalendar\DateTime) {
2256
-			$value = $prop->getDateTime();
2257
-		} else {
2258
-			$value = $prop->getValue();
2259
-		}
2260
-
2261
-		return [
2262
-			$value,
2263
-			$prop->parameters()
2264
-		];
2265
-	}
2266
-
2267
-	/**
2268
-	 * @param string $principalUri
2269
-	 * @param string $pattern
2270
-	 * @param array $componentTypes
2271
-	 * @param array $searchProperties
2272
-	 * @param array $searchParameters
2273
-	 * @param array $options
2274
-	 * @return array
2275
-	 */
2276
-	public function searchPrincipalUri(string $principalUri,
2277
-		string $pattern,
2278
-		array $componentTypes,
2279
-		array $searchProperties,
2280
-		array $searchParameters,
2281
-		array $options = [],
2282
-	): array {
2283
-		return $this->atomic(function () use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
2284
-			$escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
2285
-
2286
-			$calendarObjectIdQuery = $this->db->getQueryBuilder();
2287
-			$calendarOr = [];
2288
-			$searchOr = [];
2289
-
2290
-			// Fetch calendars and subscription
2291
-			$calendars = $this->getCalendarsForUser($principalUri);
2292
-			$subscriptions = $this->getSubscriptionsForUser($principalUri);
2293
-			foreach ($calendars as $calendar) {
2294
-				$calendarAnd = $calendarObjectIdQuery->expr()->andX(
2295
-					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])),
2296
-					$calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)),
2297
-				);
2298
-
2299
-				// If it's shared, limit search to public events
2300
-				if (isset($calendar['{http://owncloud.org/ns}owner-principal'])
2301
-					&& $calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
2302
-					$calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2303
-				}
2304
-
2305
-				$calendarOr[] = $calendarAnd;
2306
-			}
2307
-			foreach ($subscriptions as $subscription) {
2308
-				$subscriptionAnd = $calendarObjectIdQuery->expr()->andX(
2309
-					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])),
2310
-					$calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)),
2311
-				);
2312
-
2313
-				// If it's shared, limit search to public events
2314
-				if (isset($subscription['{http://owncloud.org/ns}owner-principal'])
2315
-					&& $subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
2316
-					$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2317
-				}
2318
-
2319
-				$calendarOr[] = $subscriptionAnd;
2320
-			}
2321
-
2322
-			foreach ($searchProperties as $property) {
2323
-				$propertyAnd = $calendarObjectIdQuery->expr()->andX(
2324
-					$calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2325
-					$calendarObjectIdQuery->expr()->isNull('cob.parameter'),
2326
-				);
2327
-
2328
-				$searchOr[] = $propertyAnd;
2329
-			}
2330
-			foreach ($searchParameters as $property => $parameter) {
2331
-				$parameterAnd = $calendarObjectIdQuery->expr()->andX(
2332
-					$calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2333
-					$calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)),
2334
-				);
2335
-
2336
-				$searchOr[] = $parameterAnd;
2337
-			}
2338
-
2339
-			if (empty($calendarOr)) {
2340
-				return [];
2341
-			}
2342
-			if (empty($searchOr)) {
2343
-				return [];
2344
-			}
2345
-
2346
-			$calendarObjectIdQuery->selectDistinct('cob.objectid')
2347
-				->from($this->dbObjectPropertiesTable, 'cob')
2348
-				->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
2349
-				->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
2350
-				->andWhere($calendarObjectIdQuery->expr()->orX(...$calendarOr))
2351
-				->andWhere($calendarObjectIdQuery->expr()->orX(...$searchOr))
2352
-				->andWhere($calendarObjectIdQuery->expr()->isNull('deleted_at'));
2353
-
2354
-			if ($pattern !== '') {
2355
-				if (!$escapePattern) {
2356
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
2357
-				} else {
2358
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
2359
-				}
2360
-			}
2361
-
2362
-			if (isset($options['limit'])) {
2363
-				$calendarObjectIdQuery->setMaxResults($options['limit']);
2364
-			}
2365
-			if (isset($options['offset'])) {
2366
-				$calendarObjectIdQuery->setFirstResult($options['offset']);
2367
-			}
2368
-			if (isset($options['timerange'])) {
2369
-				if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2370
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->gt(
2371
-						'lastoccurence',
2372
-						$calendarObjectIdQuery->createNamedParameter($options['timerange']['start']->getTimeStamp()),
2373
-					));
2374
-				}
2375
-				if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2376
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->lt(
2377
-						'firstoccurence',
2378
-						$calendarObjectIdQuery->createNamedParameter($options['timerange']['end']->getTimeStamp()),
2379
-					));
2380
-				}
2381
-			}
2382
-
2383
-			$result = $calendarObjectIdQuery->executeQuery();
2384
-			$matches = [];
2385
-			while (($row = $result->fetch()) !== false) {
2386
-				$matches[] = (int)$row['objectid'];
2387
-			}
2388
-			$result->closeCursor();
2389
-
2390
-			$query = $this->db->getQueryBuilder();
2391
-			$query->select('calendardata', 'uri', 'calendarid', 'calendartype')
2392
-				->from('calendarobjects')
2393
-				->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
2394
-
2395
-			$result = $query->executeQuery();
2396
-			$calendarObjects = [];
2397
-			while (($array = $result->fetch()) !== false) {
2398
-				$array['calendarid'] = (int)$array['calendarid'];
2399
-				$array['calendartype'] = (int)$array['calendartype'];
2400
-				$array['calendardata'] = $this->readBlob($array['calendardata']);
2401
-
2402
-				$calendarObjects[] = $array;
2403
-			}
2404
-			$result->closeCursor();
2405
-			return $calendarObjects;
2406
-		}, $this->db);
2407
-	}
2408
-
2409
-	/**
2410
-	 * Searches through all of a users calendars and calendar objects to find
2411
-	 * an object with a specific UID.
2412
-	 *
2413
-	 * This method should return the path to this object, relative to the
2414
-	 * calendar home, so this path usually only contains two parts:
2415
-	 *
2416
-	 * calendarpath/objectpath.ics
2417
-	 *
2418
-	 * If the uid is not found, return null.
2419
-	 *
2420
-	 * This method should only consider * objects that the principal owns, so
2421
-	 * any calendars owned by other principals that also appear in this
2422
-	 * collection should be ignored.
2423
-	 *
2424
-	 * @param string $principalUri
2425
-	 * @param string $uid
2426
-	 * @return string|null
2427
-	 */
2428
-	public function getCalendarObjectByUID($principalUri, $uid) {
2429
-		$query = $this->db->getQueryBuilder();
2430
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
2431
-			->from('calendarobjects', 'co')
2432
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
2433
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2434
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
2435
-			->andWhere($query->expr()->isNull('co.deleted_at'));
2436
-		$stmt = $query->executeQuery();
2437
-		$row = $stmt->fetch();
2438
-		$stmt->closeCursor();
2439
-		if ($row) {
2440
-			return $row['calendaruri'] . '/' . $row['objecturi'];
2441
-		}
2442
-
2443
-		return null;
2444
-	}
2445
-
2446
-	public function getCalendarObjectById(string $principalUri, int $id): ?array {
2447
-		$query = $this->db->getQueryBuilder();
2448
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.calendardata', 'co.componenttype', 'co.classification', 'co.deleted_at'])
2449
-			->selectAlias('c.uri', 'calendaruri')
2450
-			->from('calendarobjects', 'co')
2451
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
2452
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2453
-			->andWhere($query->expr()->eq('co.id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
2454
-		$stmt = $query->executeQuery();
2455
-		$row = $stmt->fetch();
2456
-		$stmt->closeCursor();
2457
-
2458
-		if (!$row) {
2459
-			return null;
2460
-		}
2461
-
2462
-		return [
2463
-			'id' => $row['id'],
2464
-			'uri' => $row['uri'],
2465
-			'lastmodified' => $row['lastmodified'],
2466
-			'etag' => '"' . $row['etag'] . '"',
2467
-			'calendarid' => $row['calendarid'],
2468
-			'calendaruri' => $row['calendaruri'],
2469
-			'size' => (int)$row['size'],
2470
-			'calendardata' => $this->readBlob($row['calendardata']),
2471
-			'component' => strtolower($row['componenttype']),
2472
-			'classification' => (int)$row['classification'],
2473
-			'deleted_at' => isset($row['deleted_at']) ? ((int)$row['deleted_at']) : null,
2474
-		];
2475
-	}
2476
-
2477
-	/**
2478
-	 * The getChanges method returns all the changes that have happened, since
2479
-	 * the specified syncToken in the specified calendar.
2480
-	 *
2481
-	 * This function should return an array, such as the following:
2482
-	 *
2483
-	 * [
2484
-	 *   'syncToken' => 'The current synctoken',
2485
-	 *   'added'   => [
2486
-	 *      'new.txt',
2487
-	 *   ],
2488
-	 *   'modified'   => [
2489
-	 *      'modified.txt',
2490
-	 *   ],
2491
-	 *   'deleted' => [
2492
-	 *      'foo.php.bak',
2493
-	 *      'old.txt'
2494
-	 *   ]
2495
-	 * );
2496
-	 *
2497
-	 * The returned syncToken property should reflect the *current* syncToken
2498
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
2499
-	 * property This is * needed here too, to ensure the operation is atomic.
2500
-	 *
2501
-	 * If the $syncToken argument is specified as null, this is an initial
2502
-	 * sync, and all members should be reported.
2503
-	 *
2504
-	 * The modified property is an array of nodenames that have changed since
2505
-	 * the last token.
2506
-	 *
2507
-	 * The deleted property is an array with nodenames, that have been deleted
2508
-	 * from collection.
2509
-	 *
2510
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
2511
-	 * 1, you only have to report changes that happened only directly in
2512
-	 * immediate descendants. If it's 2, it should also include changes from
2513
-	 * the nodes below the child collections. (grandchildren)
2514
-	 *
2515
-	 * The $limit argument allows a client to specify how many results should
2516
-	 * be returned at most. If the limit is not specified, it should be treated
2517
-	 * as infinite.
2518
-	 *
2519
-	 * If the limit (infinite or not) is higher than you're willing to return,
2520
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
2521
-	 *
2522
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
2523
-	 * return null.
2524
-	 *
2525
-	 * The limit is 'suggestive'. You are free to ignore it.
2526
-	 *
2527
-	 * @param string $calendarId
2528
-	 * @param string $syncToken
2529
-	 * @param int $syncLevel
2530
-	 * @param int|null $limit
2531
-	 * @param int $calendarType
2532
-	 * @return ?array
2533
-	 */
2534
-	public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2535
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2536
-
2537
-		return $this->atomic(function () use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
2538
-			// Current synctoken
2539
-			$qb = $this->db->getQueryBuilder();
2540
-			$qb->select('synctoken')
2541
-				->from($table)
2542
-				->where(
2543
-					$qb->expr()->eq('id', $qb->createNamedParameter($calendarId))
2544
-				);
2545
-			$stmt = $qb->executeQuery();
2546
-			$currentToken = $stmt->fetchOne();
2547
-			$initialSync = !is_numeric($syncToken);
2548
-
2549
-			if ($currentToken === false) {
2550
-				return null;
2551
-			}
2552
-
2553
-			// evaluate if this is a initial sync and construct appropriate command
2554
-			if ($initialSync) {
2555
-				$qb = $this->db->getQueryBuilder();
2556
-				$qb->select('uri')
2557
-					->from('calendarobjects')
2558
-					->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2559
-					->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2560
-					->andWhere($qb->expr()->isNull('deleted_at'));
2561
-			} else {
2562
-				$qb = $this->db->getQueryBuilder();
2563
-				$qb->select('uri', $qb->func()->max('operation'))
2564
-					->from('calendarchanges')
2565
-					->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2566
-					->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2567
-					->andWhere($qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)))
2568
-					->andWhere($qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)))
2569
-					->groupBy('uri');
2570
-			}
2571
-			// evaluate if limit exists
2572
-			if (is_numeric($limit)) {
2573
-				$qb->setMaxResults($limit);
2574
-			}
2575
-			// execute command
2576
-			$stmt = $qb->executeQuery();
2577
-			// build results
2578
-			$result = ['syncToken' => $currentToken, 'added' => [], 'modified' => [], 'deleted' => []];
2579
-			// retrieve results
2580
-			if ($initialSync) {
2581
-				$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
2582
-			} else {
2583
-				// \PDO::FETCH_NUM is needed due to the inconsistent field names
2584
-				// produced by doctrine for MAX() with different databases
2585
-				while ($entry = $stmt->fetch(\PDO::FETCH_NUM)) {
2586
-					// assign uri (column 0) to appropriate mutation based on operation (column 1)
2587
-					// forced (int) is needed as doctrine with OCI returns the operation field as string not integer
2588
-					match ((int)$entry[1]) {
2589
-						1 => $result['added'][] = $entry[0],
2590
-						2 => $result['modified'][] = $entry[0],
2591
-						3 => $result['deleted'][] = $entry[0],
2592
-						default => $this->logger->debug('Unknown calendar change operation detected')
2593
-					};
2594
-				}
2595
-			}
2596
-			$stmt->closeCursor();
2597
-
2598
-			return $result;
2599
-		}, $this->db);
2600
-	}
2601
-
2602
-	/**
2603
-	 * Returns a list of subscriptions for a principal.
2604
-	 *
2605
-	 * Every subscription is an array with the following keys:
2606
-	 *  * id, a unique id that will be used by other functions to modify the
2607
-	 *    subscription. This can be the same as the uri or a database key.
2608
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
2609
-	 *  * principaluri. The owner of the subscription. Almost always the same as
2610
-	 *    principalUri passed to this method.
2611
-	 *
2612
-	 * Furthermore, all the subscription info must be returned too:
2613
-	 *
2614
-	 * 1. {DAV:}displayname
2615
-	 * 2. {http://apple.com/ns/ical/}refreshrate
2616
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
2617
-	 *    should not be stripped).
2618
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
2619
-	 *    should not be stripped).
2620
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
2621
-	 *    attachments should not be stripped).
2622
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
2623
-	 *     Sabre\DAV\Property\Href).
2624
-	 * 7. {http://apple.com/ns/ical/}calendar-color
2625
-	 * 8. {http://apple.com/ns/ical/}calendar-order
2626
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
2627
-	 *    (should just be an instance of
2628
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
2629
-	 *    default components).
2630
-	 *
2631
-	 * @param string $principalUri
2632
-	 * @return array
2633
-	 */
2634
-	public function getSubscriptionsForUser($principalUri) {
2635
-		$fields = array_column($this->subscriptionPropertyMap, 0);
2636
-		$fields[] = 'id';
2637
-		$fields[] = 'uri';
2638
-		$fields[] = 'source';
2639
-		$fields[] = 'principaluri';
2640
-		$fields[] = 'lastmodified';
2641
-		$fields[] = 'synctoken';
2642
-
2643
-		$query = $this->db->getQueryBuilder();
2644
-		$query->select($fields)
2645
-			->from('calendarsubscriptions')
2646
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2647
-			->orderBy('calendarorder', 'asc');
2648
-		$stmt = $query->executeQuery();
2649
-
2650
-		$subscriptions = [];
2651
-		while ($row = $stmt->fetch()) {
2652
-			$subscription = [
2653
-				'id' => $row['id'],
2654
-				'uri' => $row['uri'],
2655
-				'principaluri' => $row['principaluri'],
2656
-				'source' => $row['source'],
2657
-				'lastmodified' => $row['lastmodified'],
2658
-
2659
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2660
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
2661
-			];
2662
-
2663
-			$subscriptions[] = $this->rowToSubscription($row, $subscription);
2664
-		}
2665
-
2666
-		return $subscriptions;
2667
-	}
2668
-
2669
-	/**
2670
-	 * Creates a new subscription for a principal.
2671
-	 *
2672
-	 * If the creation was a success, an id must be returned that can be used to reference
2673
-	 * this subscription in other methods, such as updateSubscription.
2674
-	 *
2675
-	 * @param string $principalUri
2676
-	 * @param string $uri
2677
-	 * @param array $properties
2678
-	 * @return mixed
2679
-	 */
2680
-	public function createSubscription($principalUri, $uri, array $properties) {
2681
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2682
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2683
-		}
2684
-
2685
-		$values = [
2686
-			'principaluri' => $principalUri,
2687
-			'uri' => $uri,
2688
-			'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2689
-			'lastmodified' => time(),
2690
-		];
2691
-
2692
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2693
-
2694
-		foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
2695
-			if (array_key_exists($xmlName, $properties)) {
2696
-				$values[$dbName] = $properties[$xmlName];
2697
-				if (in_array($dbName, $propertiesBoolean)) {
2698
-					$values[$dbName] = true;
2699
-				}
2700
-			}
2701
-		}
2702
-
2703
-		[$subscriptionId, $subscriptionRow] = $this->atomic(function () use ($values) {
2704
-			$valuesToInsert = [];
2705
-			$query = $this->db->getQueryBuilder();
2706
-			foreach (array_keys($values) as $name) {
2707
-				$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2708
-			}
2709
-			$query->insert('calendarsubscriptions')
2710
-				->values($valuesToInsert)
2711
-				->executeStatement();
2712
-
2713
-			$subscriptionId = $query->getLastInsertId();
2714
-
2715
-			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2716
-			return [$subscriptionId, $subscriptionRow];
2717
-		}, $this->db);
2718
-
2719
-		$this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow));
2720
-
2721
-		return $subscriptionId;
2722
-	}
2723
-
2724
-	/**
2725
-	 * Updates a subscription
2726
-	 *
2727
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2728
-	 * To do the actual updates, you must tell this object which properties
2729
-	 * you're going to process with the handle() method.
2730
-	 *
2731
-	 * Calling the handle method is like telling the PropPatch object "I
2732
-	 * promise I can handle updating this property".
2733
-	 *
2734
-	 * Read the PropPatch documentation for more info and examples.
2735
-	 *
2736
-	 * @param mixed $subscriptionId
2737
-	 * @param PropPatch $propPatch
2738
-	 * @return void
2739
-	 */
2740
-	public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2741
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
2742
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
2743
-
2744
-		$propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2745
-			$newValues = [];
2746
-
2747
-			foreach ($mutations as $propertyName => $propertyValue) {
2748
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
2749
-					$newValues['source'] = $propertyValue->getHref();
2750
-				} else {
2751
-					$fieldName = $this->subscriptionPropertyMap[$propertyName][0];
2752
-					$newValues[$fieldName] = $propertyValue;
2753
-				}
2754
-			}
2755
-
2756
-			$subscriptionRow = $this->atomic(function () use ($subscriptionId, $newValues) {
2757
-				$query = $this->db->getQueryBuilder();
2758
-				$query->update('calendarsubscriptions')
2759
-					->set('lastmodified', $query->createNamedParameter(time()));
2760
-				foreach ($newValues as $fieldName => $value) {
2761
-					$query->set($fieldName, $query->createNamedParameter($value));
2762
-				}
2763
-				$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2764
-					->executeStatement();
2765
-
2766
-				return $this->getSubscriptionById($subscriptionId);
2767
-			}, $this->db);
2768
-
2769
-			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2770
-
2771
-			return true;
2772
-		});
2773
-	}
2774
-
2775
-	/**
2776
-	 * Deletes a subscription.
2777
-	 *
2778
-	 * @param mixed $subscriptionId
2779
-	 * @return void
2780
-	 */
2781
-	public function deleteSubscription($subscriptionId) {
2782
-		$this->atomic(function () use ($subscriptionId): void {
2783
-			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2784
-
2785
-			$query = $this->db->getQueryBuilder();
2786
-			$query->delete('calendarsubscriptions')
2787
-				->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2788
-				->executeStatement();
2789
-
2790
-			$query = $this->db->getQueryBuilder();
2791
-			$query->delete('calendarobjects')
2792
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2793
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2794
-				->executeStatement();
2795
-
2796
-			$query->delete('calendarchanges')
2797
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2798
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2799
-				->executeStatement();
2800
-
2801
-			$query->delete($this->dbObjectPropertiesTable)
2802
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2803
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2804
-				->executeStatement();
2805
-
2806
-			if ($subscriptionRow) {
2807
-				$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2808
-			}
2809
-		}, $this->db);
2810
-	}
2811
-
2812
-	/**
2813
-	 * Returns a single scheduling object for the inbox collection.
2814
-	 *
2815
-	 * The returned array should contain the following elements:
2816
-	 *   * uri - A unique basename for the object. This will be used to
2817
-	 *           construct a full uri.
2818
-	 *   * calendardata - The iCalendar object
2819
-	 *   * lastmodified - The last modification date. Can be an int for a unix
2820
-	 *                    timestamp, or a PHP DateTime object.
2821
-	 *   * etag - A unique token that must change if the object changed.
2822
-	 *   * size - The size of the object, in bytes.
2823
-	 *
2824
-	 * @param string $principalUri
2825
-	 * @param string $objectUri
2826
-	 * @return array
2827
-	 */
2828
-	public function getSchedulingObject($principalUri, $objectUri) {
2829
-		$query = $this->db->getQueryBuilder();
2830
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2831
-			->from('schedulingobjects')
2832
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2833
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2834
-			->executeQuery();
2835
-
2836
-		$row = $stmt->fetch();
2837
-
2838
-		if (!$row) {
2839
-			return null;
2840
-		}
2841
-
2842
-		return [
2843
-			'uri' => $row['uri'],
2844
-			'calendardata' => $row['calendardata'],
2845
-			'lastmodified' => $row['lastmodified'],
2846
-			'etag' => '"' . $row['etag'] . '"',
2847
-			'size' => (int)$row['size'],
2848
-		];
2849
-	}
2850
-
2851
-	/**
2852
-	 * Returns all scheduling objects for the inbox collection.
2853
-	 *
2854
-	 * These objects should be returned as an array. Every item in the array
2855
-	 * should follow the same structure as returned from getSchedulingObject.
2856
-	 *
2857
-	 * The main difference is that 'calendardata' is optional.
2858
-	 *
2859
-	 * @param string $principalUri
2860
-	 * @return array
2861
-	 */
2862
-	public function getSchedulingObjects($principalUri) {
2863
-		$query = $this->db->getQueryBuilder();
2864
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2865
-			->from('schedulingobjects')
2866
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2867
-			->executeQuery();
2868
-
2869
-		$results = [];
2870
-		while (($row = $stmt->fetch()) !== false) {
2871
-			$results[] = [
2872
-				'calendardata' => $row['calendardata'],
2873
-				'uri' => $row['uri'],
2874
-				'lastmodified' => $row['lastmodified'],
2875
-				'etag' => '"' . $row['etag'] . '"',
2876
-				'size' => (int)$row['size'],
2877
-			];
2878
-		}
2879
-		$stmt->closeCursor();
2880
-
2881
-		return $results;
2882
-	}
2883
-
2884
-	/**
2885
-	 * Deletes a scheduling object from the inbox collection.
2886
-	 *
2887
-	 * @param string $principalUri
2888
-	 * @param string $objectUri
2889
-	 * @return void
2890
-	 */
2891
-	public function deleteSchedulingObject($principalUri, $objectUri) {
2892
-		$this->cachedObjects = [];
2893
-		$query = $this->db->getQueryBuilder();
2894
-		$query->delete('schedulingobjects')
2895
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2896
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2897
-			->executeStatement();
2898
-	}
2899
-
2900
-	/**
2901
-	 * Deletes all scheduling objects last modified before $modifiedBefore from the inbox collection.
2902
-	 *
2903
-	 * @param int $modifiedBefore
2904
-	 * @param int $limit
2905
-	 * @return void
2906
-	 */
2907
-	public function deleteOutdatedSchedulingObjects(int $modifiedBefore, int $limit): void {
2908
-		$query = $this->db->getQueryBuilder();
2909
-		$query->select('id')
2910
-			->from('schedulingobjects')
2911
-			->where($query->expr()->lt('lastmodified', $query->createNamedParameter($modifiedBefore)))
2912
-			->setMaxResults($limit);
2913
-		$result = $query->executeQuery();
2914
-		$count = $result->rowCount();
2915
-		if ($count === 0) {
2916
-			return;
2917
-		}
2918
-		$ids = array_map(static function (array $id) {
2919
-			return (int)$id[0];
2920
-		}, $result->fetchAll(\PDO::FETCH_NUM));
2921
-		$result->closeCursor();
2922
-
2923
-		$numDeleted = 0;
2924
-		$deleteQuery = $this->db->getQueryBuilder();
2925
-		$deleteQuery->delete('schedulingobjects')
2926
-			->where($deleteQuery->expr()->in('id', $deleteQuery->createParameter('ids'), IQueryBuilder::PARAM_INT_ARRAY));
2927
-		foreach (array_chunk($ids, 1000) as $chunk) {
2928
-			$deleteQuery->setParameter('ids', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
2929
-			$numDeleted += $deleteQuery->executeStatement();
2930
-		}
2931
-
2932
-		if ($numDeleted === $limit) {
2933
-			$this->logger->info("Deleted $limit scheduling objects, continuing with next batch");
2934
-			$this->deleteOutdatedSchedulingObjects($modifiedBefore, $limit);
2935
-		}
2936
-	}
2937
-
2938
-	/**
2939
-	 * Creates a new scheduling object. This should land in a users' inbox.
2940
-	 *
2941
-	 * @param string $principalUri
2942
-	 * @param string $objectUri
2943
-	 * @param string $objectData
2944
-	 * @return void
2945
-	 */
2946
-	public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2947
-		$this->cachedObjects = [];
2948
-		$query = $this->db->getQueryBuilder();
2949
-		$query->insert('schedulingobjects')
2950
-			->values([
2951
-				'principaluri' => $query->createNamedParameter($principalUri),
2952
-				'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2953
-				'uri' => $query->createNamedParameter($objectUri),
2954
-				'lastmodified' => $query->createNamedParameter(time()),
2955
-				'etag' => $query->createNamedParameter(md5($objectData)),
2956
-				'size' => $query->createNamedParameter(strlen($objectData))
2957
-			])
2958
-			->executeStatement();
2959
-	}
2960
-
2961
-	/**
2962
-	 * Adds a change record to the calendarchanges table.
2963
-	 *
2964
-	 * @param mixed $calendarId
2965
-	 * @param string[] $objectUris
2966
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2967
-	 * @param int $calendarType
2968
-	 * @return void
2969
-	 */
2970
-	protected function addChanges(int $calendarId, array $objectUris, int $operation, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
2971
-		$this->cachedObjects = [];
2972
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2973
-
2974
-		$this->atomic(function () use ($calendarId, $objectUris, $operation, $calendarType, $table): void {
2975
-			$query = $this->db->getQueryBuilder();
2976
-			$query->select('synctoken')
2977
-				->from($table)
2978
-				->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2979
-			$result = $query->executeQuery();
2980
-			$syncToken = (int)$result->fetchOne();
2981
-			$result->closeCursor();
2982
-
2983
-			$query = $this->db->getQueryBuilder();
2984
-			$query->insert('calendarchanges')
2985
-				->values([
2986
-					'uri' => $query->createParameter('uri'),
2987
-					'synctoken' => $query->createNamedParameter($syncToken),
2988
-					'calendarid' => $query->createNamedParameter($calendarId),
2989
-					'operation' => $query->createNamedParameter($operation),
2990
-					'calendartype' => $query->createNamedParameter($calendarType),
2991
-					'created_at' => time(),
2992
-				]);
2993
-			foreach ($objectUris as $uri) {
2994
-				$query->setParameter('uri', $uri);
2995
-				$query->executeStatement();
2996
-			}
2997
-
2998
-			$query = $this->db->getQueryBuilder();
2999
-			$query->update($table)
3000
-				->set('synctoken', $query->createNamedParameter($syncToken + 1, IQueryBuilder::PARAM_INT))
3001
-				->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
3002
-				->executeStatement();
3003
-		}, $this->db);
3004
-	}
3005
-
3006
-	public function restoreChanges(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
3007
-		$this->cachedObjects = [];
3008
-
3009
-		$this->atomic(function () use ($calendarId, $calendarType): void {
3010
-			$qbAdded = $this->db->getQueryBuilder();
3011
-			$qbAdded->select('uri')
3012
-				->from('calendarobjects')
3013
-				->where(
3014
-					$qbAdded->expr()->andX(
3015
-						$qbAdded->expr()->eq('calendarid', $qbAdded->createNamedParameter($calendarId)),
3016
-						$qbAdded->expr()->eq('calendartype', $qbAdded->createNamedParameter($calendarType)),
3017
-						$qbAdded->expr()->isNull('deleted_at'),
3018
-					)
3019
-				);
3020
-			$resultAdded = $qbAdded->executeQuery();
3021
-			$addedUris = $resultAdded->fetchAll(\PDO::FETCH_COLUMN);
3022
-			$resultAdded->closeCursor();
3023
-			// Track everything as changed
3024
-			// Tracking the creation is not necessary because \OCA\DAV\CalDAV\CalDavBackend::getChangesForCalendar
3025
-			// only returns the last change per object.
3026
-			$this->addChanges($calendarId, $addedUris, 2, $calendarType);
3027
-
3028
-			$qbDeleted = $this->db->getQueryBuilder();
3029
-			$qbDeleted->select('uri')
3030
-				->from('calendarobjects')
3031
-				->where(
3032
-					$qbDeleted->expr()->andX(
3033
-						$qbDeleted->expr()->eq('calendarid', $qbDeleted->createNamedParameter($calendarId)),
3034
-						$qbDeleted->expr()->eq('calendartype', $qbDeleted->createNamedParameter($calendarType)),
3035
-						$qbDeleted->expr()->isNotNull('deleted_at'),
3036
-					)
3037
-				);
3038
-			$resultDeleted = $qbDeleted->executeQuery();
3039
-			$deletedUris = array_map(function (string $uri) {
3040
-				return str_replace('-deleted.ics', '.ics', $uri);
3041
-			}, $resultDeleted->fetchAll(\PDO::FETCH_COLUMN));
3042
-			$resultDeleted->closeCursor();
3043
-			$this->addChanges($calendarId, $deletedUris, 3, $calendarType);
3044
-		}, $this->db);
3045
-	}
3046
-
3047
-	/**
3048
-	 * Parses some information from calendar objects, used for optimized
3049
-	 * calendar-queries.
3050
-	 *
3051
-	 * Returns an array with the following keys:
3052
-	 *   * etag - An md5 checksum of the object without the quotes.
3053
-	 *   * size - Size of the object in bytes
3054
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
3055
-	 *   * firstOccurence
3056
-	 *   * lastOccurence
3057
-	 *   * uid - value of the UID property
3058
-	 *
3059
-	 * @param string $calendarData
3060
-	 * @return array
3061
-	 */
3062
-	public function getDenormalizedData(string $calendarData): array {
3063
-		$vObject = Reader::read($calendarData);
3064
-		$vEvents = [];
3065
-		$componentType = null;
3066
-		$component = null;
3067
-		$firstOccurrence = null;
3068
-		$lastOccurrence = null;
3069
-		$uid = null;
3070
-		$classification = self::CLASSIFICATION_PUBLIC;
3071
-		$hasDTSTART = false;
3072
-		foreach ($vObject->getComponents() as $component) {
3073
-			if ($component->name !== 'VTIMEZONE') {
3074
-				// Finding all VEVENTs, and track them
3075
-				if ($component->name === 'VEVENT') {
3076
-					$vEvents[] = $component;
3077
-					if ($component->DTSTART) {
3078
-						$hasDTSTART = true;
3079
-					}
3080
-				}
3081
-				// Track first component type and uid
3082
-				if ($uid === null) {
3083
-					$componentType = $component->name;
3084
-					$uid = (string)$component->UID;
3085
-				}
3086
-			}
3087
-		}
3088
-		if (!$componentType) {
3089
-			throw new BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
3090
-		}
3091
-
3092
-		if ($hasDTSTART) {
3093
-			$component = $vEvents[0];
3094
-
3095
-			// Finding the last occurrence is a bit harder
3096
-			if (!isset($component->RRULE) && count($vEvents) === 1) {
3097
-				$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
3098
-				if (isset($component->DTEND)) {
3099
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
3100
-				} elseif (isset($component->DURATION)) {
3101
-					$endDate = clone $component->DTSTART->getDateTime();
3102
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
3103
-					$lastOccurrence = $endDate->getTimeStamp();
3104
-				} elseif (!$component->DTSTART->hasTime()) {
3105
-					$endDate = clone $component->DTSTART->getDateTime();
3106
-					$endDate->modify('+1 day');
3107
-					$lastOccurrence = $endDate->getTimeStamp();
3108
-				} else {
3109
-					$lastOccurrence = $firstOccurrence;
3110
-				}
3111
-			} else {
3112
-				try {
3113
-					$it = new EventIterator($vEvents);
3114
-				} catch (NoInstancesException $e) {
3115
-					$this->logger->debug('Caught no instance exception for calendar data. This usually indicates invalid calendar data.', [
3116
-						'app' => 'dav',
3117
-						'exception' => $e,
3118
-					]);
3119
-					throw new Forbidden($e->getMessage());
3120
-				}
3121
-				$maxDate = new DateTime(self::MAX_DATE);
3122
-				$firstOccurrence = $it->getDtStart()->getTimestamp();
3123
-				if ($it->isInfinite()) {
3124
-					$lastOccurrence = $maxDate->getTimestamp();
3125
-				} else {
3126
-					$end = $it->getDtEnd();
3127
-					while ($it->valid() && $end < $maxDate) {
3128
-						$end = $it->getDtEnd();
3129
-						$it->next();
3130
-					}
3131
-					$lastOccurrence = $end->getTimestamp();
3132
-				}
3133
-			}
3134
-		}
3135
-
3136
-		if ($component->CLASS) {
3137
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
3138
-			switch ($component->CLASS->getValue()) {
3139
-				case 'PUBLIC':
3140
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
3141
-					break;
3142
-				case 'CONFIDENTIAL':
3143
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
3144
-					break;
3145
-			}
3146
-		}
3147
-		return [
3148
-			'etag' => md5($calendarData),
3149
-			'size' => strlen($calendarData),
3150
-			'componentType' => $componentType,
3151
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
3152
-			'lastOccurence' => is_null($lastOccurrence) ? null : max(0, $lastOccurrence),
3153
-			'uid' => $uid,
3154
-			'classification' => $classification
3155
-		];
3156
-	}
3157
-
3158
-	/**
3159
-	 * @param $cardData
3160
-	 * @return bool|string
3161
-	 */
3162
-	private function readBlob($cardData) {
3163
-		if (is_resource($cardData)) {
3164
-			return stream_get_contents($cardData);
3165
-		}
3166
-
3167
-		return $cardData;
3168
-	}
3169
-
3170
-	/**
3171
-	 * @param list<array{href: string, commonName: string, readOnly: bool}> $add
3172
-	 * @param list<string> $remove
3173
-	 */
3174
-	public function updateShares(IShareable $shareable, array $add, array $remove): void {
3175
-		$this->atomic(function () use ($shareable, $add, $remove): void {
3176
-			$calendarId = $shareable->getResourceId();
3177
-			$calendarRow = $this->getCalendarById($calendarId);
3178
-			if ($calendarRow === null) {
3179
-				throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $calendarId);
3180
-			}
3181
-			$oldShares = $this->getShares($calendarId);
3182
-
3183
-			$this->calendarSharingBackend->updateShares($shareable, $add, $remove, $oldShares);
3184
-
3185
-			$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent($calendarId, $calendarRow, $oldShares, $add, $remove));
3186
-		}, $this->db);
3187
-	}
3188
-
3189
-	/**
3190
-	 * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
3191
-	 */
3192
-	public function getShares(int $resourceId): array {
3193
-		return $this->calendarSharingBackend->getShares($resourceId);
3194
-	}
3195
-
3196
-	public function preloadShares(array $resourceIds): void {
3197
-		$this->calendarSharingBackend->preloadShares($resourceIds);
3198
-	}
3199
-
3200
-	/**
3201
-	 * @param boolean $value
3202
-	 * @param Calendar $calendar
3203
-	 * @return string|null
3204
-	 */
3205
-	public function setPublishStatus($value, $calendar) {
3206
-		return $this->atomic(function () use ($value, $calendar) {
3207
-			$calendarId = $calendar->getResourceId();
3208
-			$calendarData = $this->getCalendarById($calendarId);
3209
-
3210
-			$query = $this->db->getQueryBuilder();
3211
-			if ($value) {
3212
-				$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
3213
-				$query->insert('dav_shares')
3214
-					->values([
3215
-						'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
3216
-						'type' => $query->createNamedParameter('calendar'),
3217
-						'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
3218
-						'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
3219
-						'publicuri' => $query->createNamedParameter($publicUri)
3220
-					]);
3221
-				$query->executeStatement();
3222
-
3223
-				$this->dispatcher->dispatchTyped(new CalendarPublishedEvent($calendarId, $calendarData, $publicUri));
3224
-				return $publicUri;
3225
-			}
3226
-			$query->delete('dav_shares')
3227
-				->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3228
-				->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
3229
-			$query->executeStatement();
3230
-
3231
-			$this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent($calendarId, $calendarData));
3232
-			return null;
3233
-		}, $this->db);
3234
-	}
3235
-
3236
-	/**
3237
-	 * @param Calendar $calendar
3238
-	 * @return mixed
3239
-	 */
3240
-	public function getPublishStatus($calendar) {
3241
-		$query = $this->db->getQueryBuilder();
3242
-		$result = $query->select('publicuri')
3243
-			->from('dav_shares')
3244
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3245
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
3246
-			->executeQuery();
3247
-
3248
-		$row = $result->fetch();
3249
-		$result->closeCursor();
3250
-		return $row ? reset($row) : false;
3251
-	}
3252
-
3253
-	/**
3254
-	 * @param int $resourceId
3255
-	 * @param list<array{privilege: string, principal: string, protected: bool}> $acl
3256
-	 * @return list<array{privilege: string, principal: string, protected: bool}>
3257
-	 */
3258
-	public function applyShareAcl(int $resourceId, array $acl): array {
3259
-		$shares = $this->calendarSharingBackend->getShares($resourceId);
3260
-		return $this->calendarSharingBackend->applyShareAcl($shares, $acl);
3261
-	}
3262
-
3263
-	/**
3264
-	 * update properties table
3265
-	 *
3266
-	 * @param int $calendarId
3267
-	 * @param string $objectUri
3268
-	 * @param string $calendarData
3269
-	 * @param int $calendarType
3270
-	 */
3271
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
3272
-		$this->cachedObjects = [];
3273
-		$this->atomic(function () use ($calendarId, $objectUri, $calendarData, $calendarType): void {
3274
-			$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
3275
-
3276
-			try {
3277
-				$vCalendar = $this->readCalendarData($calendarData);
3278
-			} catch (\Exception $ex) {
3279
-				return;
3280
-			}
3281
-
3282
-			$this->purgeProperties($calendarId, $objectId);
3283
-
3284
-			$query = $this->db->getQueryBuilder();
3285
-			$query->insert($this->dbObjectPropertiesTable)
3286
-				->values(
3287
-					[
3288
-						'calendarid' => $query->createNamedParameter($calendarId),
3289
-						'calendartype' => $query->createNamedParameter($calendarType),
3290
-						'objectid' => $query->createNamedParameter($objectId),
3291
-						'name' => $query->createParameter('name'),
3292
-						'parameter' => $query->createParameter('parameter'),
3293
-						'value' => $query->createParameter('value'),
3294
-					]
3295
-				);
3296
-
3297
-			$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
3298
-			foreach ($vCalendar->getComponents() as $component) {
3299
-				if (!in_array($component->name, $indexComponents)) {
3300
-					continue;
3301
-				}
3302
-
3303
-				foreach ($component->children() as $property) {
3304
-					if (in_array($property->name, self::INDEXED_PROPERTIES, true)) {
3305
-						$value = $property->getValue();
3306
-						// is this a shitty db?
3307
-						if (!$this->db->supports4ByteText()) {
3308
-							$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3309
-						}
3310
-						$value = mb_strcut($value, 0, 254);
3311
-
3312
-						$query->setParameter('name', $property->name);
3313
-						$query->setParameter('parameter', null);
3314
-						$query->setParameter('value', mb_strcut($value, 0, 254));
3315
-						$query->executeStatement();
3316
-					}
3317
-
3318
-					if (array_key_exists($property->name, self::$indexParameters)) {
3319
-						$parameters = $property->parameters();
3320
-						$indexedParametersForProperty = self::$indexParameters[$property->name];
3321
-
3322
-						foreach ($parameters as $key => $value) {
3323
-							if (in_array($key, $indexedParametersForProperty)) {
3324
-								// is this a shitty db?
3325
-								if ($this->db->supports4ByteText()) {
3326
-									$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3327
-								}
3328
-
3329
-								$query->setParameter('name', $property->name);
3330
-								$query->setParameter('parameter', mb_strcut($key, 0, 254));
3331
-								$query->setParameter('value', mb_strcut($value, 0, 254));
3332
-								$query->executeStatement();
3333
-							}
3334
-						}
3335
-					}
3336
-				}
3337
-			}
3338
-		}, $this->db);
3339
-	}
3340
-
3341
-	/**
3342
-	 * deletes all birthday calendars
3343
-	 */
3344
-	public function deleteAllBirthdayCalendars() {
3345
-		$this->atomic(function (): void {
3346
-			$query = $this->db->getQueryBuilder();
3347
-			$result = $query->select(['id'])->from('calendars')
3348
-				->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
3349
-				->executeQuery();
3350
-
3351
-			while (($row = $result->fetch()) !== false) {
3352
-				$this->deleteCalendar(
3353
-					$row['id'],
3354
-					true // No data to keep in the trashbin, if the user re-enables then we regenerate
3355
-				);
3356
-			}
3357
-			$result->closeCursor();
3358
-		}, $this->db);
3359
-	}
3360
-
3361
-	/**
3362
-	 * @param $subscriptionId
3363
-	 */
3364
-	public function purgeAllCachedEventsForSubscription($subscriptionId) {
3365
-		$this->atomic(function () use ($subscriptionId): void {
3366
-			$query = $this->db->getQueryBuilder();
3367
-			$query->select('uri')
3368
-				->from('calendarobjects')
3369
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3370
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
3371
-			$stmt = $query->executeQuery();
3372
-
3373
-			$uris = [];
3374
-			while (($row = $stmt->fetch()) !== false) {
3375
-				$uris[] = $row['uri'];
3376
-			}
3377
-			$stmt->closeCursor();
3378
-
3379
-			$query = $this->db->getQueryBuilder();
3380
-			$query->delete('calendarobjects')
3381
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3382
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3383
-				->executeStatement();
3384
-
3385
-			$query = $this->db->getQueryBuilder();
3386
-			$query->delete('calendarchanges')
3387
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3388
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3389
-				->executeStatement();
3390
-
3391
-			$query = $this->db->getQueryBuilder();
3392
-			$query->delete($this->dbObjectPropertiesTable)
3393
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3394
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3395
-				->executeStatement();
3396
-
3397
-			$this->addChanges($subscriptionId, $uris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3398
-		}, $this->db);
3399
-	}
3400
-
3401
-	/**
3402
-	 * @param int $subscriptionId
3403
-	 * @param array<int> $calendarObjectIds
3404
-	 * @param array<string> $calendarObjectUris
3405
-	 */
3406
-	public function purgeCachedEventsForSubscription(int $subscriptionId, array $calendarObjectIds, array $calendarObjectUris): void {
3407
-		if (empty($calendarObjectUris)) {
3408
-			return;
3409
-		}
3410
-
3411
-		$this->atomic(function () use ($subscriptionId, $calendarObjectIds, $calendarObjectUris): void {
3412
-			foreach (array_chunk($calendarObjectIds, 1000) as $chunk) {
3413
-				$query = $this->db->getQueryBuilder();
3414
-				$query->delete($this->dbObjectPropertiesTable)
3415
-					->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3416
-					->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3417
-					->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3418
-					->executeStatement();
3419
-
3420
-				$query = $this->db->getQueryBuilder();
3421
-				$query->delete('calendarobjects')
3422
-					->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3423
-					->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3424
-					->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3425
-					->executeStatement();
3426
-			}
3427
-
3428
-			foreach (array_chunk($calendarObjectUris, 1000) as $chunk) {
3429
-				$query = $this->db->getQueryBuilder();
3430
-				$query->delete('calendarchanges')
3431
-					->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3432
-					->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3433
-					->andWhere($query->expr()->in('uri', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
3434
-					->executeStatement();
3435
-			}
3436
-			$this->addChanges($subscriptionId, $calendarObjectUris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3437
-		}, $this->db);
3438
-	}
3439
-
3440
-	/**
3441
-	 * Move a calendar from one user to another
3442
-	 *
3443
-	 * @param string $uriName
3444
-	 * @param string $uriOrigin
3445
-	 * @param string $uriDestination
3446
-	 * @param string $newUriName (optional) the new uriName
3447
-	 */
3448
-	public function moveCalendar($uriName, $uriOrigin, $uriDestination, $newUriName = null) {
3449
-		$query = $this->db->getQueryBuilder();
3450
-		$query->update('calendars')
3451
-			->set('principaluri', $query->createNamedParameter($uriDestination))
3452
-			->set('uri', $query->createNamedParameter($newUriName ?: $uriName))
3453
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
3454
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
3455
-			->executeStatement();
3456
-	}
3457
-
3458
-	/**
3459
-	 * read VCalendar data into a VCalendar object
3460
-	 *
3461
-	 * @param string $objectData
3462
-	 * @return VCalendar
3463
-	 */
3464
-	protected function readCalendarData($objectData) {
3465
-		return Reader::read($objectData);
3466
-	}
3467
-
3468
-	/**
3469
-	 * delete all properties from a given calendar object
3470
-	 *
3471
-	 * @param int $calendarId
3472
-	 * @param int $objectId
3473
-	 */
3474
-	protected function purgeProperties($calendarId, $objectId) {
3475
-		$this->cachedObjects = [];
3476
-		$query = $this->db->getQueryBuilder();
3477
-		$query->delete($this->dbObjectPropertiesTable)
3478
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
3479
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
3480
-		$query->executeStatement();
3481
-	}
3482
-
3483
-	/**
3484
-	 * get ID from a given calendar object
3485
-	 *
3486
-	 * @param int $calendarId
3487
-	 * @param string $uri
3488
-	 * @param int $calendarType
3489
-	 * @return int
3490
-	 */
3491
-	protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
3492
-		$query = $this->db->getQueryBuilder();
3493
-		$query->select('id')
3494
-			->from('calendarobjects')
3495
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
3496
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
3497
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
3498
-
3499
-		$result = $query->executeQuery();
3500
-		$objectIds = $result->fetch();
3501
-		$result->closeCursor();
3502
-
3503
-		if (!isset($objectIds['id'])) {
3504
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
3505
-		}
3506
-
3507
-		return (int)$objectIds['id'];
3508
-	}
3509
-
3510
-	/**
3511
-	 * @throws \InvalidArgumentException
3512
-	 */
3513
-	public function pruneOutdatedSyncTokens(int $keep, int $retention): int {
3514
-		if ($keep < 0) {
3515
-			throw new \InvalidArgumentException();
3516
-		}
3517
-
3518
-		$query = $this->db->getQueryBuilder();
3519
-		$query->select($query->func()->max('id'))
3520
-			->from('calendarchanges');
3521
-
3522
-		$result = $query->executeQuery();
3523
-		$maxId = (int)$result->fetchOne();
3524
-		$result->closeCursor();
3525
-		if (!$maxId || $maxId < $keep) {
3526
-			return 0;
3527
-		}
3528
-
3529
-		$query = $this->db->getQueryBuilder();
3530
-		$query->delete('calendarchanges')
3531
-			->where(
3532
-				$query->expr()->lte('id', $query->createNamedParameter($maxId - $keep, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
3533
-				$query->expr()->lte('created_at', $query->createNamedParameter($retention)),
3534
-			);
3535
-		return $query->executeStatement();
3536
-	}
3537
-
3538
-	/**
3539
-	 * return legacy endpoint principal name to new principal name
3540
-	 *
3541
-	 * @param $principalUri
3542
-	 * @param $toV2
3543
-	 * @return string
3544
-	 */
3545
-	private function convertPrincipal($principalUri, $toV2) {
3546
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
3547
-			[, $name] = Uri\split($principalUri);
3548
-			if ($toV2 === true) {
3549
-				return "principals/users/$name";
3550
-			}
3551
-			return "principals/$name";
3552
-		}
3553
-		return $principalUri;
3554
-	}
3555
-
3556
-	/**
3557
-	 * adds information about an owner to the calendar data
3558
-	 *
3559
-	 */
3560
-	private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
3561
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
3562
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
3563
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
3564
-			$uri = $calendarInfo[$ownerPrincipalKey];
3565
-		} else {
3566
-			$uri = $calendarInfo['principaluri'];
3567
-		}
3568
-
3569
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
3570
-		if (isset($principalInformation['{DAV:}displayname'])) {
3571
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
3572
-		}
3573
-		return $calendarInfo;
3574
-	}
3575
-
3576
-	private function addResourceTypeToCalendar(array $row, array $calendar): array {
3577
-		if (isset($row['deleted_at'])) {
3578
-			// Columns is set and not null -> this is a deleted calendar
3579
-			// we send a custom resourcetype to hide the deleted calendar
3580
-			// from ordinary DAV clients, but the Calendar app will know
3581
-			// how to handle this special resource.
3582
-			$calendar['{DAV:}resourcetype'] = new DAV\Xml\Property\ResourceType([
3583
-				'{DAV:}collection',
3584
-				sprintf('{%s}deleted-calendar', \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD),
3585
-			]);
3586
-		}
3587
-		return $calendar;
3588
-	}
3589
-
3590
-	/**
3591
-	 * Amend the calendar info with database row data
3592
-	 *
3593
-	 * @param array $row
3594
-	 * @param array $calendar
3595
-	 *
3596
-	 * @return array
3597
-	 */
3598
-	private function rowToCalendar($row, array $calendar): array {
3599
-		foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
3600
-			$value = $row[$dbName];
3601
-			if ($value !== null) {
3602
-				settype($value, $type);
3603
-			}
3604
-			$calendar[$xmlName] = $value;
3605
-		}
3606
-		return $calendar;
3607
-	}
3608
-
3609
-	/**
3610
-	 * Amend the subscription info with database row data
3611
-	 *
3612
-	 * @param array $row
3613
-	 * @param array $subscription
3614
-	 *
3615
-	 * @return array
3616
-	 */
3617
-	private function rowToSubscription($row, array $subscription): array {
3618
-		foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
3619
-			$value = $row[$dbName];
3620
-			if ($value !== null) {
3621
-				settype($value, $type);
3622
-			}
3623
-			$subscription[$xmlName] = $value;
3624
-		}
3625
-		return $subscription;
3626
-	}
3627
-
3628
-	/**
3629
-	 * delete all invitations from a given calendar
3630
-	 *
3631
-	 * @since 31.0.0
3632
-	 *
3633
-	 * @param int $calendarId
3634
-	 *
3635
-	 * @return void
3636
-	 */
3637
-	protected function purgeCalendarInvitations(int $calendarId): void {
3638
-		// select all calendar object uid's
3639
-		$cmd = $this->db->getQueryBuilder();
3640
-		$cmd->select('uid')
3641
-			->from($this->dbObjectsTable)
3642
-			->where($cmd->expr()->eq('calendarid', $cmd->createNamedParameter($calendarId)));
3643
-		$allIds = $cmd->executeQuery()->fetchAll(\PDO::FETCH_COLUMN);
3644
-		// delete all links that match object uid's
3645
-		$cmd = $this->db->getQueryBuilder();
3646
-		$cmd->delete($this->dbObjectInvitationsTable)
3647
-			->where($cmd->expr()->in('uid', $cmd->createParameter('uids'), IQueryBuilder::PARAM_STR_ARRAY));
3648
-		foreach (array_chunk($allIds, 1000) as $chunkIds) {
3649
-			$cmd->setParameter('uids', $chunkIds, IQueryBuilder::PARAM_STR_ARRAY);
3650
-			$cmd->executeStatement();
3651
-		}
3652
-	}
3653
-
3654
-	/**
3655
-	 * Delete all invitations from a given calendar event
3656
-	 *
3657
-	 * @since 31.0.0
3658
-	 *
3659
-	 * @param string $eventId UID of the event
3660
-	 *
3661
-	 * @return void
3662
-	 */
3663
-	protected function purgeObjectInvitations(string $eventId): void {
3664
-		$cmd = $this->db->getQueryBuilder();
3665
-		$cmd->delete($this->dbObjectInvitationsTable)
3666
-			->where($cmd->expr()->eq('uid', $cmd->createNamedParameter($eventId, IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR));
3667
-		$cmd->executeStatement();
3668
-	}
3669
-
3670
-	public function unshare(IShareable $shareable, string $principal): void {
3671
-		$this->atomic(function () use ($shareable, $principal): void {
3672
-			$calendarData = $this->getCalendarById($shareable->getResourceId());
3673
-			if ($calendarData === null) {
3674
-				throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $shareable->getResourceId());
3675
-			}
3676
-
3677
-			$oldShares = $this->getShares($shareable->getResourceId());
3678
-			$unshare = $this->calendarSharingBackend->unshare($shareable, $principal);
3679
-
3680
-			if ($unshare) {
3681
-				$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent(
3682
-					$shareable->getResourceId(),
3683
-					$calendarData,
3684
-					$oldShares,
3685
-					[],
3686
-					[$principal]
3687
-				));
3688
-			}
3689
-		}, $this->db);
3690
-	}
1044
+    /**
1045
+     * Returns all calendar objects with limited metadata for a calendar
1046
+     *
1047
+     * Every item contains an array with the following keys:
1048
+     *   * id - the table row id
1049
+     *   * etag - An arbitrary string
1050
+     *   * uri - a unique key which will be used to construct the uri. This can
1051
+     *     be any arbitrary string.
1052
+     *   * calendardata - The iCalendar-compatible calendar data
1053
+     *
1054
+     * @param mixed $calendarId
1055
+     * @param int $calendarType
1056
+     * @return array
1057
+     */
1058
+    public function getLimitedCalendarObjects(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1059
+        $query = $this->db->getQueryBuilder();
1060
+        $query->select(['id','uid', 'etag', 'uri', 'calendardata'])
1061
+            ->from('calendarobjects')
1062
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1063
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1064
+            ->andWhere($query->expr()->isNull('deleted_at'));
1065
+        $stmt = $query->executeQuery();
1066
+
1067
+        $result = [];
1068
+        while (($row = $stmt->fetch()) !== false) {
1069
+            $result[$row['uid']] = [
1070
+                'id' => $row['id'],
1071
+                'etag' => $row['etag'],
1072
+                'uri' => $row['uri'],
1073
+                'calendardata' => $row['calendardata'],
1074
+            ];
1075
+        }
1076
+        $stmt->closeCursor();
1077
+
1078
+        return $result;
1079
+    }
1080
+
1081
+    /**
1082
+     * Delete all of an user's shares
1083
+     *
1084
+     * @param string $principaluri
1085
+     * @return void
1086
+     */
1087
+    public function deleteAllSharesByUser($principaluri) {
1088
+        $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
1089
+    }
1090
+
1091
+    /**
1092
+     * Returns all calendar objects within a calendar.
1093
+     *
1094
+     * Every item contains an array with the following keys:
1095
+     *   * calendardata - The iCalendar-compatible calendar data
1096
+     *   * uri - a unique key which will be used to construct the uri. This can
1097
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
1098
+     *     good idea. This is only the basename, or filename, not the full
1099
+     *     path.
1100
+     *   * lastmodified - a timestamp of the last modification time
1101
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
1102
+     *   '"abcdef"')
1103
+     *   * size - The size of the calendar objects, in bytes.
1104
+     *   * component - optional, a string containing the type of object, such
1105
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
1106
+     *     the Content-Type header.
1107
+     *
1108
+     * Note that the etag is optional, but it's highly encouraged to return for
1109
+     * speed reasons.
1110
+     *
1111
+     * The calendardata is also optional. If it's not returned
1112
+     * 'getCalendarObject' will be called later, which *is* expected to return
1113
+     * calendardata.
1114
+     *
1115
+     * If neither etag or size are specified, the calendardata will be
1116
+     * used/fetched to determine these numbers. If both are specified the
1117
+     * amount of times this is needed is reduced by a great degree.
1118
+     *
1119
+     * @param mixed $calendarId
1120
+     * @param int $calendarType
1121
+     * @return array
1122
+     */
1123
+    public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1124
+        $query = $this->db->getQueryBuilder();
1125
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
1126
+            ->from('calendarobjects')
1127
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1128
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1129
+            ->andWhere($query->expr()->isNull('deleted_at'));
1130
+        $stmt = $query->executeQuery();
1131
+
1132
+        $result = [];
1133
+        while (($row = $stmt->fetch()) !== false) {
1134
+            $result[] = [
1135
+                'id' => $row['id'],
1136
+                'uri' => $row['uri'],
1137
+                'lastmodified' => $row['lastmodified'],
1138
+                'etag' => '"' . $row['etag'] . '"',
1139
+                'calendarid' => $row['calendarid'],
1140
+                'size' => (int)$row['size'],
1141
+                'component' => strtolower($row['componenttype']),
1142
+                'classification' => (int)$row['classification']
1143
+            ];
1144
+        }
1145
+        $stmt->closeCursor();
1146
+
1147
+        return $result;
1148
+    }
1149
+
1150
+    public function getDeletedCalendarObjects(int $deletedBefore): array {
1151
+        $query = $this->db->getQueryBuilder();
1152
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.calendartype', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1153
+            ->from('calendarobjects', 'co')
1154
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1155
+            ->where($query->expr()->isNotNull('co.deleted_at'))
1156
+            ->andWhere($query->expr()->lt('co.deleted_at', $query->createNamedParameter($deletedBefore)));
1157
+        $stmt = $query->executeQuery();
1158
+
1159
+        $result = [];
1160
+        while (($row = $stmt->fetch()) !== false) {
1161
+            $result[] = [
1162
+                'id' => $row['id'],
1163
+                'uri' => $row['uri'],
1164
+                'lastmodified' => $row['lastmodified'],
1165
+                'etag' => '"' . $row['etag'] . '"',
1166
+                'calendarid' => (int)$row['calendarid'],
1167
+                'calendartype' => (int)$row['calendartype'],
1168
+                'size' => (int)$row['size'],
1169
+                'component' => strtolower($row['componenttype']),
1170
+                'classification' => (int)$row['classification'],
1171
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1172
+            ];
1173
+        }
1174
+        $stmt->closeCursor();
1175
+
1176
+        return $result;
1177
+    }
1178
+
1179
+    /**
1180
+     * Return all deleted calendar objects by the given principal that are not
1181
+     * in deleted calendars.
1182
+     *
1183
+     * @param string $principalUri
1184
+     * @return array
1185
+     * @throws Exception
1186
+     */
1187
+    public function getDeletedCalendarObjectsByPrincipal(string $principalUri): array {
1188
+        $query = $this->db->getQueryBuilder();
1189
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1190
+            ->selectAlias('c.uri', 'calendaruri')
1191
+            ->from('calendarobjects', 'co')
1192
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1193
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1194
+            ->andWhere($query->expr()->isNotNull('co.deleted_at'))
1195
+            ->andWhere($query->expr()->isNull('c.deleted_at'));
1196
+        $stmt = $query->executeQuery();
1197
+
1198
+        $result = [];
1199
+        while ($row = $stmt->fetch()) {
1200
+            $result[] = [
1201
+                'id' => $row['id'],
1202
+                'uri' => $row['uri'],
1203
+                'lastmodified' => $row['lastmodified'],
1204
+                'etag' => '"' . $row['etag'] . '"',
1205
+                'calendarid' => $row['calendarid'],
1206
+                'calendaruri' => $row['calendaruri'],
1207
+                'size' => (int)$row['size'],
1208
+                'component' => strtolower($row['componenttype']),
1209
+                'classification' => (int)$row['classification'],
1210
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1211
+            ];
1212
+        }
1213
+        $stmt->closeCursor();
1214
+
1215
+        return $result;
1216
+    }
1217
+
1218
+    /**
1219
+     * Returns information from a single calendar object, based on it's object
1220
+     * uri.
1221
+     *
1222
+     * The object uri is only the basename, or filename and not a full path.
1223
+     *
1224
+     * The returned array must have the same keys as getCalendarObjects. The
1225
+     * 'calendardata' object is required here though, while it's not required
1226
+     * for getCalendarObjects.
1227
+     *
1228
+     * This method must return null if the object did not exist.
1229
+     *
1230
+     * @param mixed $calendarId
1231
+     * @param string $objectUri
1232
+     * @param int $calendarType
1233
+     * @return array|null
1234
+     */
1235
+    public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1236
+        $key = $calendarId . '::' . $objectUri . '::' . $calendarType;
1237
+        if (isset($this->cachedObjects[$key])) {
1238
+            return $this->cachedObjects[$key];
1239
+        }
1240
+        $query = $this->db->getQueryBuilder();
1241
+        $query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1242
+            ->from('calendarobjects')
1243
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1244
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1245
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1246
+        $stmt = $query->executeQuery();
1247
+        $row = $stmt->fetch();
1248
+        $stmt->closeCursor();
1249
+
1250
+        if (!$row) {
1251
+            return null;
1252
+        }
1253
+
1254
+        $object = $this->rowToCalendarObject($row);
1255
+        $this->cachedObjects[$key] = $object;
1256
+        return $object;
1257
+    }
1258
+
1259
+    private function rowToCalendarObject(array $row): array {
1260
+        return [
1261
+            'id' => $row['id'],
1262
+            'uri' => $row['uri'],
1263
+            'uid' => $row['uid'],
1264
+            'lastmodified' => $row['lastmodified'],
1265
+            'etag' => '"' . $row['etag'] . '"',
1266
+            'calendarid' => $row['calendarid'],
1267
+            'size' => (int)$row['size'],
1268
+            'calendardata' => $this->readBlob($row['calendardata']),
1269
+            'component' => strtolower($row['componenttype']),
1270
+            'classification' => (int)$row['classification'],
1271
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1272
+        ];
1273
+    }
1274
+
1275
+    /**
1276
+     * Returns a list of calendar objects.
1277
+     *
1278
+     * This method should work identical to getCalendarObject, but instead
1279
+     * return all the calendar objects in the list as an array.
1280
+     *
1281
+     * If the backend supports this, it may allow for some speed-ups.
1282
+     *
1283
+     * @param mixed $calendarId
1284
+     * @param string[] $uris
1285
+     * @param int $calendarType
1286
+     * @return array
1287
+     */
1288
+    public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1289
+        if (empty($uris)) {
1290
+            return [];
1291
+        }
1292
+
1293
+        $chunks = array_chunk($uris, 100);
1294
+        $objects = [];
1295
+
1296
+        $query = $this->db->getQueryBuilder();
1297
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1298
+            ->from('calendarobjects')
1299
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1300
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1301
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1302
+            ->andWhere($query->expr()->isNull('deleted_at'));
1303
+
1304
+        foreach ($chunks as $uris) {
1305
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1306
+            $result = $query->executeQuery();
1307
+
1308
+            while ($row = $result->fetch()) {
1309
+                $objects[] = [
1310
+                    'id' => $row['id'],
1311
+                    'uri' => $row['uri'],
1312
+                    'lastmodified' => $row['lastmodified'],
1313
+                    'etag' => '"' . $row['etag'] . '"',
1314
+                    'calendarid' => $row['calendarid'],
1315
+                    'size' => (int)$row['size'],
1316
+                    'calendardata' => $this->readBlob($row['calendardata']),
1317
+                    'component' => strtolower($row['componenttype']),
1318
+                    'classification' => (int)$row['classification']
1319
+                ];
1320
+            }
1321
+            $result->closeCursor();
1322
+        }
1323
+
1324
+        return $objects;
1325
+    }
1326
+
1327
+    /**
1328
+     * Creates a new calendar object.
1329
+     *
1330
+     * The object uri is only the basename, or filename and not a full path.
1331
+     *
1332
+     * It is possible return an etag from this function, which will be used in
1333
+     * the response to this PUT request. Note that the ETag must be surrounded
1334
+     * by double-quotes.
1335
+     *
1336
+     * However, you should only really return this ETag if you don't mangle the
1337
+     * calendar-data. If the result of a subsequent GET to this object is not
1338
+     * the exact same as this request body, you should omit the ETag.
1339
+     *
1340
+     * @param mixed $calendarId
1341
+     * @param string $objectUri
1342
+     * @param string $calendarData
1343
+     * @param int $calendarType
1344
+     * @return string
1345
+     */
1346
+    public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1347
+        $this->cachedObjects = [];
1348
+        $extraData = $this->getDenormalizedData($calendarData);
1349
+
1350
+        return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1351
+            // Try to detect duplicates
1352
+            $qb = $this->db->getQueryBuilder();
1353
+            $qb->select($qb->func()->count('*'))
1354
+                ->from('calendarobjects')
1355
+                ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1356
+                ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($extraData['uid'])))
1357
+                ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1358
+                ->andWhere($qb->expr()->isNull('deleted_at'));
1359
+            $result = $qb->executeQuery();
1360
+            $count = (int)$result->fetchOne();
1361
+            $result->closeCursor();
1362
+
1363
+            if ($count !== 0) {
1364
+                throw new BadRequest('Calendar object with uid already exists in this calendar collection.');
1365
+            }
1366
+            // For a more specific error message we also try to explicitly look up the UID but as a deleted entry
1367
+            $qbDel = $this->db->getQueryBuilder();
1368
+            $qbDel->select('*')
1369
+                ->from('calendarobjects')
1370
+                ->where($qbDel->expr()->eq('calendarid', $qbDel->createNamedParameter($calendarId)))
1371
+                ->andWhere($qbDel->expr()->eq('uid', $qbDel->createNamedParameter($extraData['uid'])))
1372
+                ->andWhere($qbDel->expr()->eq('calendartype', $qbDel->createNamedParameter($calendarType)))
1373
+                ->andWhere($qbDel->expr()->isNotNull('deleted_at'));
1374
+            $result = $qbDel->executeQuery();
1375
+            $found = $result->fetch();
1376
+            $result->closeCursor();
1377
+            if ($found !== false) {
1378
+                // the object existed previously but has been deleted
1379
+                // remove the trashbin entry and continue as if it was a new object
1380
+                $this->deleteCalendarObject($calendarId, $found['uri']);
1381
+            }
1382
+
1383
+            $query = $this->db->getQueryBuilder();
1384
+            $query->insert('calendarobjects')
1385
+                ->values([
1386
+                    'calendarid' => $query->createNamedParameter($calendarId),
1387
+                    'uri' => $query->createNamedParameter($objectUri),
1388
+                    'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1389
+                    'lastmodified' => $query->createNamedParameter(time()),
1390
+                    'etag' => $query->createNamedParameter($extraData['etag']),
1391
+                    'size' => $query->createNamedParameter($extraData['size']),
1392
+                    'componenttype' => $query->createNamedParameter($extraData['componentType']),
1393
+                    'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1394
+                    'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1395
+                    'classification' => $query->createNamedParameter($extraData['classification']),
1396
+                    'uid' => $query->createNamedParameter($extraData['uid']),
1397
+                    'calendartype' => $query->createNamedParameter($calendarType),
1398
+                ])
1399
+                ->executeStatement();
1400
+
1401
+            $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1402
+            $this->addChanges($calendarId, [$objectUri], 1, $calendarType);
1403
+
1404
+            $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1405
+            assert($objectRow !== null);
1406
+
1407
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1408
+                $calendarRow = $this->getCalendarById($calendarId);
1409
+                $shares = $this->getShares($calendarId);
1410
+
1411
+                $this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1412
+            } else {
1413
+                $subscriptionRow = $this->getSubscriptionById($calendarId);
1414
+
1415
+                $this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1416
+            }
1417
+
1418
+            return '"' . $extraData['etag'] . '"';
1419
+        }, $this->db);
1420
+    }
1421
+
1422
+    /**
1423
+     * Updates an existing calendarobject, based on it's uri.
1424
+     *
1425
+     * The object uri is only the basename, or filename and not a full path.
1426
+     *
1427
+     * It is possible return an etag from this function, which will be used in
1428
+     * the response to this PUT request. Note that the ETag must be surrounded
1429
+     * by double-quotes.
1430
+     *
1431
+     * However, you should only really return this ETag if you don't mangle the
1432
+     * calendar-data. If the result of a subsequent GET to this object is not
1433
+     * the exact same as this request body, you should omit the ETag.
1434
+     *
1435
+     * @param mixed $calendarId
1436
+     * @param string $objectUri
1437
+     * @param string $calendarData
1438
+     * @param int $calendarType
1439
+     * @return string
1440
+     */
1441
+    public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1442
+        $this->cachedObjects = [];
1443
+        $extraData = $this->getDenormalizedData($calendarData);
1444
+
1445
+        return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1446
+            $query = $this->db->getQueryBuilder();
1447
+            $query->update('calendarobjects')
1448
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1449
+                ->set('lastmodified', $query->createNamedParameter(time()))
1450
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1451
+                ->set('size', $query->createNamedParameter($extraData['size']))
1452
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1453
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1454
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1455
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1456
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1457
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1458
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1459
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1460
+                ->executeStatement();
1461
+
1462
+            $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1463
+            $this->addChanges($calendarId, [$objectUri], 2, $calendarType);
1464
+
1465
+            $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1466
+            if (is_array($objectRow)) {
1467
+                if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1468
+                    $calendarRow = $this->getCalendarById($calendarId);
1469
+                    $shares = $this->getShares($calendarId);
1470
+
1471
+                    $this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1472
+                } else {
1473
+                    $subscriptionRow = $this->getSubscriptionById($calendarId);
1474
+
1475
+                    $this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1476
+                }
1477
+            }
1478
+
1479
+            return '"' . $extraData['etag'] . '"';
1480
+        }, $this->db);
1481
+    }
1482
+
1483
+    /**
1484
+     * Moves a calendar object from calendar to calendar.
1485
+     *
1486
+     * @param string $sourcePrincipalUri
1487
+     * @param int $sourceObjectId
1488
+     * @param string $targetPrincipalUri
1489
+     * @param int $targetCalendarId
1490
+     * @param string $tragetObjectUri
1491
+     * @param int $calendarType
1492
+     * @return bool
1493
+     * @throws Exception
1494
+     */
1495
+    public function moveCalendarObject(string $sourcePrincipalUri, int $sourceObjectId, string $targetPrincipalUri, int $targetCalendarId, string $tragetObjectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR): bool {
1496
+        $this->cachedObjects = [];
1497
+        return $this->atomic(function () use ($sourcePrincipalUri, $sourceObjectId, $targetPrincipalUri, $targetCalendarId, $tragetObjectUri, $calendarType) {
1498
+            $object = $this->getCalendarObjectById($sourcePrincipalUri, $sourceObjectId);
1499
+            if (empty($object)) {
1500
+                return false;
1501
+            }
1502
+
1503
+            $sourceCalendarId = $object['calendarid'];
1504
+            $sourceObjectUri = $object['uri'];
1505
+
1506
+            $query = $this->db->getQueryBuilder();
1507
+            $query->update('calendarobjects')
1508
+                ->set('calendarid', $query->createNamedParameter($targetCalendarId, IQueryBuilder::PARAM_INT))
1509
+                ->set('uri', $query->createNamedParameter($tragetObjectUri, IQueryBuilder::PARAM_STR))
1510
+                ->where($query->expr()->eq('id', $query->createNamedParameter($sourceObjectId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
1511
+                ->executeStatement();
1512
+
1513
+            $this->purgeProperties($sourceCalendarId, $sourceObjectId);
1514
+            $this->updateProperties($targetCalendarId, $tragetObjectUri, $object['calendardata'], $calendarType);
1515
+
1516
+            $this->addChanges($sourceCalendarId, [$sourceObjectUri], 3, $calendarType);
1517
+            $this->addChanges($targetCalendarId, [$tragetObjectUri], 1, $calendarType);
1518
+
1519
+            $object = $this->getCalendarObjectById($targetPrincipalUri, $sourceObjectId);
1520
+            // Calendar Object wasn't found - possibly because it was deleted in the meantime by a different client
1521
+            if (empty($object)) {
1522
+                return false;
1523
+            }
1524
+
1525
+            $targetCalendarRow = $this->getCalendarById($targetCalendarId);
1526
+            // the calendar this event is being moved to does not exist any longer
1527
+            if (empty($targetCalendarRow)) {
1528
+                return false;
1529
+            }
1530
+
1531
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1532
+                $sourceShares = $this->getShares($sourceCalendarId);
1533
+                $targetShares = $this->getShares($targetCalendarId);
1534
+                $sourceCalendarRow = $this->getCalendarById($sourceCalendarId);
1535
+                $this->dispatcher->dispatchTyped(new CalendarObjectMovedEvent($sourceCalendarId, $sourceCalendarRow, $targetCalendarId, $targetCalendarRow, $sourceShares, $targetShares, $object));
1536
+            }
1537
+            return true;
1538
+        }, $this->db);
1539
+    }
1540
+
1541
+    /**
1542
+     * Deletes an existing calendar object.
1543
+     *
1544
+     * The object uri is only the basename, or filename and not a full path.
1545
+     *
1546
+     * @param mixed $calendarId
1547
+     * @param string $objectUri
1548
+     * @param int $calendarType
1549
+     * @param bool $forceDeletePermanently
1550
+     * @return void
1551
+     */
1552
+    public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
1553
+        $this->cachedObjects = [];
1554
+        $this->atomic(function () use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently): void {
1555
+            $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1556
+
1557
+            if ($data === null) {
1558
+                // Nothing to delete
1559
+                return;
1560
+            }
1561
+
1562
+            if ($forceDeletePermanently || $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0') {
1563
+                $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1564
+                $stmt->execute([$calendarId, $objectUri, $calendarType]);
1565
+
1566
+                $this->purgeProperties($calendarId, $data['id']);
1567
+
1568
+                $this->purgeObjectInvitations($data['uid']);
1569
+
1570
+                if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1571
+                    $calendarRow = $this->getCalendarById($calendarId);
1572
+                    $shares = $this->getShares($calendarId);
1573
+
1574
+                    $this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent($calendarId, $calendarRow, $shares, $data));
1575
+                } else {
1576
+                    $subscriptionRow = $this->getSubscriptionById($calendarId);
1577
+
1578
+                    $this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent($calendarId, $subscriptionRow, [], $data));
1579
+                }
1580
+            } else {
1581
+                $pathInfo = pathinfo($data['uri']);
1582
+                if (!empty($pathInfo['extension'])) {
1583
+                    // Append a suffix to "free" the old URI for recreation
1584
+                    $newUri = sprintf(
1585
+                        '%s-deleted.%s',
1586
+                        $pathInfo['filename'],
1587
+                        $pathInfo['extension']
1588
+                    );
1589
+                } else {
1590
+                    $newUri = sprintf(
1591
+                        '%s-deleted',
1592
+                        $pathInfo['filename']
1593
+                    );
1594
+                }
1595
+
1596
+                // Try to detect conflicts before the DB does
1597
+                // As unlikely as it seems, this can happen when the user imports, then deletes, imports and deletes again
1598
+                $newObject = $this->getCalendarObject($calendarId, $newUri, $calendarType);
1599
+                if ($newObject !== null) {
1600
+                    throw new Forbidden("A calendar object with URI $newUri already exists in calendar $calendarId, therefore this object can't be moved into the trashbin");
1601
+                }
1602
+
1603
+                $qb = $this->db->getQueryBuilder();
1604
+                $markObjectDeletedQuery = $qb->update('calendarobjects')
1605
+                    ->set('deleted_at', $qb->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
1606
+                    ->set('uri', $qb->createNamedParameter($newUri))
1607
+                    ->where(
1608
+                        $qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
1609
+                        $qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
1610
+                        $qb->expr()->eq('uri', $qb->createNamedParameter($objectUri))
1611
+                    );
1612
+                $markObjectDeletedQuery->executeStatement();
1613
+
1614
+                $calendarData = $this->getCalendarById($calendarId);
1615
+                if ($calendarData !== null) {
1616
+                    $this->dispatcher->dispatchTyped(
1617
+                        new CalendarObjectMovedToTrashEvent(
1618
+                            $calendarId,
1619
+                            $calendarData,
1620
+                            $this->getShares($calendarId),
1621
+                            $data
1622
+                        )
1623
+                    );
1624
+                }
1625
+            }
1626
+
1627
+            $this->addChanges($calendarId, [$objectUri], 3, $calendarType);
1628
+        }, $this->db);
1629
+    }
1630
+
1631
+    /**
1632
+     * @param mixed $objectData
1633
+     *
1634
+     * @throws Forbidden
1635
+     */
1636
+    public function restoreCalendarObject(array $objectData): void {
1637
+        $this->cachedObjects = [];
1638
+        $this->atomic(function () use ($objectData): void {
1639
+            $id = (int)$objectData['id'];
1640
+            $restoreUri = str_replace('-deleted.ics', '.ics', $objectData['uri']);
1641
+            $targetObject = $this->getCalendarObject(
1642
+                $objectData['calendarid'],
1643
+                $restoreUri
1644
+            );
1645
+            if ($targetObject !== null) {
1646
+                throw new Forbidden("Can not restore calendar $id because a calendar object with the URI $restoreUri already exists");
1647
+            }
1648
+
1649
+            $qb = $this->db->getQueryBuilder();
1650
+            $update = $qb->update('calendarobjects')
1651
+                ->set('uri', $qb->createNamedParameter($restoreUri))
1652
+                ->set('deleted_at', $qb->createNamedParameter(null))
1653
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1654
+            $update->executeStatement();
1655
+
1656
+            // Make sure this change is tracked in the changes table
1657
+            $qb2 = $this->db->getQueryBuilder();
1658
+            $selectObject = $qb2->select('calendardata', 'uri', 'calendarid', 'calendartype')
1659
+                ->selectAlias('componenttype', 'component')
1660
+                ->from('calendarobjects')
1661
+                ->where($qb2->expr()->eq('id', $qb2->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1662
+            $result = $selectObject->executeQuery();
1663
+            $row = $result->fetch();
1664
+            $result->closeCursor();
1665
+            if ($row === false) {
1666
+                // Welp, this should possibly not have happened, but let's ignore
1667
+                return;
1668
+            }
1669
+            $this->addChanges($row['calendarid'], [$row['uri']], 1, (int)$row['calendartype']);
1670
+
1671
+            $calendarRow = $this->getCalendarById((int)$row['calendarid']);
1672
+            if ($calendarRow === null) {
1673
+                throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
1674
+            }
1675
+            $this->dispatcher->dispatchTyped(
1676
+                new CalendarObjectRestoredEvent(
1677
+                    (int)$objectData['calendarid'],
1678
+                    $calendarRow,
1679
+                    $this->getShares((int)$row['calendarid']),
1680
+                    $row
1681
+                )
1682
+            );
1683
+        }, $this->db);
1684
+    }
1685
+
1686
+    /**
1687
+     * Performs a calendar-query on the contents of this calendar.
1688
+     *
1689
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1690
+     * calendar-query it is possible for a client to request a specific set of
1691
+     * object, based on contents of iCalendar properties, date-ranges and
1692
+     * iCalendar component types (VTODO, VEVENT).
1693
+     *
1694
+     * This method should just return a list of (relative) urls that match this
1695
+     * query.
1696
+     *
1697
+     * The list of filters are specified as an array. The exact array is
1698
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1699
+     *
1700
+     * Note that it is extremely likely that getCalendarObject for every path
1701
+     * returned from this method will be called almost immediately after. You
1702
+     * may want to anticipate this to speed up these requests.
1703
+     *
1704
+     * This method provides a default implementation, which parses *all* the
1705
+     * iCalendar objects in the specified calendar.
1706
+     *
1707
+     * This default may well be good enough for personal use, and calendars
1708
+     * that aren't very large. But if you anticipate high usage, big calendars
1709
+     * or high loads, you are strongly advised to optimize certain paths.
1710
+     *
1711
+     * The best way to do so is override this method and to optimize
1712
+     * specifically for 'common filters'.
1713
+     *
1714
+     * Requests that are extremely common are:
1715
+     *   * requests for just VEVENTS
1716
+     *   * requests for just VTODO
1717
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1718
+     *
1719
+     * ..and combinations of these requests. It may not be worth it to try to
1720
+     * handle every possible situation and just rely on the (relatively
1721
+     * easy to use) CalendarQueryValidator to handle the rest.
1722
+     *
1723
+     * Note that especially time-range-filters may be difficult to parse. A
1724
+     * time-range filter specified on a VEVENT must for instance also handle
1725
+     * recurrence rules correctly.
1726
+     * A good example of how to interpret all these filters can also simply
1727
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1728
+     * as possible, so it gives you a good idea on what type of stuff you need
1729
+     * to think of.
1730
+     *
1731
+     * @param mixed $calendarId
1732
+     * @param array $filters
1733
+     * @param int $calendarType
1734
+     * @return array
1735
+     */
1736
+    public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1737
+        $componentType = null;
1738
+        $requirePostFilter = true;
1739
+        $timeRange = null;
1740
+
1741
+        // if no filters were specified, we don't need to filter after a query
1742
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1743
+            $requirePostFilter = false;
1744
+        }
1745
+
1746
+        // Figuring out if there's a component filter
1747
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1748
+            $componentType = $filters['comp-filters'][0]['name'];
1749
+
1750
+            // Checking if we need post-filters
1751
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1752
+                $requirePostFilter = false;
1753
+            }
1754
+            // There was a time-range filter
1755
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
1756
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1757
+
1758
+                // If start time OR the end time is not specified, we can do a
1759
+                // 100% accurate mysql query.
1760
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1761
+                    $requirePostFilter = false;
1762
+                }
1763
+            }
1764
+        }
1765
+        $query = $this->db->getQueryBuilder();
1766
+        $query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1767
+            ->from('calendarobjects')
1768
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1769
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1770
+            ->andWhere($query->expr()->isNull('deleted_at'));
1771
+
1772
+        if ($componentType) {
1773
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1774
+        }
1775
+
1776
+        if ($timeRange && $timeRange['start']) {
1777
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1778
+        }
1779
+        if ($timeRange && $timeRange['end']) {
1780
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1781
+        }
1782
+
1783
+        $stmt = $query->executeQuery();
1784
+
1785
+        $result = [];
1786
+        while ($row = $stmt->fetch()) {
1787
+            // if we leave it as a blob we can't read it both from the post filter and the rowToCalendarObject
1788
+            if (isset($row['calendardata'])) {
1789
+                $row['calendardata'] = $this->readBlob($row['calendardata']);
1790
+            }
1791
+
1792
+            if ($requirePostFilter) {
1793
+                // validateFilterForObject will parse the calendar data
1794
+                // catch parsing errors
1795
+                try {
1796
+                    $matches = $this->validateFilterForObject($row, $filters);
1797
+                } catch (ParseException $ex) {
1798
+                    $this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1799
+                        'app' => 'dav',
1800
+                        'exception' => $ex,
1801
+                    ]);
1802
+                    continue;
1803
+                } catch (InvalidDataException $ex) {
1804
+                    $this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1805
+                        'app' => 'dav',
1806
+                        'exception' => $ex,
1807
+                    ]);
1808
+                    continue;
1809
+                } catch (MaxInstancesExceededException $ex) {
1810
+                    $this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
1811
+                        'app' => 'dav',
1812
+                        'exception' => $ex,
1813
+                    ]);
1814
+                    continue;
1815
+                }
1816
+
1817
+                if (!$matches) {
1818
+                    continue;
1819
+                }
1820
+            }
1821
+            $result[] = $row['uri'];
1822
+            $key = $calendarId . '::' . $row['uri'] . '::' . $calendarType;
1823
+            $this->cachedObjects[$key] = $this->rowToCalendarObject($row);
1824
+        }
1825
+
1826
+        return $result;
1827
+    }
1828
+
1829
+    /**
1830
+     * custom Nextcloud search extension for CalDAV
1831
+     *
1832
+     * TODO - this should optionally cover cached calendar objects as well
1833
+     *
1834
+     * @param string $principalUri
1835
+     * @param array $filters
1836
+     * @param integer|null $limit
1837
+     * @param integer|null $offset
1838
+     * @return array
1839
+     */
1840
+    public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1841
+        return $this->atomic(function () use ($principalUri, $filters, $limit, $offset) {
1842
+            $calendars = $this->getCalendarsForUser($principalUri);
1843
+            $ownCalendars = [];
1844
+            $sharedCalendars = [];
1845
+
1846
+            $uriMapper = [];
1847
+
1848
+            foreach ($calendars as $calendar) {
1849
+                if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1850
+                    $ownCalendars[] = $calendar['id'];
1851
+                } else {
1852
+                    $sharedCalendars[] = $calendar['id'];
1853
+                }
1854
+                $uriMapper[$calendar['id']] = $calendar['uri'];
1855
+            }
1856
+            if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1857
+                return [];
1858
+            }
1859
+
1860
+            $query = $this->db->getQueryBuilder();
1861
+            // Calendar id expressions
1862
+            $calendarExpressions = [];
1863
+            foreach ($ownCalendars as $id) {
1864
+                $calendarExpressions[] = $query->expr()->andX(
1865
+                    $query->expr()->eq('c.calendarid',
1866
+                        $query->createNamedParameter($id)),
1867
+                    $query->expr()->eq('c.calendartype',
1868
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1869
+            }
1870
+            foreach ($sharedCalendars as $id) {
1871
+                $calendarExpressions[] = $query->expr()->andX(
1872
+                    $query->expr()->eq('c.calendarid',
1873
+                        $query->createNamedParameter($id)),
1874
+                    $query->expr()->eq('c.classification',
1875
+                        $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1876
+                    $query->expr()->eq('c.calendartype',
1877
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1878
+            }
1879
+
1880
+            if (count($calendarExpressions) === 1) {
1881
+                $calExpr = $calendarExpressions[0];
1882
+            } else {
1883
+                $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1884
+            }
1885
+
1886
+            // Component expressions
1887
+            $compExpressions = [];
1888
+            foreach ($filters['comps'] as $comp) {
1889
+                $compExpressions[] = $query->expr()
1890
+                    ->eq('c.componenttype', $query->createNamedParameter($comp));
1891
+            }
1892
+
1893
+            if (count($compExpressions) === 1) {
1894
+                $compExpr = $compExpressions[0];
1895
+            } else {
1896
+                $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1897
+            }
1898
+
1899
+            if (!isset($filters['props'])) {
1900
+                $filters['props'] = [];
1901
+            }
1902
+            if (!isset($filters['params'])) {
1903
+                $filters['params'] = [];
1904
+            }
1905
+
1906
+            $propParamExpressions = [];
1907
+            foreach ($filters['props'] as $prop) {
1908
+                $propParamExpressions[] = $query->expr()->andX(
1909
+                    $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1910
+                    $query->expr()->isNull('i.parameter')
1911
+                );
1912
+            }
1913
+            foreach ($filters['params'] as $param) {
1914
+                $propParamExpressions[] = $query->expr()->andX(
1915
+                    $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1916
+                    $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1917
+                );
1918
+            }
1919
+
1920
+            if (count($propParamExpressions) === 1) {
1921
+                $propParamExpr = $propParamExpressions[0];
1922
+            } else {
1923
+                $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1924
+            }
1925
+
1926
+            $query->select(['c.calendarid', 'c.uri'])
1927
+                ->from($this->dbObjectPropertiesTable, 'i')
1928
+                ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1929
+                ->where($calExpr)
1930
+                ->andWhere($compExpr)
1931
+                ->andWhere($propParamExpr)
1932
+                ->andWhere($query->expr()->iLike('i.value',
1933
+                    $query->createNamedParameter('%' . $this->db->escapeLikeParameter($filters['search-term']) . '%')))
1934
+                ->andWhere($query->expr()->isNull('deleted_at'));
1935
+
1936
+            if ($offset) {
1937
+                $query->setFirstResult($offset);
1938
+            }
1939
+            if ($limit) {
1940
+                $query->setMaxResults($limit);
1941
+            }
1942
+
1943
+            $stmt = $query->executeQuery();
1944
+
1945
+            $result = [];
1946
+            while ($row = $stmt->fetch()) {
1947
+                $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1948
+                if (!in_array($path, $result)) {
1949
+                    $result[] = $path;
1950
+                }
1951
+            }
1952
+
1953
+            return $result;
1954
+        }, $this->db);
1955
+    }
1956
+
1957
+    /**
1958
+     * used for Nextcloud's calendar API
1959
+     *
1960
+     * @param array $calendarInfo
1961
+     * @param string $pattern
1962
+     * @param array $searchProperties
1963
+     * @param array $options
1964
+     * @param integer|null $limit
1965
+     * @param integer|null $offset
1966
+     *
1967
+     * @return array
1968
+     */
1969
+    public function search(
1970
+        array $calendarInfo,
1971
+        $pattern,
1972
+        array $searchProperties,
1973
+        array $options,
1974
+        $limit,
1975
+        $offset,
1976
+    ) {
1977
+        $outerQuery = $this->db->getQueryBuilder();
1978
+        $innerQuery = $this->db->getQueryBuilder();
1979
+
1980
+        if (isset($calendarInfo['source'])) {
1981
+            $calendarType = self::CALENDAR_TYPE_SUBSCRIPTION;
1982
+        } else {
1983
+            $calendarType = self::CALENDAR_TYPE_CALENDAR;
1984
+        }
1985
+
1986
+        $innerQuery->selectDistinct('op.objectid')
1987
+            ->from($this->dbObjectPropertiesTable, 'op')
1988
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
1989
+                $outerQuery->createNamedParameter($calendarInfo['id'])))
1990
+            ->andWhere($innerQuery->expr()->eq('op.calendartype',
1991
+                $outerQuery->createNamedParameter($calendarType)));
1992
+
1993
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1994
+            ->from('calendarobjects', 'c')
1995
+            ->where($outerQuery->expr()->isNull('deleted_at'));
1996
+
1997
+        // only return public items for shared calendars for now
1998
+        if (isset($calendarInfo['{http://owncloud.org/ns}owner-principal']) === false || $calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1999
+            $outerQuery->andWhere($outerQuery->expr()->eq('c.classification',
2000
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2001
+        }
2002
+
2003
+        if (!empty($searchProperties)) {
2004
+            $or = [];
2005
+            foreach ($searchProperties as $searchProperty) {
2006
+                $or[] = $innerQuery->expr()->eq('op.name',
2007
+                    $outerQuery->createNamedParameter($searchProperty));
2008
+            }
2009
+            $innerQuery->andWhere($innerQuery->expr()->orX(...$or));
2010
+        }
2011
+
2012
+        if ($pattern !== '') {
2013
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
2014
+                $outerQuery->createNamedParameter('%' .
2015
+                    $this->db->escapeLikeParameter($pattern) . '%')));
2016
+        }
2017
+
2018
+        $start = null;
2019
+        $end = null;
2020
+
2021
+        $hasLimit = is_int($limit);
2022
+        $hasTimeRange = false;
2023
+
2024
+        if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2025
+            /** @var DateTimeInterface $start */
2026
+            $start = $options['timerange']['start'];
2027
+            $outerQuery->andWhere(
2028
+                $outerQuery->expr()->gt(
2029
+                    'lastoccurence',
2030
+                    $outerQuery->createNamedParameter($start->getTimestamp())
2031
+                )
2032
+            );
2033
+            $hasTimeRange = true;
2034
+        }
2035
+
2036
+        if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2037
+            /** @var DateTimeInterface $end */
2038
+            $end = $options['timerange']['end'];
2039
+            $outerQuery->andWhere(
2040
+                $outerQuery->expr()->lt(
2041
+                    'firstoccurence',
2042
+                    $outerQuery->createNamedParameter($end->getTimestamp())
2043
+                )
2044
+            );
2045
+            $hasTimeRange = true;
2046
+        }
2047
+
2048
+        if (isset($options['uid'])) {
2049
+            $outerQuery->andWhere($outerQuery->expr()->eq('uid', $outerQuery->createNamedParameter($options['uid'])));
2050
+        }
2051
+
2052
+        if (!empty($options['types'])) {
2053
+            $or = [];
2054
+            foreach ($options['types'] as $type) {
2055
+                $or[] = $outerQuery->expr()->eq('componenttype',
2056
+                    $outerQuery->createNamedParameter($type));
2057
+            }
2058
+            $outerQuery->andWhere($outerQuery->expr()->orX(...$or));
2059
+        }
2060
+
2061
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id', $outerQuery->createFunction($innerQuery->getSQL())));
2062
+
2063
+        // Without explicit order by its undefined in which order the SQL server returns the events.
2064
+        // For the pagination with hasLimit and hasTimeRange, a stable ordering is helpful.
2065
+        $outerQuery->addOrderBy('id');
2066
+
2067
+        $offset = (int)$offset;
2068
+        $outerQuery->setFirstResult($offset);
2069
+
2070
+        $calendarObjects = [];
2071
+
2072
+        if ($hasLimit && $hasTimeRange) {
2073
+            /**
2074
+             * Event recurrences are evaluated at runtime because the database only knows the first and last occurrence.
2075
+             *
2076
+             * Given, a user created 8 events with a yearly reoccurrence and two for events tomorrow.
2077
+             * The upcoming event widget asks the CalDAV backend for 7 events within the next 14 days.
2078
+             *
2079
+             * If limit 7 is applied to the SQL query, we find the 7 events with a yearly reoccurrence
2080
+             * and discard the events after evaluating the reoccurrence rules because they are not due within
2081
+             * the next 14 days and end up with an empty result even if there are two events to show.
2082
+             *
2083
+             * The workaround for search requests with a limit and time range is asking for more row than requested
2084
+             * and retrying if we have not reached the limit.
2085
+             *
2086
+             * 25 rows and 3 retries is entirely arbitrary.
2087
+             */
2088
+            $maxResults = (int)max($limit, 25);
2089
+            $outerQuery->setMaxResults($maxResults);
2090
+
2091
+            for ($attempt = $objectsCount = 0; $attempt < 3 && $objectsCount < $limit; $attempt++) {
2092
+                $objectsCount = array_push($calendarObjects, ...$this->searchCalendarObjects($outerQuery, $start, $end));
2093
+                $outerQuery->setFirstResult($offset += $maxResults);
2094
+            }
2095
+
2096
+            $calendarObjects = array_slice($calendarObjects, 0, $limit, false);
2097
+        } else {
2098
+            $outerQuery->setMaxResults($limit);
2099
+            $calendarObjects = $this->searchCalendarObjects($outerQuery, $start, $end);
2100
+        }
2101
+
2102
+        $calendarObjects = array_map(function ($o) use ($options) {
2103
+            $calendarData = Reader::read($o['calendardata']);
2104
+
2105
+            // Expand recurrences if an explicit time range is requested
2106
+            if ($calendarData instanceof VCalendar
2107
+                && isset($options['timerange']['start'], $options['timerange']['end'])) {
2108
+                $calendarData = $calendarData->expand(
2109
+                    $options['timerange']['start'],
2110
+                    $options['timerange']['end'],
2111
+                );
2112
+            }
2113
+
2114
+            $comps = $calendarData->getComponents();
2115
+            $objects = [];
2116
+            $timezones = [];
2117
+            foreach ($comps as $comp) {
2118
+                if ($comp instanceof VTimeZone) {
2119
+                    $timezones[] = $comp;
2120
+                } else {
2121
+                    $objects[] = $comp;
2122
+                }
2123
+            }
2124
+
2125
+            return [
2126
+                'id' => $o['id'],
2127
+                'type' => $o['componenttype'],
2128
+                'uid' => $o['uid'],
2129
+                'uri' => $o['uri'],
2130
+                'objects' => array_map(function ($c) {
2131
+                    return $this->transformSearchData($c);
2132
+                }, $objects),
2133
+                'timezones' => array_map(function ($c) {
2134
+                    return $this->transformSearchData($c);
2135
+                }, $timezones),
2136
+            ];
2137
+        }, $calendarObjects);
2138
+
2139
+        usort($calendarObjects, function (array $a, array $b) {
2140
+            /** @var DateTimeImmutable $startA */
2141
+            $startA = $a['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2142
+            /** @var DateTimeImmutable $startB */
2143
+            $startB = $b['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2144
+
2145
+            return $startA->getTimestamp() <=> $startB->getTimestamp();
2146
+        });
2147
+
2148
+        return $calendarObjects;
2149
+    }
2150
+
2151
+    private function searchCalendarObjects(IQueryBuilder $query, ?DateTimeInterface $start, ?DateTimeInterface $end): array {
2152
+        $calendarObjects = [];
2153
+        $filterByTimeRange = ($start instanceof DateTimeInterface) || ($end instanceof DateTimeInterface);
2154
+
2155
+        $result = $query->executeQuery();
2156
+
2157
+        while (($row = $result->fetch()) !== false) {
2158
+            if ($filterByTimeRange === false) {
2159
+                // No filter required
2160
+                $calendarObjects[] = $row;
2161
+                continue;
2162
+            }
2163
+
2164
+            try {
2165
+                $isValid = $this->validateFilterForObject($row, [
2166
+                    'name' => 'VCALENDAR',
2167
+                    'comp-filters' => [
2168
+                        [
2169
+                            'name' => 'VEVENT',
2170
+                            'comp-filters' => [],
2171
+                            'prop-filters' => [],
2172
+                            'is-not-defined' => false,
2173
+                            'time-range' => [
2174
+                                'start' => $start,
2175
+                                'end' => $end,
2176
+                            ],
2177
+                        ],
2178
+                    ],
2179
+                    'prop-filters' => [],
2180
+                    'is-not-defined' => false,
2181
+                    'time-range' => null,
2182
+                ]);
2183
+            } catch (MaxInstancesExceededException $ex) {
2184
+                $this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
2185
+                    'app' => 'dav',
2186
+                    'exception' => $ex,
2187
+                ]);
2188
+                continue;
2189
+            }
2190
+
2191
+            if (is_resource($row['calendardata'])) {
2192
+                // Put the stream back to the beginning so it can be read another time
2193
+                rewind($row['calendardata']);
2194
+            }
2195
+
2196
+            if ($isValid) {
2197
+                $calendarObjects[] = $row;
2198
+            }
2199
+        }
2200
+
2201
+        $result->closeCursor();
2202
+
2203
+        return $calendarObjects;
2204
+    }
2205
+
2206
+    /**
2207
+     * @param Component $comp
2208
+     * @return array
2209
+     */
2210
+    private function transformSearchData(Component $comp) {
2211
+        $data = [];
2212
+        /** @var Component[] $subComponents */
2213
+        $subComponents = $comp->getComponents();
2214
+        /** @var Property[] $properties */
2215
+        $properties = array_filter($comp->children(), function ($c) {
2216
+            return $c instanceof Property;
2217
+        });
2218
+        $validationRules = $comp->getValidationRules();
2219
+
2220
+        foreach ($subComponents as $subComponent) {
2221
+            $name = $subComponent->name;
2222
+            if (!isset($data[$name])) {
2223
+                $data[$name] = [];
2224
+            }
2225
+            $data[$name][] = $this->transformSearchData($subComponent);
2226
+        }
2227
+
2228
+        foreach ($properties as $property) {
2229
+            $name = $property->name;
2230
+            if (!isset($validationRules[$name])) {
2231
+                $validationRules[$name] = '*';
2232
+            }
2233
+
2234
+            $rule = $validationRules[$property->name];
2235
+            if ($rule === '+' || $rule === '*') { // multiple
2236
+                if (!isset($data[$name])) {
2237
+                    $data[$name] = [];
2238
+                }
2239
+
2240
+                $data[$name][] = $this->transformSearchProperty($property);
2241
+            } else { // once
2242
+                $data[$name] = $this->transformSearchProperty($property);
2243
+            }
2244
+        }
2245
+
2246
+        return $data;
2247
+    }
2248
+
2249
+    /**
2250
+     * @param Property $prop
2251
+     * @return array
2252
+     */
2253
+    private function transformSearchProperty(Property $prop) {
2254
+        // No need to check Date, as it extends DateTime
2255
+        if ($prop instanceof Property\ICalendar\DateTime) {
2256
+            $value = $prop->getDateTime();
2257
+        } else {
2258
+            $value = $prop->getValue();
2259
+        }
2260
+
2261
+        return [
2262
+            $value,
2263
+            $prop->parameters()
2264
+        ];
2265
+    }
2266
+
2267
+    /**
2268
+     * @param string $principalUri
2269
+     * @param string $pattern
2270
+     * @param array $componentTypes
2271
+     * @param array $searchProperties
2272
+     * @param array $searchParameters
2273
+     * @param array $options
2274
+     * @return array
2275
+     */
2276
+    public function searchPrincipalUri(string $principalUri,
2277
+        string $pattern,
2278
+        array $componentTypes,
2279
+        array $searchProperties,
2280
+        array $searchParameters,
2281
+        array $options = [],
2282
+    ): array {
2283
+        return $this->atomic(function () use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
2284
+            $escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
2285
+
2286
+            $calendarObjectIdQuery = $this->db->getQueryBuilder();
2287
+            $calendarOr = [];
2288
+            $searchOr = [];
2289
+
2290
+            // Fetch calendars and subscription
2291
+            $calendars = $this->getCalendarsForUser($principalUri);
2292
+            $subscriptions = $this->getSubscriptionsForUser($principalUri);
2293
+            foreach ($calendars as $calendar) {
2294
+                $calendarAnd = $calendarObjectIdQuery->expr()->andX(
2295
+                    $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])),
2296
+                    $calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)),
2297
+                );
2298
+
2299
+                // If it's shared, limit search to public events
2300
+                if (isset($calendar['{http://owncloud.org/ns}owner-principal'])
2301
+                    && $calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
2302
+                    $calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2303
+                }
2304
+
2305
+                $calendarOr[] = $calendarAnd;
2306
+            }
2307
+            foreach ($subscriptions as $subscription) {
2308
+                $subscriptionAnd = $calendarObjectIdQuery->expr()->andX(
2309
+                    $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])),
2310
+                    $calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)),
2311
+                );
2312
+
2313
+                // If it's shared, limit search to public events
2314
+                if (isset($subscription['{http://owncloud.org/ns}owner-principal'])
2315
+                    && $subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
2316
+                    $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2317
+                }
2318
+
2319
+                $calendarOr[] = $subscriptionAnd;
2320
+            }
2321
+
2322
+            foreach ($searchProperties as $property) {
2323
+                $propertyAnd = $calendarObjectIdQuery->expr()->andX(
2324
+                    $calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2325
+                    $calendarObjectIdQuery->expr()->isNull('cob.parameter'),
2326
+                );
2327
+
2328
+                $searchOr[] = $propertyAnd;
2329
+            }
2330
+            foreach ($searchParameters as $property => $parameter) {
2331
+                $parameterAnd = $calendarObjectIdQuery->expr()->andX(
2332
+                    $calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2333
+                    $calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)),
2334
+                );
2335
+
2336
+                $searchOr[] = $parameterAnd;
2337
+            }
2338
+
2339
+            if (empty($calendarOr)) {
2340
+                return [];
2341
+            }
2342
+            if (empty($searchOr)) {
2343
+                return [];
2344
+            }
2345
+
2346
+            $calendarObjectIdQuery->selectDistinct('cob.objectid')
2347
+                ->from($this->dbObjectPropertiesTable, 'cob')
2348
+                ->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
2349
+                ->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
2350
+                ->andWhere($calendarObjectIdQuery->expr()->orX(...$calendarOr))
2351
+                ->andWhere($calendarObjectIdQuery->expr()->orX(...$searchOr))
2352
+                ->andWhere($calendarObjectIdQuery->expr()->isNull('deleted_at'));
2353
+
2354
+            if ($pattern !== '') {
2355
+                if (!$escapePattern) {
2356
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
2357
+                } else {
2358
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
2359
+                }
2360
+            }
2361
+
2362
+            if (isset($options['limit'])) {
2363
+                $calendarObjectIdQuery->setMaxResults($options['limit']);
2364
+            }
2365
+            if (isset($options['offset'])) {
2366
+                $calendarObjectIdQuery->setFirstResult($options['offset']);
2367
+            }
2368
+            if (isset($options['timerange'])) {
2369
+                if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2370
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->gt(
2371
+                        'lastoccurence',
2372
+                        $calendarObjectIdQuery->createNamedParameter($options['timerange']['start']->getTimeStamp()),
2373
+                    ));
2374
+                }
2375
+                if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2376
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->lt(
2377
+                        'firstoccurence',
2378
+                        $calendarObjectIdQuery->createNamedParameter($options['timerange']['end']->getTimeStamp()),
2379
+                    ));
2380
+                }
2381
+            }
2382
+
2383
+            $result = $calendarObjectIdQuery->executeQuery();
2384
+            $matches = [];
2385
+            while (($row = $result->fetch()) !== false) {
2386
+                $matches[] = (int)$row['objectid'];
2387
+            }
2388
+            $result->closeCursor();
2389
+
2390
+            $query = $this->db->getQueryBuilder();
2391
+            $query->select('calendardata', 'uri', 'calendarid', 'calendartype')
2392
+                ->from('calendarobjects')
2393
+                ->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
2394
+
2395
+            $result = $query->executeQuery();
2396
+            $calendarObjects = [];
2397
+            while (($array = $result->fetch()) !== false) {
2398
+                $array['calendarid'] = (int)$array['calendarid'];
2399
+                $array['calendartype'] = (int)$array['calendartype'];
2400
+                $array['calendardata'] = $this->readBlob($array['calendardata']);
2401
+
2402
+                $calendarObjects[] = $array;
2403
+            }
2404
+            $result->closeCursor();
2405
+            return $calendarObjects;
2406
+        }, $this->db);
2407
+    }
2408
+
2409
+    /**
2410
+     * Searches through all of a users calendars and calendar objects to find
2411
+     * an object with a specific UID.
2412
+     *
2413
+     * This method should return the path to this object, relative to the
2414
+     * calendar home, so this path usually only contains two parts:
2415
+     *
2416
+     * calendarpath/objectpath.ics
2417
+     *
2418
+     * If the uid is not found, return null.
2419
+     *
2420
+     * This method should only consider * objects that the principal owns, so
2421
+     * any calendars owned by other principals that also appear in this
2422
+     * collection should be ignored.
2423
+     *
2424
+     * @param string $principalUri
2425
+     * @param string $uid
2426
+     * @return string|null
2427
+     */
2428
+    public function getCalendarObjectByUID($principalUri, $uid) {
2429
+        $query = $this->db->getQueryBuilder();
2430
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
2431
+            ->from('calendarobjects', 'co')
2432
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
2433
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2434
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
2435
+            ->andWhere($query->expr()->isNull('co.deleted_at'));
2436
+        $stmt = $query->executeQuery();
2437
+        $row = $stmt->fetch();
2438
+        $stmt->closeCursor();
2439
+        if ($row) {
2440
+            return $row['calendaruri'] . '/' . $row['objecturi'];
2441
+        }
2442
+
2443
+        return null;
2444
+    }
2445
+
2446
+    public function getCalendarObjectById(string $principalUri, int $id): ?array {
2447
+        $query = $this->db->getQueryBuilder();
2448
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.calendardata', 'co.componenttype', 'co.classification', 'co.deleted_at'])
2449
+            ->selectAlias('c.uri', 'calendaruri')
2450
+            ->from('calendarobjects', 'co')
2451
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
2452
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2453
+            ->andWhere($query->expr()->eq('co.id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
2454
+        $stmt = $query->executeQuery();
2455
+        $row = $stmt->fetch();
2456
+        $stmt->closeCursor();
2457
+
2458
+        if (!$row) {
2459
+            return null;
2460
+        }
2461
+
2462
+        return [
2463
+            'id' => $row['id'],
2464
+            'uri' => $row['uri'],
2465
+            'lastmodified' => $row['lastmodified'],
2466
+            'etag' => '"' . $row['etag'] . '"',
2467
+            'calendarid' => $row['calendarid'],
2468
+            'calendaruri' => $row['calendaruri'],
2469
+            'size' => (int)$row['size'],
2470
+            'calendardata' => $this->readBlob($row['calendardata']),
2471
+            'component' => strtolower($row['componenttype']),
2472
+            'classification' => (int)$row['classification'],
2473
+            'deleted_at' => isset($row['deleted_at']) ? ((int)$row['deleted_at']) : null,
2474
+        ];
2475
+    }
2476
+
2477
+    /**
2478
+     * The getChanges method returns all the changes that have happened, since
2479
+     * the specified syncToken in the specified calendar.
2480
+     *
2481
+     * This function should return an array, such as the following:
2482
+     *
2483
+     * [
2484
+     *   'syncToken' => 'The current synctoken',
2485
+     *   'added'   => [
2486
+     *      'new.txt',
2487
+     *   ],
2488
+     *   'modified'   => [
2489
+     *      'modified.txt',
2490
+     *   ],
2491
+     *   'deleted' => [
2492
+     *      'foo.php.bak',
2493
+     *      'old.txt'
2494
+     *   ]
2495
+     * );
2496
+     *
2497
+     * The returned syncToken property should reflect the *current* syncToken
2498
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
2499
+     * property This is * needed here too, to ensure the operation is atomic.
2500
+     *
2501
+     * If the $syncToken argument is specified as null, this is an initial
2502
+     * sync, and all members should be reported.
2503
+     *
2504
+     * The modified property is an array of nodenames that have changed since
2505
+     * the last token.
2506
+     *
2507
+     * The deleted property is an array with nodenames, that have been deleted
2508
+     * from collection.
2509
+     *
2510
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
2511
+     * 1, you only have to report changes that happened only directly in
2512
+     * immediate descendants. If it's 2, it should also include changes from
2513
+     * the nodes below the child collections. (grandchildren)
2514
+     *
2515
+     * The $limit argument allows a client to specify how many results should
2516
+     * be returned at most. If the limit is not specified, it should be treated
2517
+     * as infinite.
2518
+     *
2519
+     * If the limit (infinite or not) is higher than you're willing to return,
2520
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
2521
+     *
2522
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
2523
+     * return null.
2524
+     *
2525
+     * The limit is 'suggestive'. You are free to ignore it.
2526
+     *
2527
+     * @param string $calendarId
2528
+     * @param string $syncToken
2529
+     * @param int $syncLevel
2530
+     * @param int|null $limit
2531
+     * @param int $calendarType
2532
+     * @return ?array
2533
+     */
2534
+    public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2535
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2536
+
2537
+        return $this->atomic(function () use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
2538
+            // Current synctoken
2539
+            $qb = $this->db->getQueryBuilder();
2540
+            $qb->select('synctoken')
2541
+                ->from($table)
2542
+                ->where(
2543
+                    $qb->expr()->eq('id', $qb->createNamedParameter($calendarId))
2544
+                );
2545
+            $stmt = $qb->executeQuery();
2546
+            $currentToken = $stmt->fetchOne();
2547
+            $initialSync = !is_numeric($syncToken);
2548
+
2549
+            if ($currentToken === false) {
2550
+                return null;
2551
+            }
2552
+
2553
+            // evaluate if this is a initial sync and construct appropriate command
2554
+            if ($initialSync) {
2555
+                $qb = $this->db->getQueryBuilder();
2556
+                $qb->select('uri')
2557
+                    ->from('calendarobjects')
2558
+                    ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2559
+                    ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2560
+                    ->andWhere($qb->expr()->isNull('deleted_at'));
2561
+            } else {
2562
+                $qb = $this->db->getQueryBuilder();
2563
+                $qb->select('uri', $qb->func()->max('operation'))
2564
+                    ->from('calendarchanges')
2565
+                    ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2566
+                    ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2567
+                    ->andWhere($qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)))
2568
+                    ->andWhere($qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)))
2569
+                    ->groupBy('uri');
2570
+            }
2571
+            // evaluate if limit exists
2572
+            if (is_numeric($limit)) {
2573
+                $qb->setMaxResults($limit);
2574
+            }
2575
+            // execute command
2576
+            $stmt = $qb->executeQuery();
2577
+            // build results
2578
+            $result = ['syncToken' => $currentToken, 'added' => [], 'modified' => [], 'deleted' => []];
2579
+            // retrieve results
2580
+            if ($initialSync) {
2581
+                $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
2582
+            } else {
2583
+                // \PDO::FETCH_NUM is needed due to the inconsistent field names
2584
+                // produced by doctrine for MAX() with different databases
2585
+                while ($entry = $stmt->fetch(\PDO::FETCH_NUM)) {
2586
+                    // assign uri (column 0) to appropriate mutation based on operation (column 1)
2587
+                    // forced (int) is needed as doctrine with OCI returns the operation field as string not integer
2588
+                    match ((int)$entry[1]) {
2589
+                        1 => $result['added'][] = $entry[0],
2590
+                        2 => $result['modified'][] = $entry[0],
2591
+                        3 => $result['deleted'][] = $entry[0],
2592
+                        default => $this->logger->debug('Unknown calendar change operation detected')
2593
+                    };
2594
+                }
2595
+            }
2596
+            $stmt->closeCursor();
2597
+
2598
+            return $result;
2599
+        }, $this->db);
2600
+    }
2601
+
2602
+    /**
2603
+     * Returns a list of subscriptions for a principal.
2604
+     *
2605
+     * Every subscription is an array with the following keys:
2606
+     *  * id, a unique id that will be used by other functions to modify the
2607
+     *    subscription. This can be the same as the uri or a database key.
2608
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
2609
+     *  * principaluri. The owner of the subscription. Almost always the same as
2610
+     *    principalUri passed to this method.
2611
+     *
2612
+     * Furthermore, all the subscription info must be returned too:
2613
+     *
2614
+     * 1. {DAV:}displayname
2615
+     * 2. {http://apple.com/ns/ical/}refreshrate
2616
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
2617
+     *    should not be stripped).
2618
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
2619
+     *    should not be stripped).
2620
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
2621
+     *    attachments should not be stripped).
2622
+     * 6. {http://calendarserver.org/ns/}source (Must be a
2623
+     *     Sabre\DAV\Property\Href).
2624
+     * 7. {http://apple.com/ns/ical/}calendar-color
2625
+     * 8. {http://apple.com/ns/ical/}calendar-order
2626
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
2627
+     *    (should just be an instance of
2628
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
2629
+     *    default components).
2630
+     *
2631
+     * @param string $principalUri
2632
+     * @return array
2633
+     */
2634
+    public function getSubscriptionsForUser($principalUri) {
2635
+        $fields = array_column($this->subscriptionPropertyMap, 0);
2636
+        $fields[] = 'id';
2637
+        $fields[] = 'uri';
2638
+        $fields[] = 'source';
2639
+        $fields[] = 'principaluri';
2640
+        $fields[] = 'lastmodified';
2641
+        $fields[] = 'synctoken';
2642
+
2643
+        $query = $this->db->getQueryBuilder();
2644
+        $query->select($fields)
2645
+            ->from('calendarsubscriptions')
2646
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2647
+            ->orderBy('calendarorder', 'asc');
2648
+        $stmt = $query->executeQuery();
2649
+
2650
+        $subscriptions = [];
2651
+        while ($row = $stmt->fetch()) {
2652
+            $subscription = [
2653
+                'id' => $row['id'],
2654
+                'uri' => $row['uri'],
2655
+                'principaluri' => $row['principaluri'],
2656
+                'source' => $row['source'],
2657
+                'lastmodified' => $row['lastmodified'],
2658
+
2659
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2660
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
2661
+            ];
2662
+
2663
+            $subscriptions[] = $this->rowToSubscription($row, $subscription);
2664
+        }
2665
+
2666
+        return $subscriptions;
2667
+    }
2668
+
2669
+    /**
2670
+     * Creates a new subscription for a principal.
2671
+     *
2672
+     * If the creation was a success, an id must be returned that can be used to reference
2673
+     * this subscription in other methods, such as updateSubscription.
2674
+     *
2675
+     * @param string $principalUri
2676
+     * @param string $uri
2677
+     * @param array $properties
2678
+     * @return mixed
2679
+     */
2680
+    public function createSubscription($principalUri, $uri, array $properties) {
2681
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2682
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2683
+        }
2684
+
2685
+        $values = [
2686
+            'principaluri' => $principalUri,
2687
+            'uri' => $uri,
2688
+            'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2689
+            'lastmodified' => time(),
2690
+        ];
2691
+
2692
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2693
+
2694
+        foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
2695
+            if (array_key_exists($xmlName, $properties)) {
2696
+                $values[$dbName] = $properties[$xmlName];
2697
+                if (in_array($dbName, $propertiesBoolean)) {
2698
+                    $values[$dbName] = true;
2699
+                }
2700
+            }
2701
+        }
2702
+
2703
+        [$subscriptionId, $subscriptionRow] = $this->atomic(function () use ($values) {
2704
+            $valuesToInsert = [];
2705
+            $query = $this->db->getQueryBuilder();
2706
+            foreach (array_keys($values) as $name) {
2707
+                $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2708
+            }
2709
+            $query->insert('calendarsubscriptions')
2710
+                ->values($valuesToInsert)
2711
+                ->executeStatement();
2712
+
2713
+            $subscriptionId = $query->getLastInsertId();
2714
+
2715
+            $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2716
+            return [$subscriptionId, $subscriptionRow];
2717
+        }, $this->db);
2718
+
2719
+        $this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow));
2720
+
2721
+        return $subscriptionId;
2722
+    }
2723
+
2724
+    /**
2725
+     * Updates a subscription
2726
+     *
2727
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2728
+     * To do the actual updates, you must tell this object which properties
2729
+     * you're going to process with the handle() method.
2730
+     *
2731
+     * Calling the handle method is like telling the PropPatch object "I
2732
+     * promise I can handle updating this property".
2733
+     *
2734
+     * Read the PropPatch documentation for more info and examples.
2735
+     *
2736
+     * @param mixed $subscriptionId
2737
+     * @param PropPatch $propPatch
2738
+     * @return void
2739
+     */
2740
+    public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2741
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
2742
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
2743
+
2744
+        $propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2745
+            $newValues = [];
2746
+
2747
+            foreach ($mutations as $propertyName => $propertyValue) {
2748
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
2749
+                    $newValues['source'] = $propertyValue->getHref();
2750
+                } else {
2751
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName][0];
2752
+                    $newValues[$fieldName] = $propertyValue;
2753
+                }
2754
+            }
2755
+
2756
+            $subscriptionRow = $this->atomic(function () use ($subscriptionId, $newValues) {
2757
+                $query = $this->db->getQueryBuilder();
2758
+                $query->update('calendarsubscriptions')
2759
+                    ->set('lastmodified', $query->createNamedParameter(time()));
2760
+                foreach ($newValues as $fieldName => $value) {
2761
+                    $query->set($fieldName, $query->createNamedParameter($value));
2762
+                }
2763
+                $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2764
+                    ->executeStatement();
2765
+
2766
+                return $this->getSubscriptionById($subscriptionId);
2767
+            }, $this->db);
2768
+
2769
+            $this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2770
+
2771
+            return true;
2772
+        });
2773
+    }
2774
+
2775
+    /**
2776
+     * Deletes a subscription.
2777
+     *
2778
+     * @param mixed $subscriptionId
2779
+     * @return void
2780
+     */
2781
+    public function deleteSubscription($subscriptionId) {
2782
+        $this->atomic(function () use ($subscriptionId): void {
2783
+            $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2784
+
2785
+            $query = $this->db->getQueryBuilder();
2786
+            $query->delete('calendarsubscriptions')
2787
+                ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2788
+                ->executeStatement();
2789
+
2790
+            $query = $this->db->getQueryBuilder();
2791
+            $query->delete('calendarobjects')
2792
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2793
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2794
+                ->executeStatement();
2795
+
2796
+            $query->delete('calendarchanges')
2797
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2798
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2799
+                ->executeStatement();
2800
+
2801
+            $query->delete($this->dbObjectPropertiesTable)
2802
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2803
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2804
+                ->executeStatement();
2805
+
2806
+            if ($subscriptionRow) {
2807
+                $this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2808
+            }
2809
+        }, $this->db);
2810
+    }
2811
+
2812
+    /**
2813
+     * Returns a single scheduling object for the inbox collection.
2814
+     *
2815
+     * The returned array should contain the following elements:
2816
+     *   * uri - A unique basename for the object. This will be used to
2817
+     *           construct a full uri.
2818
+     *   * calendardata - The iCalendar object
2819
+     *   * lastmodified - The last modification date. Can be an int for a unix
2820
+     *                    timestamp, or a PHP DateTime object.
2821
+     *   * etag - A unique token that must change if the object changed.
2822
+     *   * size - The size of the object, in bytes.
2823
+     *
2824
+     * @param string $principalUri
2825
+     * @param string $objectUri
2826
+     * @return array
2827
+     */
2828
+    public function getSchedulingObject($principalUri, $objectUri) {
2829
+        $query = $this->db->getQueryBuilder();
2830
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2831
+            ->from('schedulingobjects')
2832
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2833
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2834
+            ->executeQuery();
2835
+
2836
+        $row = $stmt->fetch();
2837
+
2838
+        if (!$row) {
2839
+            return null;
2840
+        }
2841
+
2842
+        return [
2843
+            'uri' => $row['uri'],
2844
+            'calendardata' => $row['calendardata'],
2845
+            'lastmodified' => $row['lastmodified'],
2846
+            'etag' => '"' . $row['etag'] . '"',
2847
+            'size' => (int)$row['size'],
2848
+        ];
2849
+    }
2850
+
2851
+    /**
2852
+     * Returns all scheduling objects for the inbox collection.
2853
+     *
2854
+     * These objects should be returned as an array. Every item in the array
2855
+     * should follow the same structure as returned from getSchedulingObject.
2856
+     *
2857
+     * The main difference is that 'calendardata' is optional.
2858
+     *
2859
+     * @param string $principalUri
2860
+     * @return array
2861
+     */
2862
+    public function getSchedulingObjects($principalUri) {
2863
+        $query = $this->db->getQueryBuilder();
2864
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2865
+            ->from('schedulingobjects')
2866
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2867
+            ->executeQuery();
2868
+
2869
+        $results = [];
2870
+        while (($row = $stmt->fetch()) !== false) {
2871
+            $results[] = [
2872
+                'calendardata' => $row['calendardata'],
2873
+                'uri' => $row['uri'],
2874
+                'lastmodified' => $row['lastmodified'],
2875
+                'etag' => '"' . $row['etag'] . '"',
2876
+                'size' => (int)$row['size'],
2877
+            ];
2878
+        }
2879
+        $stmt->closeCursor();
2880
+
2881
+        return $results;
2882
+    }
2883
+
2884
+    /**
2885
+     * Deletes a scheduling object from the inbox collection.
2886
+     *
2887
+     * @param string $principalUri
2888
+     * @param string $objectUri
2889
+     * @return void
2890
+     */
2891
+    public function deleteSchedulingObject($principalUri, $objectUri) {
2892
+        $this->cachedObjects = [];
2893
+        $query = $this->db->getQueryBuilder();
2894
+        $query->delete('schedulingobjects')
2895
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2896
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2897
+            ->executeStatement();
2898
+    }
2899
+
2900
+    /**
2901
+     * Deletes all scheduling objects last modified before $modifiedBefore from the inbox collection.
2902
+     *
2903
+     * @param int $modifiedBefore
2904
+     * @param int $limit
2905
+     * @return void
2906
+     */
2907
+    public function deleteOutdatedSchedulingObjects(int $modifiedBefore, int $limit): void {
2908
+        $query = $this->db->getQueryBuilder();
2909
+        $query->select('id')
2910
+            ->from('schedulingobjects')
2911
+            ->where($query->expr()->lt('lastmodified', $query->createNamedParameter($modifiedBefore)))
2912
+            ->setMaxResults($limit);
2913
+        $result = $query->executeQuery();
2914
+        $count = $result->rowCount();
2915
+        if ($count === 0) {
2916
+            return;
2917
+        }
2918
+        $ids = array_map(static function (array $id) {
2919
+            return (int)$id[0];
2920
+        }, $result->fetchAll(\PDO::FETCH_NUM));
2921
+        $result->closeCursor();
2922
+
2923
+        $numDeleted = 0;
2924
+        $deleteQuery = $this->db->getQueryBuilder();
2925
+        $deleteQuery->delete('schedulingobjects')
2926
+            ->where($deleteQuery->expr()->in('id', $deleteQuery->createParameter('ids'), IQueryBuilder::PARAM_INT_ARRAY));
2927
+        foreach (array_chunk($ids, 1000) as $chunk) {
2928
+            $deleteQuery->setParameter('ids', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
2929
+            $numDeleted += $deleteQuery->executeStatement();
2930
+        }
2931
+
2932
+        if ($numDeleted === $limit) {
2933
+            $this->logger->info("Deleted $limit scheduling objects, continuing with next batch");
2934
+            $this->deleteOutdatedSchedulingObjects($modifiedBefore, $limit);
2935
+        }
2936
+    }
2937
+
2938
+    /**
2939
+     * Creates a new scheduling object. This should land in a users' inbox.
2940
+     *
2941
+     * @param string $principalUri
2942
+     * @param string $objectUri
2943
+     * @param string $objectData
2944
+     * @return void
2945
+     */
2946
+    public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2947
+        $this->cachedObjects = [];
2948
+        $query = $this->db->getQueryBuilder();
2949
+        $query->insert('schedulingobjects')
2950
+            ->values([
2951
+                'principaluri' => $query->createNamedParameter($principalUri),
2952
+                'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2953
+                'uri' => $query->createNamedParameter($objectUri),
2954
+                'lastmodified' => $query->createNamedParameter(time()),
2955
+                'etag' => $query->createNamedParameter(md5($objectData)),
2956
+                'size' => $query->createNamedParameter(strlen($objectData))
2957
+            ])
2958
+            ->executeStatement();
2959
+    }
2960
+
2961
+    /**
2962
+     * Adds a change record to the calendarchanges table.
2963
+     *
2964
+     * @param mixed $calendarId
2965
+     * @param string[] $objectUris
2966
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2967
+     * @param int $calendarType
2968
+     * @return void
2969
+     */
2970
+    protected function addChanges(int $calendarId, array $objectUris, int $operation, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
2971
+        $this->cachedObjects = [];
2972
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2973
+
2974
+        $this->atomic(function () use ($calendarId, $objectUris, $operation, $calendarType, $table): void {
2975
+            $query = $this->db->getQueryBuilder();
2976
+            $query->select('synctoken')
2977
+                ->from($table)
2978
+                ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2979
+            $result = $query->executeQuery();
2980
+            $syncToken = (int)$result->fetchOne();
2981
+            $result->closeCursor();
2982
+
2983
+            $query = $this->db->getQueryBuilder();
2984
+            $query->insert('calendarchanges')
2985
+                ->values([
2986
+                    'uri' => $query->createParameter('uri'),
2987
+                    'synctoken' => $query->createNamedParameter($syncToken),
2988
+                    'calendarid' => $query->createNamedParameter($calendarId),
2989
+                    'operation' => $query->createNamedParameter($operation),
2990
+                    'calendartype' => $query->createNamedParameter($calendarType),
2991
+                    'created_at' => time(),
2992
+                ]);
2993
+            foreach ($objectUris as $uri) {
2994
+                $query->setParameter('uri', $uri);
2995
+                $query->executeStatement();
2996
+            }
2997
+
2998
+            $query = $this->db->getQueryBuilder();
2999
+            $query->update($table)
3000
+                ->set('synctoken', $query->createNamedParameter($syncToken + 1, IQueryBuilder::PARAM_INT))
3001
+                ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
3002
+                ->executeStatement();
3003
+        }, $this->db);
3004
+    }
3005
+
3006
+    public function restoreChanges(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
3007
+        $this->cachedObjects = [];
3008
+
3009
+        $this->atomic(function () use ($calendarId, $calendarType): void {
3010
+            $qbAdded = $this->db->getQueryBuilder();
3011
+            $qbAdded->select('uri')
3012
+                ->from('calendarobjects')
3013
+                ->where(
3014
+                    $qbAdded->expr()->andX(
3015
+                        $qbAdded->expr()->eq('calendarid', $qbAdded->createNamedParameter($calendarId)),
3016
+                        $qbAdded->expr()->eq('calendartype', $qbAdded->createNamedParameter($calendarType)),
3017
+                        $qbAdded->expr()->isNull('deleted_at'),
3018
+                    )
3019
+                );
3020
+            $resultAdded = $qbAdded->executeQuery();
3021
+            $addedUris = $resultAdded->fetchAll(\PDO::FETCH_COLUMN);
3022
+            $resultAdded->closeCursor();
3023
+            // Track everything as changed
3024
+            // Tracking the creation is not necessary because \OCA\DAV\CalDAV\CalDavBackend::getChangesForCalendar
3025
+            // only returns the last change per object.
3026
+            $this->addChanges($calendarId, $addedUris, 2, $calendarType);
3027
+
3028
+            $qbDeleted = $this->db->getQueryBuilder();
3029
+            $qbDeleted->select('uri')
3030
+                ->from('calendarobjects')
3031
+                ->where(
3032
+                    $qbDeleted->expr()->andX(
3033
+                        $qbDeleted->expr()->eq('calendarid', $qbDeleted->createNamedParameter($calendarId)),
3034
+                        $qbDeleted->expr()->eq('calendartype', $qbDeleted->createNamedParameter($calendarType)),
3035
+                        $qbDeleted->expr()->isNotNull('deleted_at'),
3036
+                    )
3037
+                );
3038
+            $resultDeleted = $qbDeleted->executeQuery();
3039
+            $deletedUris = array_map(function (string $uri) {
3040
+                return str_replace('-deleted.ics', '.ics', $uri);
3041
+            }, $resultDeleted->fetchAll(\PDO::FETCH_COLUMN));
3042
+            $resultDeleted->closeCursor();
3043
+            $this->addChanges($calendarId, $deletedUris, 3, $calendarType);
3044
+        }, $this->db);
3045
+    }
3046
+
3047
+    /**
3048
+     * Parses some information from calendar objects, used for optimized
3049
+     * calendar-queries.
3050
+     *
3051
+     * Returns an array with the following keys:
3052
+     *   * etag - An md5 checksum of the object without the quotes.
3053
+     *   * size - Size of the object in bytes
3054
+     *   * componentType - VEVENT, VTODO or VJOURNAL
3055
+     *   * firstOccurence
3056
+     *   * lastOccurence
3057
+     *   * uid - value of the UID property
3058
+     *
3059
+     * @param string $calendarData
3060
+     * @return array
3061
+     */
3062
+    public function getDenormalizedData(string $calendarData): array {
3063
+        $vObject = Reader::read($calendarData);
3064
+        $vEvents = [];
3065
+        $componentType = null;
3066
+        $component = null;
3067
+        $firstOccurrence = null;
3068
+        $lastOccurrence = null;
3069
+        $uid = null;
3070
+        $classification = self::CLASSIFICATION_PUBLIC;
3071
+        $hasDTSTART = false;
3072
+        foreach ($vObject->getComponents() as $component) {
3073
+            if ($component->name !== 'VTIMEZONE') {
3074
+                // Finding all VEVENTs, and track them
3075
+                if ($component->name === 'VEVENT') {
3076
+                    $vEvents[] = $component;
3077
+                    if ($component->DTSTART) {
3078
+                        $hasDTSTART = true;
3079
+                    }
3080
+                }
3081
+                // Track first component type and uid
3082
+                if ($uid === null) {
3083
+                    $componentType = $component->name;
3084
+                    $uid = (string)$component->UID;
3085
+                }
3086
+            }
3087
+        }
3088
+        if (!$componentType) {
3089
+            throw new BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
3090
+        }
3091
+
3092
+        if ($hasDTSTART) {
3093
+            $component = $vEvents[0];
3094
+
3095
+            // Finding the last occurrence is a bit harder
3096
+            if (!isset($component->RRULE) && count($vEvents) === 1) {
3097
+                $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
3098
+                if (isset($component->DTEND)) {
3099
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
3100
+                } elseif (isset($component->DURATION)) {
3101
+                    $endDate = clone $component->DTSTART->getDateTime();
3102
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
3103
+                    $lastOccurrence = $endDate->getTimeStamp();
3104
+                } elseif (!$component->DTSTART->hasTime()) {
3105
+                    $endDate = clone $component->DTSTART->getDateTime();
3106
+                    $endDate->modify('+1 day');
3107
+                    $lastOccurrence = $endDate->getTimeStamp();
3108
+                } else {
3109
+                    $lastOccurrence = $firstOccurrence;
3110
+                }
3111
+            } else {
3112
+                try {
3113
+                    $it = new EventIterator($vEvents);
3114
+                } catch (NoInstancesException $e) {
3115
+                    $this->logger->debug('Caught no instance exception for calendar data. This usually indicates invalid calendar data.', [
3116
+                        'app' => 'dav',
3117
+                        'exception' => $e,
3118
+                    ]);
3119
+                    throw new Forbidden($e->getMessage());
3120
+                }
3121
+                $maxDate = new DateTime(self::MAX_DATE);
3122
+                $firstOccurrence = $it->getDtStart()->getTimestamp();
3123
+                if ($it->isInfinite()) {
3124
+                    $lastOccurrence = $maxDate->getTimestamp();
3125
+                } else {
3126
+                    $end = $it->getDtEnd();
3127
+                    while ($it->valid() && $end < $maxDate) {
3128
+                        $end = $it->getDtEnd();
3129
+                        $it->next();
3130
+                    }
3131
+                    $lastOccurrence = $end->getTimestamp();
3132
+                }
3133
+            }
3134
+        }
3135
+
3136
+        if ($component->CLASS) {
3137
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
3138
+            switch ($component->CLASS->getValue()) {
3139
+                case 'PUBLIC':
3140
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
3141
+                    break;
3142
+                case 'CONFIDENTIAL':
3143
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
3144
+                    break;
3145
+            }
3146
+        }
3147
+        return [
3148
+            'etag' => md5($calendarData),
3149
+            'size' => strlen($calendarData),
3150
+            'componentType' => $componentType,
3151
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
3152
+            'lastOccurence' => is_null($lastOccurrence) ? null : max(0, $lastOccurrence),
3153
+            'uid' => $uid,
3154
+            'classification' => $classification
3155
+        ];
3156
+    }
3157
+
3158
+    /**
3159
+     * @param $cardData
3160
+     * @return bool|string
3161
+     */
3162
+    private function readBlob($cardData) {
3163
+        if (is_resource($cardData)) {
3164
+            return stream_get_contents($cardData);
3165
+        }
3166
+
3167
+        return $cardData;
3168
+    }
3169
+
3170
+    /**
3171
+     * @param list<array{href: string, commonName: string, readOnly: bool}> $add
3172
+     * @param list<string> $remove
3173
+     */
3174
+    public function updateShares(IShareable $shareable, array $add, array $remove): void {
3175
+        $this->atomic(function () use ($shareable, $add, $remove): void {
3176
+            $calendarId = $shareable->getResourceId();
3177
+            $calendarRow = $this->getCalendarById($calendarId);
3178
+            if ($calendarRow === null) {
3179
+                throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $calendarId);
3180
+            }
3181
+            $oldShares = $this->getShares($calendarId);
3182
+
3183
+            $this->calendarSharingBackend->updateShares($shareable, $add, $remove, $oldShares);
3184
+
3185
+            $this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent($calendarId, $calendarRow, $oldShares, $add, $remove));
3186
+        }, $this->db);
3187
+    }
3188
+
3189
+    /**
3190
+     * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
3191
+     */
3192
+    public function getShares(int $resourceId): array {
3193
+        return $this->calendarSharingBackend->getShares($resourceId);
3194
+    }
3195
+
3196
+    public function preloadShares(array $resourceIds): void {
3197
+        $this->calendarSharingBackend->preloadShares($resourceIds);
3198
+    }
3199
+
3200
+    /**
3201
+     * @param boolean $value
3202
+     * @param Calendar $calendar
3203
+     * @return string|null
3204
+     */
3205
+    public function setPublishStatus($value, $calendar) {
3206
+        return $this->atomic(function () use ($value, $calendar) {
3207
+            $calendarId = $calendar->getResourceId();
3208
+            $calendarData = $this->getCalendarById($calendarId);
3209
+
3210
+            $query = $this->db->getQueryBuilder();
3211
+            if ($value) {
3212
+                $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
3213
+                $query->insert('dav_shares')
3214
+                    ->values([
3215
+                        'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
3216
+                        'type' => $query->createNamedParameter('calendar'),
3217
+                        'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
3218
+                        'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
3219
+                        'publicuri' => $query->createNamedParameter($publicUri)
3220
+                    ]);
3221
+                $query->executeStatement();
3222
+
3223
+                $this->dispatcher->dispatchTyped(new CalendarPublishedEvent($calendarId, $calendarData, $publicUri));
3224
+                return $publicUri;
3225
+            }
3226
+            $query->delete('dav_shares')
3227
+                ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3228
+                ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
3229
+            $query->executeStatement();
3230
+
3231
+            $this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent($calendarId, $calendarData));
3232
+            return null;
3233
+        }, $this->db);
3234
+    }
3235
+
3236
+    /**
3237
+     * @param Calendar $calendar
3238
+     * @return mixed
3239
+     */
3240
+    public function getPublishStatus($calendar) {
3241
+        $query = $this->db->getQueryBuilder();
3242
+        $result = $query->select('publicuri')
3243
+            ->from('dav_shares')
3244
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3245
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
3246
+            ->executeQuery();
3247
+
3248
+        $row = $result->fetch();
3249
+        $result->closeCursor();
3250
+        return $row ? reset($row) : false;
3251
+    }
3252
+
3253
+    /**
3254
+     * @param int $resourceId
3255
+     * @param list<array{privilege: string, principal: string, protected: bool}> $acl
3256
+     * @return list<array{privilege: string, principal: string, protected: bool}>
3257
+     */
3258
+    public function applyShareAcl(int $resourceId, array $acl): array {
3259
+        $shares = $this->calendarSharingBackend->getShares($resourceId);
3260
+        return $this->calendarSharingBackend->applyShareAcl($shares, $acl);
3261
+    }
3262
+
3263
+    /**
3264
+     * update properties table
3265
+     *
3266
+     * @param int $calendarId
3267
+     * @param string $objectUri
3268
+     * @param string $calendarData
3269
+     * @param int $calendarType
3270
+     */
3271
+    public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
3272
+        $this->cachedObjects = [];
3273
+        $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $calendarType): void {
3274
+            $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
3275
+
3276
+            try {
3277
+                $vCalendar = $this->readCalendarData($calendarData);
3278
+            } catch (\Exception $ex) {
3279
+                return;
3280
+            }
3281
+
3282
+            $this->purgeProperties($calendarId, $objectId);
3283
+
3284
+            $query = $this->db->getQueryBuilder();
3285
+            $query->insert($this->dbObjectPropertiesTable)
3286
+                ->values(
3287
+                    [
3288
+                        'calendarid' => $query->createNamedParameter($calendarId),
3289
+                        'calendartype' => $query->createNamedParameter($calendarType),
3290
+                        'objectid' => $query->createNamedParameter($objectId),
3291
+                        'name' => $query->createParameter('name'),
3292
+                        'parameter' => $query->createParameter('parameter'),
3293
+                        'value' => $query->createParameter('value'),
3294
+                    ]
3295
+                );
3296
+
3297
+            $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
3298
+            foreach ($vCalendar->getComponents() as $component) {
3299
+                if (!in_array($component->name, $indexComponents)) {
3300
+                    continue;
3301
+                }
3302
+
3303
+                foreach ($component->children() as $property) {
3304
+                    if (in_array($property->name, self::INDEXED_PROPERTIES, true)) {
3305
+                        $value = $property->getValue();
3306
+                        // is this a shitty db?
3307
+                        if (!$this->db->supports4ByteText()) {
3308
+                            $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3309
+                        }
3310
+                        $value = mb_strcut($value, 0, 254);
3311
+
3312
+                        $query->setParameter('name', $property->name);
3313
+                        $query->setParameter('parameter', null);
3314
+                        $query->setParameter('value', mb_strcut($value, 0, 254));
3315
+                        $query->executeStatement();
3316
+                    }
3317
+
3318
+                    if (array_key_exists($property->name, self::$indexParameters)) {
3319
+                        $parameters = $property->parameters();
3320
+                        $indexedParametersForProperty = self::$indexParameters[$property->name];
3321
+
3322
+                        foreach ($parameters as $key => $value) {
3323
+                            if (in_array($key, $indexedParametersForProperty)) {
3324
+                                // is this a shitty db?
3325
+                                if ($this->db->supports4ByteText()) {
3326
+                                    $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3327
+                                }
3328
+
3329
+                                $query->setParameter('name', $property->name);
3330
+                                $query->setParameter('parameter', mb_strcut($key, 0, 254));
3331
+                                $query->setParameter('value', mb_strcut($value, 0, 254));
3332
+                                $query->executeStatement();
3333
+                            }
3334
+                        }
3335
+                    }
3336
+                }
3337
+            }
3338
+        }, $this->db);
3339
+    }
3340
+
3341
+    /**
3342
+     * deletes all birthday calendars
3343
+     */
3344
+    public function deleteAllBirthdayCalendars() {
3345
+        $this->atomic(function (): void {
3346
+            $query = $this->db->getQueryBuilder();
3347
+            $result = $query->select(['id'])->from('calendars')
3348
+                ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
3349
+                ->executeQuery();
3350
+
3351
+            while (($row = $result->fetch()) !== false) {
3352
+                $this->deleteCalendar(
3353
+                    $row['id'],
3354
+                    true // No data to keep in the trashbin, if the user re-enables then we regenerate
3355
+                );
3356
+            }
3357
+            $result->closeCursor();
3358
+        }, $this->db);
3359
+    }
3360
+
3361
+    /**
3362
+     * @param $subscriptionId
3363
+     */
3364
+    public function purgeAllCachedEventsForSubscription($subscriptionId) {
3365
+        $this->atomic(function () use ($subscriptionId): void {
3366
+            $query = $this->db->getQueryBuilder();
3367
+            $query->select('uri')
3368
+                ->from('calendarobjects')
3369
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3370
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
3371
+            $stmt = $query->executeQuery();
3372
+
3373
+            $uris = [];
3374
+            while (($row = $stmt->fetch()) !== false) {
3375
+                $uris[] = $row['uri'];
3376
+            }
3377
+            $stmt->closeCursor();
3378
+
3379
+            $query = $this->db->getQueryBuilder();
3380
+            $query->delete('calendarobjects')
3381
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3382
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3383
+                ->executeStatement();
3384
+
3385
+            $query = $this->db->getQueryBuilder();
3386
+            $query->delete('calendarchanges')
3387
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3388
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3389
+                ->executeStatement();
3390
+
3391
+            $query = $this->db->getQueryBuilder();
3392
+            $query->delete($this->dbObjectPropertiesTable)
3393
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3394
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3395
+                ->executeStatement();
3396
+
3397
+            $this->addChanges($subscriptionId, $uris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3398
+        }, $this->db);
3399
+    }
3400
+
3401
+    /**
3402
+     * @param int $subscriptionId
3403
+     * @param array<int> $calendarObjectIds
3404
+     * @param array<string> $calendarObjectUris
3405
+     */
3406
+    public function purgeCachedEventsForSubscription(int $subscriptionId, array $calendarObjectIds, array $calendarObjectUris): void {
3407
+        if (empty($calendarObjectUris)) {
3408
+            return;
3409
+        }
3410
+
3411
+        $this->atomic(function () use ($subscriptionId, $calendarObjectIds, $calendarObjectUris): void {
3412
+            foreach (array_chunk($calendarObjectIds, 1000) as $chunk) {
3413
+                $query = $this->db->getQueryBuilder();
3414
+                $query->delete($this->dbObjectPropertiesTable)
3415
+                    ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3416
+                    ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3417
+                    ->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3418
+                    ->executeStatement();
3419
+
3420
+                $query = $this->db->getQueryBuilder();
3421
+                $query->delete('calendarobjects')
3422
+                    ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3423
+                    ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3424
+                    ->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3425
+                    ->executeStatement();
3426
+            }
3427
+
3428
+            foreach (array_chunk($calendarObjectUris, 1000) as $chunk) {
3429
+                $query = $this->db->getQueryBuilder();
3430
+                $query->delete('calendarchanges')
3431
+                    ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3432
+                    ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3433
+                    ->andWhere($query->expr()->in('uri', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
3434
+                    ->executeStatement();
3435
+            }
3436
+            $this->addChanges($subscriptionId, $calendarObjectUris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3437
+        }, $this->db);
3438
+    }
3439
+
3440
+    /**
3441
+     * Move a calendar from one user to another
3442
+     *
3443
+     * @param string $uriName
3444
+     * @param string $uriOrigin
3445
+     * @param string $uriDestination
3446
+     * @param string $newUriName (optional) the new uriName
3447
+     */
3448
+    public function moveCalendar($uriName, $uriOrigin, $uriDestination, $newUriName = null) {
3449
+        $query = $this->db->getQueryBuilder();
3450
+        $query->update('calendars')
3451
+            ->set('principaluri', $query->createNamedParameter($uriDestination))
3452
+            ->set('uri', $query->createNamedParameter($newUriName ?: $uriName))
3453
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
3454
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
3455
+            ->executeStatement();
3456
+    }
3457
+
3458
+    /**
3459
+     * read VCalendar data into a VCalendar object
3460
+     *
3461
+     * @param string $objectData
3462
+     * @return VCalendar
3463
+     */
3464
+    protected function readCalendarData($objectData) {
3465
+        return Reader::read($objectData);
3466
+    }
3467
+
3468
+    /**
3469
+     * delete all properties from a given calendar object
3470
+     *
3471
+     * @param int $calendarId
3472
+     * @param int $objectId
3473
+     */
3474
+    protected function purgeProperties($calendarId, $objectId) {
3475
+        $this->cachedObjects = [];
3476
+        $query = $this->db->getQueryBuilder();
3477
+        $query->delete($this->dbObjectPropertiesTable)
3478
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
3479
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
3480
+        $query->executeStatement();
3481
+    }
3482
+
3483
+    /**
3484
+     * get ID from a given calendar object
3485
+     *
3486
+     * @param int $calendarId
3487
+     * @param string $uri
3488
+     * @param int $calendarType
3489
+     * @return int
3490
+     */
3491
+    protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
3492
+        $query = $this->db->getQueryBuilder();
3493
+        $query->select('id')
3494
+            ->from('calendarobjects')
3495
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
3496
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
3497
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
3498
+
3499
+        $result = $query->executeQuery();
3500
+        $objectIds = $result->fetch();
3501
+        $result->closeCursor();
3502
+
3503
+        if (!isset($objectIds['id'])) {
3504
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
3505
+        }
3506
+
3507
+        return (int)$objectIds['id'];
3508
+    }
3509
+
3510
+    /**
3511
+     * @throws \InvalidArgumentException
3512
+     */
3513
+    public function pruneOutdatedSyncTokens(int $keep, int $retention): int {
3514
+        if ($keep < 0) {
3515
+            throw new \InvalidArgumentException();
3516
+        }
3517
+
3518
+        $query = $this->db->getQueryBuilder();
3519
+        $query->select($query->func()->max('id'))
3520
+            ->from('calendarchanges');
3521
+
3522
+        $result = $query->executeQuery();
3523
+        $maxId = (int)$result->fetchOne();
3524
+        $result->closeCursor();
3525
+        if (!$maxId || $maxId < $keep) {
3526
+            return 0;
3527
+        }
3528
+
3529
+        $query = $this->db->getQueryBuilder();
3530
+        $query->delete('calendarchanges')
3531
+            ->where(
3532
+                $query->expr()->lte('id', $query->createNamedParameter($maxId - $keep, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
3533
+                $query->expr()->lte('created_at', $query->createNamedParameter($retention)),
3534
+            );
3535
+        return $query->executeStatement();
3536
+    }
3537
+
3538
+    /**
3539
+     * return legacy endpoint principal name to new principal name
3540
+     *
3541
+     * @param $principalUri
3542
+     * @param $toV2
3543
+     * @return string
3544
+     */
3545
+    private function convertPrincipal($principalUri, $toV2) {
3546
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
3547
+            [, $name] = Uri\split($principalUri);
3548
+            if ($toV2 === true) {
3549
+                return "principals/users/$name";
3550
+            }
3551
+            return "principals/$name";
3552
+        }
3553
+        return $principalUri;
3554
+    }
3555
+
3556
+    /**
3557
+     * adds information about an owner to the calendar data
3558
+     *
3559
+     */
3560
+    private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
3561
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
3562
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
3563
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
3564
+            $uri = $calendarInfo[$ownerPrincipalKey];
3565
+        } else {
3566
+            $uri = $calendarInfo['principaluri'];
3567
+        }
3568
+
3569
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
3570
+        if (isset($principalInformation['{DAV:}displayname'])) {
3571
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
3572
+        }
3573
+        return $calendarInfo;
3574
+    }
3575
+
3576
+    private function addResourceTypeToCalendar(array $row, array $calendar): array {
3577
+        if (isset($row['deleted_at'])) {
3578
+            // Columns is set and not null -> this is a deleted calendar
3579
+            // we send a custom resourcetype to hide the deleted calendar
3580
+            // from ordinary DAV clients, but the Calendar app will know
3581
+            // how to handle this special resource.
3582
+            $calendar['{DAV:}resourcetype'] = new DAV\Xml\Property\ResourceType([
3583
+                '{DAV:}collection',
3584
+                sprintf('{%s}deleted-calendar', \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD),
3585
+            ]);
3586
+        }
3587
+        return $calendar;
3588
+    }
3589
+
3590
+    /**
3591
+     * Amend the calendar info with database row data
3592
+     *
3593
+     * @param array $row
3594
+     * @param array $calendar
3595
+     *
3596
+     * @return array
3597
+     */
3598
+    private function rowToCalendar($row, array $calendar): array {
3599
+        foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
3600
+            $value = $row[$dbName];
3601
+            if ($value !== null) {
3602
+                settype($value, $type);
3603
+            }
3604
+            $calendar[$xmlName] = $value;
3605
+        }
3606
+        return $calendar;
3607
+    }
3608
+
3609
+    /**
3610
+     * Amend the subscription info with database row data
3611
+     *
3612
+     * @param array $row
3613
+     * @param array $subscription
3614
+     *
3615
+     * @return array
3616
+     */
3617
+    private function rowToSubscription($row, array $subscription): array {
3618
+        foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
3619
+            $value = $row[$dbName];
3620
+            if ($value !== null) {
3621
+                settype($value, $type);
3622
+            }
3623
+            $subscription[$xmlName] = $value;
3624
+        }
3625
+        return $subscription;
3626
+    }
3627
+
3628
+    /**
3629
+     * delete all invitations from a given calendar
3630
+     *
3631
+     * @since 31.0.0
3632
+     *
3633
+     * @param int $calendarId
3634
+     *
3635
+     * @return void
3636
+     */
3637
+    protected function purgeCalendarInvitations(int $calendarId): void {
3638
+        // select all calendar object uid's
3639
+        $cmd = $this->db->getQueryBuilder();
3640
+        $cmd->select('uid')
3641
+            ->from($this->dbObjectsTable)
3642
+            ->where($cmd->expr()->eq('calendarid', $cmd->createNamedParameter($calendarId)));
3643
+        $allIds = $cmd->executeQuery()->fetchAll(\PDO::FETCH_COLUMN);
3644
+        // delete all links that match object uid's
3645
+        $cmd = $this->db->getQueryBuilder();
3646
+        $cmd->delete($this->dbObjectInvitationsTable)
3647
+            ->where($cmd->expr()->in('uid', $cmd->createParameter('uids'), IQueryBuilder::PARAM_STR_ARRAY));
3648
+        foreach (array_chunk($allIds, 1000) as $chunkIds) {
3649
+            $cmd->setParameter('uids', $chunkIds, IQueryBuilder::PARAM_STR_ARRAY);
3650
+            $cmd->executeStatement();
3651
+        }
3652
+    }
3653
+
3654
+    /**
3655
+     * Delete all invitations from a given calendar event
3656
+     *
3657
+     * @since 31.0.0
3658
+     *
3659
+     * @param string $eventId UID of the event
3660
+     *
3661
+     * @return void
3662
+     */
3663
+    protected function purgeObjectInvitations(string $eventId): void {
3664
+        $cmd = $this->db->getQueryBuilder();
3665
+        $cmd->delete($this->dbObjectInvitationsTable)
3666
+            ->where($cmd->expr()->eq('uid', $cmd->createNamedParameter($eventId, IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR));
3667
+        $cmd->executeStatement();
3668
+    }
3669
+
3670
+    public function unshare(IShareable $shareable, string $principal): void {
3671
+        $this->atomic(function () use ($shareable, $principal): void {
3672
+            $calendarData = $this->getCalendarById($shareable->getResourceId());
3673
+            if ($calendarData === null) {
3674
+                throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $shareable->getResourceId());
3675
+            }
3676
+
3677
+            $oldShares = $this->getShares($shareable->getResourceId());
3678
+            $unshare = $this->calendarSharingBackend->unshare($shareable, $principal);
3679
+
3680
+            if ($unshare) {
3681
+                $this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent(
3682
+                    $shareable->getResourceId(),
3683
+                    $calendarData,
3684
+                    $oldShares,
3685
+                    [],
3686
+                    [$principal]
3687
+                ));
3688
+            }
3689
+        }, $this->db);
3690
+    }
3691 3691
 }
Please login to merge, or discard this patch.