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