Completed
Push — master ( 5262ba...247b25 )
by
unknown
30:03 queued 13s
created
apps/dav/lib/CalDAV/CalDavBackend.php 2 patches
Indentation   +3614 added lines, -3614 removed lines patch added patch discarded remove patch
@@ -108,3618 +108,3618 @@
 block discarded – undo
108 108
  * }
109 109
  */
110 110
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
111
-	use TTransactional;
112
-
113
-	public const CALENDAR_TYPE_CALENDAR = 0;
114
-	public const CALENDAR_TYPE_SUBSCRIPTION = 1;
115
-	public const CALENDAR_TYPE_FEDERATED = 2;
116
-
117
-	public const PERSONAL_CALENDAR_URI = 'personal';
118
-	public const PERSONAL_CALENDAR_NAME = 'Personal';
119
-
120
-	public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
121
-	public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
122
-
123
-	/**
124
-	 * We need to specify a max date, because we need to stop *somewhere*
125
-	 *
126
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
127
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
128
-	 * in 2038-01-19 to avoid problems when the date is converted
129
-	 * to a unix timestamp.
130
-	 */
131
-	public const MAX_DATE = '2038-01-01';
132
-
133
-	public const ACCESS_PUBLIC = 4;
134
-	public const CLASSIFICATION_PUBLIC = 0;
135
-	public const CLASSIFICATION_PRIVATE = 1;
136
-	public const CLASSIFICATION_CONFIDENTIAL = 2;
137
-
138
-	/**
139
-	 * List of CalDAV properties, and how they map to database field names and their type
140
-	 * Add your own properties by simply adding on to this array.
141
-	 *
142
-	 * @var array
143
-	 * @psalm-var array<string, string[]>
144
-	 */
145
-	public array $propertyMap = [
146
-		'{DAV:}displayname' => ['displayname', 'string'],
147
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => ['description', 'string'],
148
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone' => ['timezone', 'string'],
149
-		'{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
150
-		'{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
151
-		'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => ['deleted_at', 'int'],
152
-	];
153
-
154
-	/**
155
-	 * List of subscription properties, and how they map to database field names.
156
-	 *
157
-	 * @var array
158
-	 */
159
-	public array $subscriptionPropertyMap = [
160
-		'{DAV:}displayname' => ['displayname', 'string'],
161
-		'{http://apple.com/ns/ical/}refreshrate' => ['refreshrate', 'string'],
162
-		'{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
163
-		'{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
164
-		'{http://calendarserver.org/ns/}subscribed-strip-todos' => ['striptodos', 'bool'],
165
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms' => ['stripalarms', 'string'],
166
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => ['stripattachments', 'string'],
167
-	];
168
-
169
-	/**
170
-	 * properties to index
171
-	 *
172
-	 * This list has to be kept in sync with ICalendarQuery::SEARCH_PROPERTY_*
173
-	 *
174
-	 * @see \OCP\Calendar\ICalendarQuery
175
-	 */
176
-	private const INDEXED_PROPERTIES = [
177
-		'CATEGORIES',
178
-		'COMMENT',
179
-		'DESCRIPTION',
180
-		'LOCATION',
181
-		'RESOURCES',
182
-		'STATUS',
183
-		'SUMMARY',
184
-		'ATTENDEE',
185
-		'CONTACT',
186
-		'ORGANIZER'
187
-	];
188
-
189
-	/** @var array parameters to index */
190
-	public static array $indexParameters = [
191
-		'ATTENDEE' => ['CN'],
192
-		'ORGANIZER' => ['CN'],
193
-	];
194
-
195
-	/**
196
-	 * @var string[] Map of uid => display name
197
-	 */
198
-	protected array $userDisplayNames;
199
-
200
-	private string $dbObjectsTable = 'calendarobjects';
201
-	private string $dbObjectPropertiesTable = 'calendarobjects_props';
202
-	private string $dbObjectInvitationsTable = 'calendar_invitations';
203
-	private array $cachedObjects = [];
204
-
205
-	public function __construct(
206
-		private IDBConnection $db,
207
-		private Principal $principalBackend,
208
-		private IUserManager $userManager,
209
-		private ISecureRandom $random,
210
-		private LoggerInterface $logger,
211
-		private IEventDispatcher $dispatcher,
212
-		private IConfig $config,
213
-		private Sharing\Backend $calendarSharingBackend,
214
-		private FederatedCalendarMapper $federatedCalendarMapper,
215
-		private bool $legacyEndpoint = false,
216
-	) {
217
-	}
218
-
219
-	/**
220
-	 * Return the number of calendars owned by the given principal.
221
-	 *
222
-	 * Calendars shared with the given principal are not counted!
223
-	 *
224
-	 * By default, this excludes the automatically generated birthday calendar.
225
-	 */
226
-	public function getCalendarsForUserCount(string $principalUri, bool $excludeBirthday = true): int {
227
-		$principalUri = $this->convertPrincipal($principalUri, true);
228
-		$query = $this->db->getQueryBuilder();
229
-		$query->select($query->func()->count('*'))
230
-			->from('calendars');
231
-
232
-		if ($principalUri === '') {
233
-			$query->where($query->expr()->emptyString('principaluri'));
234
-		} else {
235
-			$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
236
-		}
237
-
238
-		if ($excludeBirthday) {
239
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
240
-		}
241
-
242
-		$result = $query->executeQuery();
243
-		$column = (int)$result->fetchOne();
244
-		$result->closeCursor();
245
-		return $column;
246
-	}
247
-
248
-	/**
249
-	 * Return the number of subscriptions for a principal
250
-	 */
251
-	public function getSubscriptionsForUserCount(string $principalUri): int {
252
-		$principalUri = $this->convertPrincipal($principalUri, true);
253
-		$query = $this->db->getQueryBuilder();
254
-		$query->select($query->func()->count('*'))
255
-			->from('calendarsubscriptions');
256
-
257
-		if ($principalUri === '') {
258
-			$query->where($query->expr()->emptyString('principaluri'));
259
-		} else {
260
-			$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
261
-		}
262
-
263
-		$result = $query->executeQuery();
264
-		$column = (int)$result->fetchOne();
265
-		$result->closeCursor();
266
-		return $column;
267
-	}
268
-
269
-	/**
270
-	 * @return array{id: int, deleted_at: int}[]
271
-	 */
272
-	public function getDeletedCalendars(int $deletedBefore): array {
273
-		$qb = $this->db->getQueryBuilder();
274
-		$qb->select(['id', 'deleted_at'])
275
-			->from('calendars')
276
-			->where($qb->expr()->isNotNull('deleted_at'))
277
-			->andWhere($qb->expr()->lt('deleted_at', $qb->createNamedParameter($deletedBefore)));
278
-		$result = $qb->executeQuery();
279
-		$calendars = [];
280
-		while (($row = $result->fetch()) !== false) {
281
-			$calendars[] = [
282
-				'id' => (int)$row['id'],
283
-				'deleted_at' => (int)$row['deleted_at'],
284
-			];
285
-		}
286
-		$result->closeCursor();
287
-		return $calendars;
288
-	}
289
-
290
-	/**
291
-	 * Returns a list of calendars for a principal.
292
-	 *
293
-	 * Every project is an array with the following keys:
294
-	 *  * id, a unique id that will be used by other functions to modify the
295
-	 *    calendar. This can be the same as the uri or a database key.
296
-	 *  * uri, which the basename of the uri with which the calendar is
297
-	 *    accessed.
298
-	 *  * principaluri. The owner of the calendar. Almost always the same as
299
-	 *    principalUri passed to this method.
300
-	 *
301
-	 * Furthermore it can contain webdav properties in clark notation. A very
302
-	 * common one is '{DAV:}displayname'.
303
-	 *
304
-	 * Many clients also require:
305
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
306
-	 * For this property, you can just return an instance of
307
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
308
-	 *
309
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
310
-	 * ACL will automatically be put in read-only mode.
311
-	 *
312
-	 * @param string $principalUri
313
-	 * @return array
314
-	 */
315
-	public function getCalendarsForUser($principalUri) {
316
-		return $this->atomic(function () use ($principalUri) {
317
-			$principalUriOriginal = $principalUri;
318
-			$principalUri = $this->convertPrincipal($principalUri, true);
319
-			$fields = array_column($this->propertyMap, 0);
320
-			$fields[] = 'id';
321
-			$fields[] = 'uri';
322
-			$fields[] = 'synctoken';
323
-			$fields[] = 'components';
324
-			$fields[] = 'principaluri';
325
-			$fields[] = 'transparent';
326
-
327
-			// Making fields a comma-delimited list
328
-			$query = $this->db->getQueryBuilder();
329
-			$query->select($fields)
330
-				->from('calendars')
331
-				->orderBy('calendarorder', 'ASC');
332
-
333
-			if ($principalUri === '') {
334
-				$query->where($query->expr()->emptyString('principaluri'));
335
-			} else {
336
-				$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
337
-			}
338
-
339
-			$result = $query->executeQuery();
340
-
341
-			$calendars = [];
342
-			while ($row = $result->fetch()) {
343
-				$row['principaluri'] = (string)$row['principaluri'];
344
-				$components = [];
345
-				if ($row['components']) {
346
-					$components = explode(',', $row['components']);
347
-				}
348
-
349
-				$calendar = [
350
-					'id' => $row['id'],
351
-					'uri' => $row['uri'],
352
-					'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
353
-					'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
354
-					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
355
-					'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
356
-					'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
357
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
358
-				];
359
-
360
-				$calendar = $this->rowToCalendar($row, $calendar);
361
-				$calendar = $this->addOwnerPrincipalToCalendar($calendar);
362
-				$calendar = $this->addResourceTypeToCalendar($row, $calendar);
363
-
364
-				if (!isset($calendars[$calendar['id']])) {
365
-					$calendars[$calendar['id']] = $calendar;
366
-				}
367
-			}
368
-			$result->closeCursor();
369
-
370
-			// query for shared calendars
371
-			$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
372
-			$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
373
-			$principals[] = $principalUri;
374
-
375
-			$fields = array_column($this->propertyMap, 0);
376
-			$fields = array_map(function (string $field) {
377
-				return 'a.' . $field;
378
-			}, $fields);
379
-			$fields[] = 'a.id';
380
-			$fields[] = 'a.uri';
381
-			$fields[] = 'a.synctoken';
382
-			$fields[] = 'a.components';
383
-			$fields[] = 'a.principaluri';
384
-			$fields[] = 'a.transparent';
385
-			$fields[] = 's.access';
386
-
387
-			$select = $this->db->getQueryBuilder();
388
-			$subSelect = $this->db->getQueryBuilder();
389
-
390
-			$subSelect->select('resourceid')
391
-				->from('dav_shares', 'd')
392
-				->where($subSelect->expr()->eq('d.access', $select->createNamedParameter(Backend::ACCESS_UNSHARED, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
393
-				->andWhere($subSelect->expr()->in('d.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY));
394
-
395
-			$select->select($fields)
396
-				->from('dav_shares', 's')
397
-				->join('s', 'calendars', 'a', $select->expr()->eq('s.resourceid', 'a.id', IQueryBuilder::PARAM_INT))
398
-				->where($select->expr()->in('s.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
399
-				->andWhere($select->expr()->eq('s.type', $select->createNamedParameter('calendar', IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR))
400
-				->andWhere($select->expr()->notIn('a.id', $select->createFunction($subSelect->getSQL()), IQueryBuilder::PARAM_INT_ARRAY));
401
-
402
-			$results = $select->executeQuery();
403
-
404
-			$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
405
-			while ($row = $results->fetch()) {
406
-				$row['principaluri'] = (string)$row['principaluri'];
407
-				if ($row['principaluri'] === $principalUri) {
408
-					continue;
409
-				}
410
-
411
-				$readOnly = (int)$row['access'] === Backend::ACCESS_READ;
412
-				if (isset($calendars[$row['id']])) {
413
-					if ($readOnly) {
414
-						// New share can not have more permissions than the old one.
415
-						continue;
416
-					}
417
-					if (isset($calendars[$row['id']][$readOnlyPropertyName])
418
-						&& $calendars[$row['id']][$readOnlyPropertyName] === 0) {
419
-						// Old share is already read-write, no more permissions can be gained
420
-						continue;
421
-					}
422
-				}
423
-
424
-				[, $name] = Uri\split($row['principaluri']);
425
-				$uri = $row['uri'] . '_shared_by_' . $name;
426
-				$row['displayname'] = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? ($name ?? '')) . ')';
427
-				$components = [];
428
-				if ($row['components']) {
429
-					$components = explode(',', $row['components']);
430
-				}
431
-				$calendar = [
432
-					'id' => $row['id'],
433
-					'uri' => $uri,
434
-					'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
435
-					'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
436
-					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
437
-					'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
438
-					'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
439
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
440
-					$readOnlyPropertyName => $readOnly,
441
-				];
442
-
443
-				$calendar = $this->rowToCalendar($row, $calendar);
444
-				$calendar = $this->addOwnerPrincipalToCalendar($calendar);
445
-				$calendar = $this->addResourceTypeToCalendar($row, $calendar);
446
-
447
-				$calendars[$calendar['id']] = $calendar;
448
-			}
449
-			$result->closeCursor();
450
-
451
-			return array_values($calendars);
452
-		}, $this->db);
453
-	}
454
-
455
-	/**
456
-	 * @param $principalUri
457
-	 * @return array
458
-	 */
459
-	public function getUsersOwnCalendars($principalUri) {
460
-		$principalUri = $this->convertPrincipal($principalUri, true);
461
-		$fields = array_column($this->propertyMap, 0);
462
-		$fields[] = 'id';
463
-		$fields[] = 'uri';
464
-		$fields[] = 'synctoken';
465
-		$fields[] = 'components';
466
-		$fields[] = 'principaluri';
467
-		$fields[] = 'transparent';
468
-		// Making fields a comma-delimited list
469
-		$query = $this->db->getQueryBuilder();
470
-		$query->select($fields)->from('calendars')
471
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
472
-			->orderBy('calendarorder', 'ASC');
473
-		$stmt = $query->executeQuery();
474
-		$calendars = [];
475
-		while ($row = $stmt->fetch()) {
476
-			$row['principaluri'] = (string)$row['principaluri'];
477
-			$components = [];
478
-			if ($row['components']) {
479
-				$components = explode(',', $row['components']);
480
-			}
481
-			$calendar = [
482
-				'id' => $row['id'],
483
-				'uri' => $row['uri'],
484
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
485
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
486
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
487
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
488
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
489
-			];
490
-
491
-			$calendar = $this->rowToCalendar($row, $calendar);
492
-			$calendar = $this->addOwnerPrincipalToCalendar($calendar);
493
-			$calendar = $this->addResourceTypeToCalendar($row, $calendar);
494
-
495
-			if (!isset($calendars[$calendar['id']])) {
496
-				$calendars[$calendar['id']] = $calendar;
497
-			}
498
-		}
499
-		$stmt->closeCursor();
500
-		return array_values($calendars);
501
-	}
502
-
503
-	/**
504
-	 * @return array
505
-	 */
506
-	public function getPublicCalendars() {
507
-		$fields = array_column($this->propertyMap, 0);
508
-		$fields[] = 'a.id';
509
-		$fields[] = 'a.uri';
510
-		$fields[] = 'a.synctoken';
511
-		$fields[] = 'a.components';
512
-		$fields[] = 'a.principaluri';
513
-		$fields[] = 'a.transparent';
514
-		$fields[] = 's.access';
515
-		$fields[] = 's.publicuri';
516
-		$calendars = [];
517
-		$query = $this->db->getQueryBuilder();
518
-		$result = $query->select($fields)
519
-			->from('dav_shares', 's')
520
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
521
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
522
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
523
-			->executeQuery();
524
-
525
-		while ($row = $result->fetch()) {
526
-			$row['principaluri'] = (string)$row['principaluri'];
527
-			[, $name] = Uri\split($row['principaluri']);
528
-			$row['displayname'] = $row['displayname'] . "($name)";
529
-			$components = [];
530
-			if ($row['components']) {
531
-				$components = explode(',', $row['components']);
532
-			}
533
-			$calendar = [
534
-				'id' => $row['id'],
535
-				'uri' => $row['publicuri'],
536
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
537
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
538
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
539
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
540
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
541
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
542
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => true,
543
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
544
-			];
545
-
546
-			$calendar = $this->rowToCalendar($row, $calendar);
547
-			$calendar = $this->addOwnerPrincipalToCalendar($calendar);
548
-			$calendar = $this->addResourceTypeToCalendar($row, $calendar);
549
-
550
-			if (!isset($calendars[$calendar['id']])) {
551
-				$calendars[$calendar['id']] = $calendar;
552
-			}
553
-		}
554
-		$result->closeCursor();
555
-
556
-		return array_values($calendars);
557
-	}
558
-
559
-	/**
560
-	 * @param string $uri
561
-	 * @return array
562
-	 * @throws NotFound
563
-	 */
564
-	public function getPublicCalendar($uri) {
565
-		$fields = array_column($this->propertyMap, 0);
566
-		$fields[] = 'a.id';
567
-		$fields[] = 'a.uri';
568
-		$fields[] = 'a.synctoken';
569
-		$fields[] = 'a.components';
570
-		$fields[] = 'a.principaluri';
571
-		$fields[] = 'a.transparent';
572
-		$fields[] = 's.access';
573
-		$fields[] = 's.publicuri';
574
-		$query = $this->db->getQueryBuilder();
575
-		$result = $query->select($fields)
576
-			->from('dav_shares', 's')
577
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
578
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
579
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
580
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
581
-			->executeQuery();
582
-
583
-		$row = $result->fetch();
584
-
585
-		$result->closeCursor();
586
-
587
-		if ($row === false) {
588
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
589
-		}
590
-
591
-		$row['principaluri'] = (string)$row['principaluri'];
592
-		[, $name] = Uri\split($row['principaluri']);
593
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
594
-		$components = [];
595
-		if ($row['components']) {
596
-			$components = explode(',', $row['components']);
597
-		}
598
-		$calendar = [
599
-			'id' => $row['id'],
600
-			'uri' => $row['publicuri'],
601
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
602
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
603
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
604
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
605
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
606
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
607
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => true,
608
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
609
-		];
610
-
611
-		$calendar = $this->rowToCalendar($row, $calendar);
612
-		$calendar = $this->addOwnerPrincipalToCalendar($calendar);
613
-		$calendar = $this->addResourceTypeToCalendar($row, $calendar);
614
-
615
-		return $calendar;
616
-	}
617
-
618
-	/**
619
-	 * @param string $principal
620
-	 * @param string $uri
621
-	 * @return array|null
622
-	 */
623
-	public function getCalendarByUri($principal, $uri) {
624
-		$fields = array_column($this->propertyMap, 0);
625
-		$fields[] = 'id';
626
-		$fields[] = 'uri';
627
-		$fields[] = 'synctoken';
628
-		$fields[] = 'components';
629
-		$fields[] = 'principaluri';
630
-		$fields[] = 'transparent';
631
-
632
-		// Making fields a comma-delimited list
633
-		$query = $this->db->getQueryBuilder();
634
-		$query->select($fields)->from('calendars')
635
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
636
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
637
-			->setMaxResults(1);
638
-		$stmt = $query->executeQuery();
639
-
640
-		$row = $stmt->fetch();
641
-		$stmt->closeCursor();
642
-		if ($row === false) {
643
-			return null;
644
-		}
645
-
646
-		$row['principaluri'] = (string)$row['principaluri'];
647
-		$components = [];
648
-		if ($row['components']) {
649
-			$components = explode(',', $row['components']);
650
-		}
651
-
652
-		$calendar = [
653
-			'id' => $row['id'],
654
-			'uri' => $row['uri'],
655
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
656
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
657
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
658
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
659
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
660
-		];
661
-
662
-		$calendar = $this->rowToCalendar($row, $calendar);
663
-		$calendar = $this->addOwnerPrincipalToCalendar($calendar);
664
-		$calendar = $this->addResourceTypeToCalendar($row, $calendar);
665
-
666
-		return $calendar;
667
-	}
668
-
669
-	/**
670
-	 * @psalm-return CalendarInfo|null
671
-	 * @return array|null
672
-	 */
673
-	public function getCalendarById(int $calendarId): ?array {
674
-		$fields = array_column($this->propertyMap, 0);
675
-		$fields[] = 'id';
676
-		$fields[] = 'uri';
677
-		$fields[] = 'synctoken';
678
-		$fields[] = 'components';
679
-		$fields[] = 'principaluri';
680
-		$fields[] = 'transparent';
681
-
682
-		// Making fields a comma-delimited list
683
-		$query = $this->db->getQueryBuilder();
684
-		$query->select($fields)->from('calendars')
685
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
686
-			->setMaxResults(1);
687
-		$stmt = $query->executeQuery();
688
-
689
-		$row = $stmt->fetch();
690
-		$stmt->closeCursor();
691
-		if ($row === false) {
692
-			return null;
693
-		}
694
-
695
-		$row['principaluri'] = (string)$row['principaluri'];
696
-		$components = [];
697
-		if ($row['components']) {
698
-			$components = explode(',', $row['components']);
699
-		}
700
-
701
-		$calendar = [
702
-			'id' => $row['id'],
703
-			'uri' => $row['uri'],
704
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
705
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
706
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?? 0,
707
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
708
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
709
-		];
710
-
711
-		$calendar = $this->rowToCalendar($row, $calendar);
712
-		$calendar = $this->addOwnerPrincipalToCalendar($calendar);
713
-		$calendar = $this->addResourceTypeToCalendar($row, $calendar);
714
-
715
-		return $calendar;
716
-	}
717
-
718
-	/**
719
-	 * @param $subscriptionId
720
-	 */
721
-	public function getSubscriptionById($subscriptionId) {
722
-		$fields = array_column($this->subscriptionPropertyMap, 0);
723
-		$fields[] = 'id';
724
-		$fields[] = 'uri';
725
-		$fields[] = 'source';
726
-		$fields[] = 'synctoken';
727
-		$fields[] = 'principaluri';
728
-		$fields[] = 'lastmodified';
729
-
730
-		$query = $this->db->getQueryBuilder();
731
-		$query->select($fields)
732
-			->from('calendarsubscriptions')
733
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
734
-			->orderBy('calendarorder', 'asc');
735
-		$stmt = $query->executeQuery();
736
-
737
-		$row = $stmt->fetch();
738
-		$stmt->closeCursor();
739
-		if ($row === false) {
740
-			return null;
741
-		}
742
-
743
-		$row['principaluri'] = (string)$row['principaluri'];
744
-		$subscription = [
745
-			'id' => $row['id'],
746
-			'uri' => $row['uri'],
747
-			'principaluri' => $row['principaluri'],
748
-			'source' => $row['source'],
749
-			'lastmodified' => $row['lastmodified'],
750
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
751
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
752
-		];
753
-
754
-		return $this->rowToSubscription($row, $subscription);
755
-	}
756
-
757
-	public function getSubscriptionByUri(string $principal, string $uri): ?array {
758
-		$fields = array_column($this->subscriptionPropertyMap, 0);
759
-		$fields[] = 'id';
760
-		$fields[] = 'uri';
761
-		$fields[] = 'source';
762
-		$fields[] = 'synctoken';
763
-		$fields[] = 'principaluri';
764
-		$fields[] = 'lastmodified';
765
-
766
-		$query = $this->db->getQueryBuilder();
767
-		$query->select($fields)
768
-			->from('calendarsubscriptions')
769
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
770
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
771
-			->setMaxResults(1);
772
-		$stmt = $query->executeQuery();
773
-
774
-		$row = $stmt->fetch();
775
-		$stmt->closeCursor();
776
-		if ($row === false) {
777
-			return null;
778
-		}
779
-
780
-		$row['principaluri'] = (string)$row['principaluri'];
781
-		$subscription = [
782
-			'id' => $row['id'],
783
-			'uri' => $row['uri'],
784
-			'principaluri' => $row['principaluri'],
785
-			'source' => $row['source'],
786
-			'lastmodified' => $row['lastmodified'],
787
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
788
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
789
-		];
790
-
791
-		return $this->rowToSubscription($row, $subscription);
792
-	}
793
-
794
-	/**
795
-	 * Creates a new calendar for a principal.
796
-	 *
797
-	 * If the creation was a success, an id must be returned that can be used to reference
798
-	 * this calendar in other methods, such as updateCalendar.
799
-	 *
800
-	 * @param string $principalUri
801
-	 * @param string $calendarUri
802
-	 * @param array $properties
803
-	 * @return int
804
-	 *
805
-	 * @throws CalendarException
806
-	 */
807
-	public function createCalendar($principalUri, $calendarUri, array $properties) {
808
-		if (strlen($calendarUri) > 255) {
809
-			throw new CalendarException('URI too long. Calendar not created');
810
-		}
811
-
812
-		$values = [
813
-			'principaluri' => $this->convertPrincipal($principalUri, true),
814
-			'uri' => $calendarUri,
815
-			'synctoken' => 1,
816
-			'transparent' => 0,
817
-			'components' => 'VEVENT,VTODO,VJOURNAL',
818
-			'displayname' => $calendarUri
819
-		];
820
-
821
-		// Default value
822
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
823
-		if (isset($properties[$sccs])) {
824
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
825
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
826
-			}
827
-			$values['components'] = implode(',', $properties[$sccs]->getValue());
828
-		} elseif (isset($properties['components'])) {
829
-			// Allow to provide components internally without having
830
-			// to create a SupportedCalendarComponentSet object
831
-			$values['components'] = $properties['components'];
832
-		}
833
-
834
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
835
-		if (isset($properties[$transp])) {
836
-			$values['transparent'] = (int)($properties[$transp]->getValue() === 'transparent');
837
-		}
838
-
839
-		foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
840
-			if (isset($properties[$xmlName])) {
841
-				$values[$dbName] = $properties[$xmlName];
842
-			}
843
-		}
844
-
845
-		[$calendarId, $calendarData] = $this->atomic(function () use ($values) {
846
-			$query = $this->db->getQueryBuilder();
847
-			$query->insert('calendars');
848
-			foreach ($values as $column => $value) {
849
-				$query->setValue($column, $query->createNamedParameter($value));
850
-			}
851
-			$query->executeStatement();
852
-			$calendarId = $query->getLastInsertId();
853
-
854
-			$calendarData = $this->getCalendarById($calendarId);
855
-			return [$calendarId, $calendarData];
856
-		}, $this->db);
857
-
858
-		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
859
-
860
-		return $calendarId;
861
-	}
862
-
863
-	/**
864
-	 * Updates properties for a calendar.
865
-	 *
866
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
867
-	 * To do the actual updates, you must tell this object which properties
868
-	 * you're going to process with the handle() method.
869
-	 *
870
-	 * Calling the handle method is like telling the PropPatch object "I
871
-	 * promise I can handle updating this property".
872
-	 *
873
-	 * Read the PropPatch documentation for more info and examples.
874
-	 *
875
-	 * @param mixed $calendarId
876
-	 * @param PropPatch $propPatch
877
-	 * @return void
878
-	 */
879
-	public function updateCalendar($calendarId, PropPatch $propPatch) {
880
-		$supportedProperties = array_keys($this->propertyMap);
881
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
882
-
883
-		$propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
884
-			$newValues = [];
885
-			foreach ($mutations as $propertyName => $propertyValue) {
886
-				switch ($propertyName) {
887
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
888
-						$fieldName = 'transparent';
889
-						$newValues[$fieldName] = (int)($propertyValue->getValue() === 'transparent');
890
-						break;
891
-					default:
892
-						$fieldName = $this->propertyMap[$propertyName][0];
893
-						$newValues[$fieldName] = $propertyValue;
894
-						break;
895
-				}
896
-			}
897
-			[$calendarData, $shares] = $this->atomic(function () use ($calendarId, $newValues) {
898
-				$query = $this->db->getQueryBuilder();
899
-				$query->update('calendars');
900
-				foreach ($newValues as $fieldName => $value) {
901
-					$query->set($fieldName, $query->createNamedParameter($value));
902
-				}
903
-				$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
904
-				$query->executeStatement();
905
-
906
-				$this->addChanges($calendarId, [''], 2);
907
-
908
-				$calendarData = $this->getCalendarById($calendarId);
909
-				$shares = $this->getShares($calendarId);
910
-				return [$calendarData, $shares];
911
-			}, $this->db);
912
-
913
-			$this->dispatcher->dispatchTyped(new CalendarUpdatedEvent($calendarId, $calendarData, $shares, $mutations));
914
-
915
-			return true;
916
-		});
917
-	}
918
-
919
-	/**
920
-	 * Delete a calendar and all it's objects
921
-	 *
922
-	 * @param mixed $calendarId
923
-	 * @return void
924
-	 */
925
-	public function deleteCalendar($calendarId, bool $forceDeletePermanently = false) {
926
-		$this->atomic(function () use ($calendarId, $forceDeletePermanently): void {
927
-			// The calendar is deleted right away if this is either enforced by the caller
928
-			// or the special contacts birthday calendar or when the preference of an empty
929
-			// retention (0 seconds) is set, which signals a disabled trashbin.
930
-			$calendarData = $this->getCalendarById($calendarId);
931
-			$isBirthdayCalendar = isset($calendarData['uri']) && $calendarData['uri'] === BirthdayService::BIRTHDAY_CALENDAR_URI;
932
-			$trashbinDisabled = $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0';
933
-			if ($forceDeletePermanently || $isBirthdayCalendar || $trashbinDisabled) {
934
-				$calendarData = $this->getCalendarById($calendarId);
935
-				$shares = $this->getShares($calendarId);
936
-
937
-				$this->purgeCalendarInvitations($calendarId);
938
-
939
-				$qbDeleteCalendarObjectProps = $this->db->getQueryBuilder();
940
-				$qbDeleteCalendarObjectProps->delete($this->dbObjectPropertiesTable)
941
-					->where($qbDeleteCalendarObjectProps->expr()->eq('calendarid', $qbDeleteCalendarObjectProps->createNamedParameter($calendarId)))
942
-					->andWhere($qbDeleteCalendarObjectProps->expr()->eq('calendartype', $qbDeleteCalendarObjectProps->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
943
-					->executeStatement();
944
-
945
-				$qbDeleteCalendarObjects = $this->db->getQueryBuilder();
946
-				$qbDeleteCalendarObjects->delete('calendarobjects')
947
-					->where($qbDeleteCalendarObjects->expr()->eq('calendarid', $qbDeleteCalendarObjects->createNamedParameter($calendarId)))
948
-					->andWhere($qbDeleteCalendarObjects->expr()->eq('calendartype', $qbDeleteCalendarObjects->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
949
-					->executeStatement();
950
-
951
-				$qbDeleteCalendarChanges = $this->db->getQueryBuilder();
952
-				$qbDeleteCalendarChanges->delete('calendarchanges')
953
-					->where($qbDeleteCalendarChanges->expr()->eq('calendarid', $qbDeleteCalendarChanges->createNamedParameter($calendarId)))
954
-					->andWhere($qbDeleteCalendarChanges->expr()->eq('calendartype', $qbDeleteCalendarChanges->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
955
-					->executeStatement();
956
-
957
-				$this->calendarSharingBackend->deleteAllShares($calendarId);
958
-
959
-				$qbDeleteCalendar = $this->db->getQueryBuilder();
960
-				$qbDeleteCalendar->delete('calendars')
961
-					->where($qbDeleteCalendar->expr()->eq('id', $qbDeleteCalendar->createNamedParameter($calendarId)))
962
-					->executeStatement();
963
-
964
-				// Only dispatch if we actually deleted anything
965
-				if ($calendarData) {
966
-					$this->dispatcher->dispatchTyped(new CalendarDeletedEvent($calendarId, $calendarData, $shares));
967
-				}
968
-			} else {
969
-				$qbMarkCalendarDeleted = $this->db->getQueryBuilder();
970
-				$qbMarkCalendarDeleted->update('calendars')
971
-					->set('deleted_at', $qbMarkCalendarDeleted->createNamedParameter(time()))
972
-					->where($qbMarkCalendarDeleted->expr()->eq('id', $qbMarkCalendarDeleted->createNamedParameter($calendarId)))
973
-					->executeStatement();
974
-
975
-				$calendarData = $this->getCalendarById($calendarId);
976
-				$shares = $this->getShares($calendarId);
977
-				if ($calendarData) {
978
-					$this->dispatcher->dispatchTyped(new CalendarMovedToTrashEvent(
979
-						$calendarId,
980
-						$calendarData,
981
-						$shares
982
-					));
983
-				}
984
-			}
985
-		}, $this->db);
986
-	}
987
-
988
-	public function restoreCalendar(int $id): void {
989
-		$this->atomic(function () use ($id): void {
990
-			$qb = $this->db->getQueryBuilder();
991
-			$update = $qb->update('calendars')
992
-				->set('deleted_at', $qb->createNamedParameter(null))
993
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
994
-			$update->executeStatement();
995
-
996
-			$calendarData = $this->getCalendarById($id);
997
-			$shares = $this->getShares($id);
998
-			if ($calendarData === null) {
999
-				throw new RuntimeException('Calendar data that was just written can\'t be read back. Check your database configuration.');
1000
-			}
1001
-			$this->dispatcher->dispatchTyped(new CalendarRestoredEvent(
1002
-				$id,
1003
-				$calendarData,
1004
-				$shares
1005
-			));
1006
-		}, $this->db);
1007
-	}
1008
-
1009
-	/**
1010
-	 * Returns all calendar entries as a stream of data
1011
-	 *
1012
-	 * @since 32.0.0
1013
-	 *
1014
-	 * @return Generator<array>
1015
-	 */
1016
-	public function exportCalendar(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR, ?CalendarExportOptions $options = null): Generator {
1017
-		// extract options
1018
-		$rangeStart = $options?->getRangeStart();
1019
-		$rangeCount = $options?->getRangeCount();
1020
-		// construct query
1021
-		$qb = $this->db->getQueryBuilder();
1022
-		$qb->select('*')
1023
-			->from('calendarobjects')
1024
-			->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1025
-			->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1026
-			->andWhere($qb->expr()->isNull('deleted_at'));
1027
-		if ($rangeStart !== null) {
1028
-			$qb->andWhere($qb->expr()->gt('uid', $qb->createNamedParameter($rangeStart)));
1029
-		}
1030
-		if ($rangeCount !== null) {
1031
-			$qb->setMaxResults($rangeCount);
1032
-		}
1033
-		if ($rangeStart !== null || $rangeCount !== null) {
1034
-			$qb->orderBy('uid', 'ASC');
1035
-		}
1036
-		$rs = $qb->executeQuery();
1037
-		// iterate through results
1038
-		try {
1039
-			while (($row = $rs->fetch()) !== false) {
1040
-				yield $row;
1041
-			}
1042
-		} finally {
1043
-			$rs->closeCursor();
1044
-		}
1045
-	}
1046
-
1047
-	/**
1048
-	 * Returns all calendar objects with limited metadata for a calendar
1049
-	 *
1050
-	 * Every item contains an array with the following keys:
1051
-	 *   * id - the table row id
1052
-	 *   * etag - An arbitrary string
1053
-	 *   * uri - a unique key which will be used to construct the uri. This can
1054
-	 *     be any arbitrary string.
1055
-	 *   * calendardata - The iCalendar-compatible calendar data
1056
-	 *
1057
-	 * @param mixed $calendarId
1058
-	 * @param int $calendarType
1059
-	 * @return array
1060
-	 */
1061
-	public function getLimitedCalendarObjects(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1062
-		$query = $this->db->getQueryBuilder();
1063
-		$query->select(['id','uid', 'etag', 'uri', 'calendardata'])
1064
-			->from('calendarobjects')
1065
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1066
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1067
-			->andWhere($query->expr()->isNull('deleted_at'));
1068
-		$stmt = $query->executeQuery();
1069
-
1070
-		$result = [];
1071
-		while (($row = $stmt->fetch()) !== false) {
1072
-			$result[$row['uid']] = [
1073
-				'id' => $row['id'],
1074
-				'etag' => $row['etag'],
1075
-				'uri' => $row['uri'],
1076
-				'calendardata' => $row['calendardata'],
1077
-			];
1078
-		}
1079
-		$stmt->closeCursor();
1080
-
1081
-		return $result;
1082
-	}
1083
-
1084
-	/**
1085
-	 * Delete all of an user's shares
1086
-	 *
1087
-	 * @param string $principaluri
1088
-	 * @return void
1089
-	 */
1090
-	public function deleteAllSharesByUser($principaluri) {
1091
-		$this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
1092
-	}
1093
-
1094
-	/**
1095
-	 * Returns all calendar objects within a calendar.
1096
-	 *
1097
-	 * Every item contains an array with the following keys:
1098
-	 *   * calendardata - The iCalendar-compatible calendar data
1099
-	 *   * uri - a unique key which will be used to construct the uri. This can
1100
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
1101
-	 *     good idea. This is only the basename, or filename, not the full
1102
-	 *     path.
1103
-	 *   * lastmodified - a timestamp of the last modification time
1104
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
1105
-	 *   '"abcdef"')
1106
-	 *   * size - The size of the calendar objects, in bytes.
1107
-	 *   * component - optional, a string containing the type of object, such
1108
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
1109
-	 *     the Content-Type header.
1110
-	 *
1111
-	 * Note that the etag is optional, but it's highly encouraged to return for
1112
-	 * speed reasons.
1113
-	 *
1114
-	 * The calendardata is also optional. If it's not returned
1115
-	 * 'getCalendarObject' will be called later, which *is* expected to return
1116
-	 * calendardata.
1117
-	 *
1118
-	 * If neither etag or size are specified, the calendardata will be
1119
-	 * used/fetched to determine these numbers. If both are specified the
1120
-	 * amount of times this is needed is reduced by a great degree.
1121
-	 *
1122
-	 * @param mixed $calendarId
1123
-	 * @param int $calendarType
1124
-	 * @return array
1125
-	 */
1126
-	public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1127
-		$query = $this->db->getQueryBuilder();
1128
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
1129
-			->from('calendarobjects')
1130
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1131
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1132
-			->andWhere($query->expr()->isNull('deleted_at'));
1133
-		$stmt = $query->executeQuery();
1134
-
1135
-		$result = [];
1136
-		while (($row = $stmt->fetch()) !== false) {
1137
-			$result[] = [
1138
-				'id' => $row['id'],
1139
-				'uri' => $row['uri'],
1140
-				'lastmodified' => $row['lastmodified'],
1141
-				'etag' => '"' . $row['etag'] . '"',
1142
-				'calendarid' => $row['calendarid'],
1143
-				'size' => (int)$row['size'],
1144
-				'component' => strtolower($row['componenttype']),
1145
-				'classification' => (int)$row['classification']
1146
-			];
1147
-		}
1148
-		$stmt->closeCursor();
1149
-
1150
-		return $result;
1151
-	}
1152
-
1153
-	public function getDeletedCalendarObjects(int $deletedBefore): array {
1154
-		$query = $this->db->getQueryBuilder();
1155
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.calendartype', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1156
-			->from('calendarobjects', 'co')
1157
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1158
-			->where($query->expr()->isNotNull('co.deleted_at'))
1159
-			->andWhere($query->expr()->lt('co.deleted_at', $query->createNamedParameter($deletedBefore)));
1160
-		$stmt = $query->executeQuery();
1161
-
1162
-		$result = [];
1163
-		while (($row = $stmt->fetch()) !== false) {
1164
-			$result[] = [
1165
-				'id' => $row['id'],
1166
-				'uri' => $row['uri'],
1167
-				'lastmodified' => $row['lastmodified'],
1168
-				'etag' => '"' . $row['etag'] . '"',
1169
-				'calendarid' => (int)$row['calendarid'],
1170
-				'calendartype' => (int)$row['calendartype'],
1171
-				'size' => (int)$row['size'],
1172
-				'component' => strtolower($row['componenttype']),
1173
-				'classification' => (int)$row['classification'],
1174
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1175
-			];
1176
-		}
1177
-		$stmt->closeCursor();
1178
-
1179
-		return $result;
1180
-	}
1181
-
1182
-	/**
1183
-	 * Return all deleted calendar objects by the given principal that are not
1184
-	 * in deleted calendars.
1185
-	 *
1186
-	 * @param string $principalUri
1187
-	 * @return array
1188
-	 * @throws Exception
1189
-	 */
1190
-	public function getDeletedCalendarObjectsByPrincipal(string $principalUri): array {
1191
-		$query = $this->db->getQueryBuilder();
1192
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1193
-			->selectAlias('c.uri', 'calendaruri')
1194
-			->from('calendarobjects', 'co')
1195
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1196
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1197
-			->andWhere($query->expr()->isNotNull('co.deleted_at'))
1198
-			->andWhere($query->expr()->isNull('c.deleted_at'));
1199
-		$stmt = $query->executeQuery();
1200
-
1201
-		$result = [];
1202
-		while ($row = $stmt->fetch()) {
1203
-			$result[] = [
1204
-				'id' => $row['id'],
1205
-				'uri' => $row['uri'],
1206
-				'lastmodified' => $row['lastmodified'],
1207
-				'etag' => '"' . $row['etag'] . '"',
1208
-				'calendarid' => $row['calendarid'],
1209
-				'calendaruri' => $row['calendaruri'],
1210
-				'size' => (int)$row['size'],
1211
-				'component' => strtolower($row['componenttype']),
1212
-				'classification' => (int)$row['classification'],
1213
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1214
-			];
1215
-		}
1216
-		$stmt->closeCursor();
1217
-
1218
-		return $result;
1219
-	}
1220
-
1221
-	/**
1222
-	 * Returns information from a single calendar object, based on it's object
1223
-	 * uri.
1224
-	 *
1225
-	 * The object uri is only the basename, or filename and not a full path.
1226
-	 *
1227
-	 * The returned array must have the same keys as getCalendarObjects. The
1228
-	 * 'calendardata' object is required here though, while it's not required
1229
-	 * for getCalendarObjects.
1230
-	 *
1231
-	 * This method must return null if the object did not exist.
1232
-	 *
1233
-	 * @param mixed $calendarId
1234
-	 * @param string $objectUri
1235
-	 * @param int $calendarType
1236
-	 * @return array|null
1237
-	 */
1238
-	public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1239
-		$key = $calendarId . '::' . $objectUri . '::' . $calendarType;
1240
-		if (isset($this->cachedObjects[$key])) {
1241
-			return $this->cachedObjects[$key];
1242
-		}
1243
-		$query = $this->db->getQueryBuilder();
1244
-		$query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1245
-			->from('calendarobjects')
1246
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1247
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1248
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1249
-		$stmt = $query->executeQuery();
1250
-		$row = $stmt->fetch();
1251
-		$stmt->closeCursor();
1252
-
1253
-		if (!$row) {
1254
-			return null;
1255
-		}
1256
-
1257
-		$object = $this->rowToCalendarObject($row);
1258
-		$this->cachedObjects[$key] = $object;
1259
-		return $object;
1260
-	}
1261
-
1262
-	private function rowToCalendarObject(array $row): array {
1263
-		return [
1264
-			'id' => $row['id'],
1265
-			'uri' => $row['uri'],
1266
-			'uid' => $row['uid'],
1267
-			'lastmodified' => $row['lastmodified'],
1268
-			'etag' => '"' . $row['etag'] . '"',
1269
-			'calendarid' => $row['calendarid'],
1270
-			'size' => (int)$row['size'],
1271
-			'calendardata' => $this->readBlob($row['calendardata']),
1272
-			'component' => strtolower($row['componenttype']),
1273
-			'classification' => (int)$row['classification'],
1274
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1275
-		];
1276
-	}
1277
-
1278
-	/**
1279
-	 * Returns a list of calendar objects.
1280
-	 *
1281
-	 * This method should work identical to getCalendarObject, but instead
1282
-	 * return all the calendar objects in the list as an array.
1283
-	 *
1284
-	 * If the backend supports this, it may allow for some speed-ups.
1285
-	 *
1286
-	 * @param mixed $calendarId
1287
-	 * @param string[] $uris
1288
-	 * @param int $calendarType
1289
-	 * @return array
1290
-	 */
1291
-	public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1292
-		if (empty($uris)) {
1293
-			return [];
1294
-		}
1295
-
1296
-		$chunks = array_chunk($uris, 100);
1297
-		$objects = [];
1298
-
1299
-		$query = $this->db->getQueryBuilder();
1300
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1301
-			->from('calendarobjects')
1302
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1303
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1304
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1305
-			->andWhere($query->expr()->isNull('deleted_at'));
1306
-
1307
-		foreach ($chunks as $uris) {
1308
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1309
-			$result = $query->executeQuery();
1310
-
1311
-			while ($row = $result->fetch()) {
1312
-				$objects[] = [
1313
-					'id' => $row['id'],
1314
-					'uri' => $row['uri'],
1315
-					'lastmodified' => $row['lastmodified'],
1316
-					'etag' => '"' . $row['etag'] . '"',
1317
-					'calendarid' => $row['calendarid'],
1318
-					'size' => (int)$row['size'],
1319
-					'calendardata' => $this->readBlob($row['calendardata']),
1320
-					'component' => strtolower($row['componenttype']),
1321
-					'classification' => (int)$row['classification']
1322
-				];
1323
-			}
1324
-			$result->closeCursor();
1325
-		}
1326
-
1327
-		return $objects;
1328
-	}
1329
-
1330
-	/**
1331
-	 * Creates a new calendar object.
1332
-	 *
1333
-	 * The object uri is only the basename, or filename and not a full path.
1334
-	 *
1335
-	 * It is possible return an etag from this function, which will be used in
1336
-	 * the response to this PUT request. Note that the ETag must be surrounded
1337
-	 * by double-quotes.
1338
-	 *
1339
-	 * However, you should only really return this ETag if you don't mangle the
1340
-	 * calendar-data. If the result of a subsequent GET to this object is not
1341
-	 * the exact same as this request body, you should omit the ETag.
1342
-	 *
1343
-	 * @param mixed $calendarId
1344
-	 * @param string $objectUri
1345
-	 * @param string $calendarData
1346
-	 * @param int $calendarType
1347
-	 * @return string
1348
-	 */
1349
-	public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1350
-		$this->cachedObjects = [];
1351
-		$extraData = $this->getDenormalizedData($calendarData);
1352
-
1353
-		return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1354
-			// Try to detect duplicates
1355
-			$qb = $this->db->getQueryBuilder();
1356
-			$qb->select($qb->func()->count('*'))
1357
-				->from('calendarobjects')
1358
-				->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1359
-				->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($extraData['uid'])))
1360
-				->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1361
-				->andWhere($qb->expr()->isNull('deleted_at'));
1362
-			$result = $qb->executeQuery();
1363
-			$count = (int)$result->fetchOne();
1364
-			$result->closeCursor();
1365
-
1366
-			if ($count !== 0) {
1367
-				throw new BadRequest('Calendar object with uid already exists in this calendar collection.');
1368
-			}
1369
-			// For a more specific error message we also try to explicitly look up the UID but as a deleted entry
1370
-			$qbDel = $this->db->getQueryBuilder();
1371
-			$qbDel->select('*')
1372
-				->from('calendarobjects')
1373
-				->where($qbDel->expr()->eq('calendarid', $qbDel->createNamedParameter($calendarId)))
1374
-				->andWhere($qbDel->expr()->eq('uid', $qbDel->createNamedParameter($extraData['uid'])))
1375
-				->andWhere($qbDel->expr()->eq('calendartype', $qbDel->createNamedParameter($calendarType)))
1376
-				->andWhere($qbDel->expr()->isNotNull('deleted_at'));
1377
-			$result = $qbDel->executeQuery();
1378
-			$found = $result->fetch();
1379
-			$result->closeCursor();
1380
-			if ($found !== false) {
1381
-				// the object existed previously but has been deleted
1382
-				// remove the trashbin entry and continue as if it was a new object
1383
-				$this->deleteCalendarObject($calendarId, $found['uri']);
1384
-			}
1385
-
1386
-			$query = $this->db->getQueryBuilder();
1387
-			$query->insert('calendarobjects')
1388
-				->values([
1389
-					'calendarid' => $query->createNamedParameter($calendarId),
1390
-					'uri' => $query->createNamedParameter($objectUri),
1391
-					'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1392
-					'lastmodified' => $query->createNamedParameter(time()),
1393
-					'etag' => $query->createNamedParameter($extraData['etag']),
1394
-					'size' => $query->createNamedParameter($extraData['size']),
1395
-					'componenttype' => $query->createNamedParameter($extraData['componentType']),
1396
-					'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1397
-					'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1398
-					'classification' => $query->createNamedParameter($extraData['classification']),
1399
-					'uid' => $query->createNamedParameter($extraData['uid']),
1400
-					'calendartype' => $query->createNamedParameter($calendarType),
1401
-				])
1402
-				->executeStatement();
1403
-
1404
-			$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1405
-			$this->addChanges($calendarId, [$objectUri], 1, $calendarType);
1406
-
1407
-			$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1408
-			assert($objectRow !== null);
1409
-
1410
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1411
-				$calendarRow = $this->getCalendarById($calendarId);
1412
-				$shares = $this->getShares($calendarId);
1413
-
1414
-				$this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1415
-			} elseif ($calendarType === self::CALENDAR_TYPE_SUBSCRIPTION) {
1416
-				$subscriptionRow = $this->getSubscriptionById($calendarId);
1417
-
1418
-				$this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1419
-			} elseif ($calendarType === self::CALENDAR_TYPE_FEDERATED) {
1420
-				// TODO: implement custom event for federated calendars
1421
-			}
1422
-
1423
-			return '"' . $extraData['etag'] . '"';
1424
-		}, $this->db);
1425
-	}
1426
-
1427
-	/**
1428
-	 * Updates an existing calendarobject, based on it's uri.
1429
-	 *
1430
-	 * The object uri is only the basename, or filename and not a full path.
1431
-	 *
1432
-	 * It is possible return an etag from this function, which will be used in
1433
-	 * the response to this PUT request. Note that the ETag must be surrounded
1434
-	 * by double-quotes.
1435
-	 *
1436
-	 * However, you should only really return this ETag if you don't mangle the
1437
-	 * calendar-data. If the result of a subsequent GET to this object is not
1438
-	 * the exact same as this request body, you should omit the ETag.
1439
-	 *
1440
-	 * @param mixed $calendarId
1441
-	 * @param string $objectUri
1442
-	 * @param string $calendarData
1443
-	 * @param int $calendarType
1444
-	 * @return string
1445
-	 */
1446
-	public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1447
-		$this->cachedObjects = [];
1448
-		$extraData = $this->getDenormalizedData($calendarData);
1449
-
1450
-		return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1451
-			$query = $this->db->getQueryBuilder();
1452
-			$query->update('calendarobjects')
1453
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1454
-				->set('lastmodified', $query->createNamedParameter(time()))
1455
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1456
-				->set('size', $query->createNamedParameter($extraData['size']))
1457
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1458
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1459
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1460
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1461
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1462
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1463
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1464
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1465
-				->executeStatement();
1466
-
1467
-			$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1468
-			$this->addChanges($calendarId, [$objectUri], 2, $calendarType);
1469
-
1470
-			$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1471
-			if (is_array($objectRow)) {
1472
-				if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1473
-					$calendarRow = $this->getCalendarById($calendarId);
1474
-					$shares = $this->getShares($calendarId);
1475
-
1476
-					$this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1477
-				} elseif ($calendarType === self::CALENDAR_TYPE_SUBSCRIPTION) {
1478
-					$subscriptionRow = $this->getSubscriptionById($calendarId);
1479
-
1480
-					$this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1481
-				} elseif ($calendarType === self::CALENDAR_TYPE_FEDERATED) {
1482
-					// TODO: implement custom event for federated calendars
1483
-				}
1484
-			}
1485
-
1486
-			return '"' . $extraData['etag'] . '"';
1487
-		}, $this->db);
1488
-	}
1489
-
1490
-	/**
1491
-	 * Moves a calendar object from calendar to calendar.
1492
-	 *
1493
-	 * @param string $sourcePrincipalUri
1494
-	 * @param int $sourceObjectId
1495
-	 * @param string $targetPrincipalUri
1496
-	 * @param int $targetCalendarId
1497
-	 * @param string $tragetObjectUri
1498
-	 * @param int $calendarType
1499
-	 * @return bool
1500
-	 * @throws Exception
1501
-	 */
1502
-	public function moveCalendarObject(string $sourcePrincipalUri, int $sourceObjectId, string $targetPrincipalUri, int $targetCalendarId, string $tragetObjectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR): bool {
1503
-		$this->cachedObjects = [];
1504
-		return $this->atomic(function () use ($sourcePrincipalUri, $sourceObjectId, $targetPrincipalUri, $targetCalendarId, $tragetObjectUri, $calendarType) {
1505
-			$object = $this->getCalendarObjectById($sourcePrincipalUri, $sourceObjectId);
1506
-			if (empty($object)) {
1507
-				return false;
1508
-			}
1509
-
1510
-			$sourceCalendarId = $object['calendarid'];
1511
-			$sourceObjectUri = $object['uri'];
1512
-
1513
-			$query = $this->db->getQueryBuilder();
1514
-			$query->update('calendarobjects')
1515
-				->set('calendarid', $query->createNamedParameter($targetCalendarId, IQueryBuilder::PARAM_INT))
1516
-				->set('uri', $query->createNamedParameter($tragetObjectUri, IQueryBuilder::PARAM_STR))
1517
-				->where($query->expr()->eq('id', $query->createNamedParameter($sourceObjectId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
1518
-				->executeStatement();
1519
-
1520
-			$this->purgeProperties($sourceCalendarId, $sourceObjectId);
1521
-			$this->updateProperties($targetCalendarId, $tragetObjectUri, $object['calendardata'], $calendarType);
1522
-
1523
-			$this->addChanges($sourceCalendarId, [$sourceObjectUri], 3, $calendarType);
1524
-			$this->addChanges($targetCalendarId, [$tragetObjectUri], 1, $calendarType);
1525
-
1526
-			$object = $this->getCalendarObjectById($targetPrincipalUri, $sourceObjectId);
1527
-			// Calendar Object wasn't found - possibly because it was deleted in the meantime by a different client
1528
-			if (empty($object)) {
1529
-				return false;
1530
-			}
1531
-
1532
-			$targetCalendarRow = $this->getCalendarById($targetCalendarId);
1533
-			// the calendar this event is being moved to does not exist any longer
1534
-			if (empty($targetCalendarRow)) {
1535
-				return false;
1536
-			}
1537
-
1538
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1539
-				$sourceShares = $this->getShares($sourceCalendarId);
1540
-				$targetShares = $this->getShares($targetCalendarId);
1541
-				$sourceCalendarRow = $this->getCalendarById($sourceCalendarId);
1542
-				$this->dispatcher->dispatchTyped(new CalendarObjectMovedEvent($sourceCalendarId, $sourceCalendarRow, $targetCalendarId, $targetCalendarRow, $sourceShares, $targetShares, $object));
1543
-			}
1544
-			return true;
1545
-		}, $this->db);
1546
-	}
1547
-
1548
-	/**
1549
-	 * Deletes an existing calendar object.
1550
-	 *
1551
-	 * The object uri is only the basename, or filename and not a full path.
1552
-	 *
1553
-	 * @param mixed $calendarId
1554
-	 * @param string $objectUri
1555
-	 * @param int $calendarType
1556
-	 * @param bool $forceDeletePermanently
1557
-	 * @return void
1558
-	 */
1559
-	public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
1560
-		$this->cachedObjects = [];
1561
-		$this->atomic(function () use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently): void {
1562
-			$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1563
-
1564
-			if ($data === null) {
1565
-				// Nothing to delete
1566
-				return;
1567
-			}
1568
-
1569
-			if ($forceDeletePermanently || $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0') {
1570
-				$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1571
-				$stmt->execute([$calendarId, $objectUri, $calendarType]);
1572
-
1573
-				$this->purgeProperties($calendarId, $data['id']);
1574
-
1575
-				$this->purgeObjectInvitations($data['uid']);
1576
-
1577
-				if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1578
-					$calendarRow = $this->getCalendarById($calendarId);
1579
-					$shares = $this->getShares($calendarId);
1580
-
1581
-					$this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent($calendarId, $calendarRow, $shares, $data));
1582
-				} else {
1583
-					$subscriptionRow = $this->getSubscriptionById($calendarId);
1584
-
1585
-					$this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent($calendarId, $subscriptionRow, [], $data));
1586
-				}
1587
-			} else {
1588
-				$pathInfo = pathinfo($data['uri']);
1589
-				if (!empty($pathInfo['extension'])) {
1590
-					// Append a suffix to "free" the old URI for recreation
1591
-					$newUri = sprintf(
1592
-						'%s-deleted.%s',
1593
-						$pathInfo['filename'],
1594
-						$pathInfo['extension']
1595
-					);
1596
-				} else {
1597
-					$newUri = sprintf(
1598
-						'%s-deleted',
1599
-						$pathInfo['filename']
1600
-					);
1601
-				}
1602
-
1603
-				// Try to detect conflicts before the DB does
1604
-				// As unlikely as it seems, this can happen when the user imports, then deletes, imports and deletes again
1605
-				$newObject = $this->getCalendarObject($calendarId, $newUri, $calendarType);
1606
-				if ($newObject !== null) {
1607
-					throw new Forbidden("A calendar object with URI $newUri already exists in calendar $calendarId, therefore this object can't be moved into the trashbin");
1608
-				}
1609
-
1610
-				$qb = $this->db->getQueryBuilder();
1611
-				$markObjectDeletedQuery = $qb->update('calendarobjects')
1612
-					->set('deleted_at', $qb->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
1613
-					->set('uri', $qb->createNamedParameter($newUri))
1614
-					->where(
1615
-						$qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
1616
-						$qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
1617
-						$qb->expr()->eq('uri', $qb->createNamedParameter($objectUri))
1618
-					);
1619
-				$markObjectDeletedQuery->executeStatement();
1620
-
1621
-				$calendarData = $this->getCalendarById($calendarId);
1622
-				if ($calendarData !== null) {
1623
-					$this->dispatcher->dispatchTyped(
1624
-						new CalendarObjectMovedToTrashEvent(
1625
-							$calendarId,
1626
-							$calendarData,
1627
-							$this->getShares($calendarId),
1628
-							$data
1629
-						)
1630
-					);
1631
-				}
1632
-			}
1633
-
1634
-			$this->addChanges($calendarId, [$objectUri], 3, $calendarType);
1635
-		}, $this->db);
1636
-	}
1637
-
1638
-	/**
1639
-	 * @param mixed $objectData
1640
-	 *
1641
-	 * @throws Forbidden
1642
-	 */
1643
-	public function restoreCalendarObject(array $objectData): void {
1644
-		$this->cachedObjects = [];
1645
-		$this->atomic(function () use ($objectData): void {
1646
-			$id = (int)$objectData['id'];
1647
-			$restoreUri = str_replace('-deleted.ics', '.ics', $objectData['uri']);
1648
-			$targetObject = $this->getCalendarObject(
1649
-				$objectData['calendarid'],
1650
-				$restoreUri
1651
-			);
1652
-			if ($targetObject !== null) {
1653
-				throw new Forbidden("Can not restore calendar $id because a calendar object with the URI $restoreUri already exists");
1654
-			}
1655
-
1656
-			$qb = $this->db->getQueryBuilder();
1657
-			$update = $qb->update('calendarobjects')
1658
-				->set('uri', $qb->createNamedParameter($restoreUri))
1659
-				->set('deleted_at', $qb->createNamedParameter(null))
1660
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1661
-			$update->executeStatement();
1662
-
1663
-			// Make sure this change is tracked in the changes table
1664
-			$qb2 = $this->db->getQueryBuilder();
1665
-			$selectObject = $qb2->select('calendardata', 'uri', 'calendarid', 'calendartype')
1666
-				->selectAlias('componenttype', 'component')
1667
-				->from('calendarobjects')
1668
-				->where($qb2->expr()->eq('id', $qb2->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1669
-			$result = $selectObject->executeQuery();
1670
-			$row = $result->fetch();
1671
-			$result->closeCursor();
1672
-			if ($row === false) {
1673
-				// Welp, this should possibly not have happened, but let's ignore
1674
-				return;
1675
-			}
1676
-			$this->addChanges($row['calendarid'], [$row['uri']], 1, (int)$row['calendartype']);
1677
-
1678
-			$calendarRow = $this->getCalendarById((int)$row['calendarid']);
1679
-			if ($calendarRow === null) {
1680
-				throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
1681
-			}
1682
-			$this->dispatcher->dispatchTyped(
1683
-				new CalendarObjectRestoredEvent(
1684
-					(int)$objectData['calendarid'],
1685
-					$calendarRow,
1686
-					$this->getShares((int)$row['calendarid']),
1687
-					$row
1688
-				)
1689
-			);
1690
-		}, $this->db);
1691
-	}
1692
-
1693
-	/**
1694
-	 * Performs a calendar-query on the contents of this calendar.
1695
-	 *
1696
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1697
-	 * calendar-query it is possible for a client to request a specific set of
1698
-	 * object, based on contents of iCalendar properties, date-ranges and
1699
-	 * iCalendar component types (VTODO, VEVENT).
1700
-	 *
1701
-	 * This method should just return a list of (relative) urls that match this
1702
-	 * query.
1703
-	 *
1704
-	 * The list of filters are specified as an array. The exact array is
1705
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1706
-	 *
1707
-	 * Note that it is extremely likely that getCalendarObject for every path
1708
-	 * returned from this method will be called almost immediately after. You
1709
-	 * may want to anticipate this to speed up these requests.
1710
-	 *
1711
-	 * This method provides a default implementation, which parses *all* the
1712
-	 * iCalendar objects in the specified calendar.
1713
-	 *
1714
-	 * This default may well be good enough for personal use, and calendars
1715
-	 * that aren't very large. But if you anticipate high usage, big calendars
1716
-	 * or high loads, you are strongly advised to optimize certain paths.
1717
-	 *
1718
-	 * The best way to do so is override this method and to optimize
1719
-	 * specifically for 'common filters'.
1720
-	 *
1721
-	 * Requests that are extremely common are:
1722
-	 *   * requests for just VEVENTS
1723
-	 *   * requests for just VTODO
1724
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1725
-	 *
1726
-	 * ..and combinations of these requests. It may not be worth it to try to
1727
-	 * handle every possible situation and just rely on the (relatively
1728
-	 * easy to use) CalendarQueryValidator to handle the rest.
1729
-	 *
1730
-	 * Note that especially time-range-filters may be difficult to parse. A
1731
-	 * time-range filter specified on a VEVENT must for instance also handle
1732
-	 * recurrence rules correctly.
1733
-	 * A good example of how to interpret all these filters can also simply
1734
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1735
-	 * as possible, so it gives you a good idea on what type of stuff you need
1736
-	 * to think of.
1737
-	 *
1738
-	 * @param mixed $calendarId
1739
-	 * @param array $filters
1740
-	 * @param int $calendarType
1741
-	 * @return array
1742
-	 */
1743
-	public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1744
-		$componentType = null;
1745
-		$requirePostFilter = true;
1746
-		$timeRange = null;
1747
-
1748
-		// if no filters were specified, we don't need to filter after a query
1749
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1750
-			$requirePostFilter = false;
1751
-		}
1752
-
1753
-		// Figuring out if there's a component filter
1754
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1755
-			$componentType = $filters['comp-filters'][0]['name'];
1756
-
1757
-			// Checking if we need post-filters
1758
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1759
-				$requirePostFilter = false;
1760
-			}
1761
-			// There was a time-range filter
1762
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
1763
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1764
-
1765
-				// If start time OR the end time is not specified, we can do a
1766
-				// 100% accurate mysql query.
1767
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1768
-					$requirePostFilter = false;
1769
-				}
1770
-			}
1771
-		}
1772
-		$query = $this->db->getQueryBuilder();
1773
-		$query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1774
-			->from('calendarobjects')
1775
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1776
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1777
-			->andWhere($query->expr()->isNull('deleted_at'));
1778
-
1779
-		if ($componentType) {
1780
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1781
-		}
1782
-
1783
-		if ($timeRange && $timeRange['start']) {
1784
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1785
-		}
1786
-		if ($timeRange && $timeRange['end']) {
1787
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1788
-		}
1789
-
1790
-		$stmt = $query->executeQuery();
1791
-
1792
-		$result = [];
1793
-		while ($row = $stmt->fetch()) {
1794
-			// if we leave it as a blob we can't read it both from the post filter and the rowToCalendarObject
1795
-			if (isset($row['calendardata'])) {
1796
-				$row['calendardata'] = $this->readBlob($row['calendardata']);
1797
-			}
1798
-
1799
-			if ($requirePostFilter) {
1800
-				// validateFilterForObject will parse the calendar data
1801
-				// catch parsing errors
1802
-				try {
1803
-					$matches = $this->validateFilterForObject($row, $filters);
1804
-				} catch (ParseException $ex) {
1805
-					$this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1806
-						'app' => 'dav',
1807
-						'exception' => $ex,
1808
-					]);
1809
-					continue;
1810
-				} catch (InvalidDataException $ex) {
1811
-					$this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1812
-						'app' => 'dav',
1813
-						'exception' => $ex,
1814
-					]);
1815
-					continue;
1816
-				} catch (MaxInstancesExceededException $ex) {
1817
-					$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'], [
1818
-						'app' => 'dav',
1819
-						'exception' => $ex,
1820
-					]);
1821
-					continue;
1822
-				}
1823
-
1824
-				if (!$matches) {
1825
-					continue;
1826
-				}
1827
-			}
1828
-			$result[] = $row['uri'];
1829
-			$key = $calendarId . '::' . $row['uri'] . '::' . $calendarType;
1830
-			$this->cachedObjects[$key] = $this->rowToCalendarObject($row);
1831
-		}
1832
-
1833
-		return $result;
1834
-	}
1835
-
1836
-	/**
1837
-	 * custom Nextcloud search extension for CalDAV
1838
-	 *
1839
-	 * TODO - this should optionally cover cached calendar objects as well
1840
-	 *
1841
-	 * @param string $principalUri
1842
-	 * @param array $filters
1843
-	 * @param integer|null $limit
1844
-	 * @param integer|null $offset
1845
-	 * @return array
1846
-	 */
1847
-	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1848
-		return $this->atomic(function () use ($principalUri, $filters, $limit, $offset) {
1849
-			$calendars = $this->getCalendarsForUser($principalUri);
1850
-			$ownCalendars = [];
1851
-			$sharedCalendars = [];
1852
-
1853
-			$uriMapper = [];
1854
-
1855
-			foreach ($calendars as $calendar) {
1856
-				if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1857
-					$ownCalendars[] = $calendar['id'];
1858
-				} else {
1859
-					$sharedCalendars[] = $calendar['id'];
1860
-				}
1861
-				$uriMapper[$calendar['id']] = $calendar['uri'];
1862
-			}
1863
-			if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1864
-				return [];
1865
-			}
1866
-
1867
-			$query = $this->db->getQueryBuilder();
1868
-			// Calendar id expressions
1869
-			$calendarExpressions = [];
1870
-			foreach ($ownCalendars as $id) {
1871
-				$calendarExpressions[] = $query->expr()->andX(
1872
-					$query->expr()->eq('c.calendarid',
1873
-						$query->createNamedParameter($id)),
1874
-					$query->expr()->eq('c.calendartype',
1875
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1876
-			}
1877
-			foreach ($sharedCalendars as $id) {
1878
-				$calendarExpressions[] = $query->expr()->andX(
1879
-					$query->expr()->eq('c.calendarid',
1880
-						$query->createNamedParameter($id)),
1881
-					$query->expr()->eq('c.classification',
1882
-						$query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1883
-					$query->expr()->eq('c.calendartype',
1884
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1885
-			}
1886
-
1887
-			if (count($calendarExpressions) === 1) {
1888
-				$calExpr = $calendarExpressions[0];
1889
-			} else {
1890
-				$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1891
-			}
1892
-
1893
-			// Component expressions
1894
-			$compExpressions = [];
1895
-			foreach ($filters['comps'] as $comp) {
1896
-				$compExpressions[] = $query->expr()
1897
-					->eq('c.componenttype', $query->createNamedParameter($comp));
1898
-			}
1899
-
1900
-			if (count($compExpressions) === 1) {
1901
-				$compExpr = $compExpressions[0];
1902
-			} else {
1903
-				$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1904
-			}
1905
-
1906
-			if (!isset($filters['props'])) {
1907
-				$filters['props'] = [];
1908
-			}
1909
-			if (!isset($filters['params'])) {
1910
-				$filters['params'] = [];
1911
-			}
1912
-
1913
-			$propParamExpressions = [];
1914
-			foreach ($filters['props'] as $prop) {
1915
-				$propParamExpressions[] = $query->expr()->andX(
1916
-					$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1917
-					$query->expr()->isNull('i.parameter')
1918
-				);
1919
-			}
1920
-			foreach ($filters['params'] as $param) {
1921
-				$propParamExpressions[] = $query->expr()->andX(
1922
-					$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1923
-					$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1924
-				);
1925
-			}
1926
-
1927
-			if (count($propParamExpressions) === 1) {
1928
-				$propParamExpr = $propParamExpressions[0];
1929
-			} else {
1930
-				$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1931
-			}
1932
-
1933
-			$query->select(['c.calendarid', 'c.uri'])
1934
-				->from($this->dbObjectPropertiesTable, 'i')
1935
-				->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1936
-				->where($calExpr)
1937
-				->andWhere($compExpr)
1938
-				->andWhere($propParamExpr)
1939
-				->andWhere($query->expr()->iLike('i.value',
1940
-					$query->createNamedParameter('%' . $this->db->escapeLikeParameter($filters['search-term']) . '%')))
1941
-				->andWhere($query->expr()->isNull('deleted_at'));
1942
-
1943
-			if ($offset) {
1944
-				$query->setFirstResult($offset);
1945
-			}
1946
-			if ($limit) {
1947
-				$query->setMaxResults($limit);
1948
-			}
1949
-
1950
-			$stmt = $query->executeQuery();
1951
-
1952
-			$result = [];
1953
-			while ($row = $stmt->fetch()) {
1954
-				$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1955
-				if (!in_array($path, $result)) {
1956
-					$result[] = $path;
1957
-				}
1958
-			}
1959
-
1960
-			return $result;
1961
-		}, $this->db);
1962
-	}
1963
-
1964
-	/**
1965
-	 * used for Nextcloud's calendar API
1966
-	 *
1967
-	 * @param array $calendarInfo
1968
-	 * @param string $pattern
1969
-	 * @param array $searchProperties
1970
-	 * @param array $options
1971
-	 * @param integer|null $limit
1972
-	 * @param integer|null $offset
1973
-	 *
1974
-	 * @return array
1975
-	 */
1976
-	public function search(
1977
-		array $calendarInfo,
1978
-		$pattern,
1979
-		array $searchProperties,
1980
-		array $options,
1981
-		$limit,
1982
-		$offset,
1983
-	) {
1984
-		$outerQuery = $this->db->getQueryBuilder();
1985
-		$innerQuery = $this->db->getQueryBuilder();
1986
-
1987
-		if (isset($calendarInfo['source'])) {
1988
-			$calendarType = self::CALENDAR_TYPE_SUBSCRIPTION;
1989
-		} elseif (isset($calendarInfo['federated'])) {
1990
-			$calendarType = self::CALENDAR_TYPE_FEDERATED;
1991
-		} else {
1992
-			$calendarType = self::CALENDAR_TYPE_CALENDAR;
1993
-		}
1994
-
1995
-		$innerQuery->selectDistinct('op.objectid')
1996
-			->from($this->dbObjectPropertiesTable, 'op')
1997
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
1998
-				$outerQuery->createNamedParameter($calendarInfo['id'])))
1999
-			->andWhere($innerQuery->expr()->eq('op.calendartype',
2000
-				$outerQuery->createNamedParameter($calendarType)));
2001
-
2002
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
2003
-			->from('calendarobjects', 'c')
2004
-			->where($outerQuery->expr()->isNull('deleted_at'));
2005
-
2006
-		// only return public items for shared calendars for now
2007
-		if (isset($calendarInfo['{http://owncloud.org/ns}owner-principal']) === false || $calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
2008
-			$outerQuery->andWhere($outerQuery->expr()->eq('c.classification',
2009
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2010
-		}
2011
-
2012
-		if (!empty($searchProperties)) {
2013
-			$or = [];
2014
-			foreach ($searchProperties as $searchProperty) {
2015
-				$or[] = $innerQuery->expr()->eq('op.name',
2016
-					$outerQuery->createNamedParameter($searchProperty));
2017
-			}
2018
-			$innerQuery->andWhere($innerQuery->expr()->orX(...$or));
2019
-		}
2020
-
2021
-		if ($pattern !== '') {
2022
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
2023
-				$outerQuery->createNamedParameter('%'
2024
-					. $this->db->escapeLikeParameter($pattern) . '%')));
2025
-		}
2026
-
2027
-		$start = null;
2028
-		$end = null;
2029
-
2030
-		$hasLimit = is_int($limit);
2031
-		$hasTimeRange = false;
2032
-
2033
-		if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2034
-			/** @var DateTimeInterface $start */
2035
-			$start = $options['timerange']['start'];
2036
-			$outerQuery->andWhere(
2037
-				$outerQuery->expr()->gt(
2038
-					'lastoccurence',
2039
-					$outerQuery->createNamedParameter($start->getTimestamp())
2040
-				)
2041
-			);
2042
-			$hasTimeRange = true;
2043
-		}
2044
-
2045
-		if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2046
-			/** @var DateTimeInterface $end */
2047
-			$end = $options['timerange']['end'];
2048
-			$outerQuery->andWhere(
2049
-				$outerQuery->expr()->lt(
2050
-					'firstoccurence',
2051
-					$outerQuery->createNamedParameter($end->getTimestamp())
2052
-				)
2053
-			);
2054
-			$hasTimeRange = true;
2055
-		}
2056
-
2057
-		if (isset($options['uid'])) {
2058
-			$outerQuery->andWhere($outerQuery->expr()->eq('uid', $outerQuery->createNamedParameter($options['uid'])));
2059
-		}
2060
-
2061
-		if (!empty($options['types'])) {
2062
-			$or = [];
2063
-			foreach ($options['types'] as $type) {
2064
-				$or[] = $outerQuery->expr()->eq('componenttype',
2065
-					$outerQuery->createNamedParameter($type));
2066
-			}
2067
-			$outerQuery->andWhere($outerQuery->expr()->orX(...$or));
2068
-		}
2069
-
2070
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id', $outerQuery->createFunction($innerQuery->getSQL())));
2071
-
2072
-		// Without explicit order by its undefined in which order the SQL server returns the events.
2073
-		// For the pagination with hasLimit and hasTimeRange, a stable ordering is helpful.
2074
-		$outerQuery->addOrderBy('id');
2075
-
2076
-		$offset = (int)$offset;
2077
-		$outerQuery->setFirstResult($offset);
2078
-
2079
-		$calendarObjects = [];
2080
-
2081
-		if ($hasLimit && $hasTimeRange) {
2082
-			/**
2083
-			 * Event recurrences are evaluated at runtime because the database only knows the first and last occurrence.
2084
-			 *
2085
-			 * Given, a user created 8 events with a yearly reoccurrence and two for events tomorrow.
2086
-			 * The upcoming event widget asks the CalDAV backend for 7 events within the next 14 days.
2087
-			 *
2088
-			 * If limit 7 is applied to the SQL query, we find the 7 events with a yearly reoccurrence
2089
-			 * and discard the events after evaluating the reoccurrence rules because they are not due within
2090
-			 * the next 14 days and end up with an empty result even if there are two events to show.
2091
-			 *
2092
-			 * The workaround for search requests with a limit and time range is asking for more row than requested
2093
-			 * and retrying if we have not reached the limit.
2094
-			 *
2095
-			 * 25 rows and 3 retries is entirely arbitrary.
2096
-			 */
2097
-			$maxResults = (int)max($limit, 25);
2098
-			$outerQuery->setMaxResults($maxResults);
2099
-
2100
-			for ($attempt = $objectsCount = 0; $attempt < 3 && $objectsCount < $limit; $attempt++) {
2101
-				$objectsCount = array_push($calendarObjects, ...$this->searchCalendarObjects($outerQuery, $start, $end));
2102
-				$outerQuery->setFirstResult($offset += $maxResults);
2103
-			}
2104
-
2105
-			$calendarObjects = array_slice($calendarObjects, 0, $limit, false);
2106
-		} else {
2107
-			$outerQuery->setMaxResults($limit);
2108
-			$calendarObjects = $this->searchCalendarObjects($outerQuery, $start, $end);
2109
-		}
2110
-
2111
-		$calendarObjects = array_map(function ($o) use ($options) {
2112
-			$calendarData = Reader::read($o['calendardata']);
2113
-
2114
-			// Expand recurrences if an explicit time range is requested
2115
-			if ($calendarData instanceof VCalendar
2116
-				&& isset($options['timerange']['start'], $options['timerange']['end'])) {
2117
-				$calendarData = $calendarData->expand(
2118
-					$options['timerange']['start'],
2119
-					$options['timerange']['end'],
2120
-				);
2121
-			}
2122
-
2123
-			$comps = $calendarData->getComponents();
2124
-			$objects = [];
2125
-			$timezones = [];
2126
-			foreach ($comps as $comp) {
2127
-				if ($comp instanceof VTimeZone) {
2128
-					$timezones[] = $comp;
2129
-				} else {
2130
-					$objects[] = $comp;
2131
-				}
2132
-			}
2133
-
2134
-			return [
2135
-				'id' => $o['id'],
2136
-				'type' => $o['componenttype'],
2137
-				'uid' => $o['uid'],
2138
-				'uri' => $o['uri'],
2139
-				'objects' => array_map(function ($c) {
2140
-					return $this->transformSearchData($c);
2141
-				}, $objects),
2142
-				'timezones' => array_map(function ($c) {
2143
-					return $this->transformSearchData($c);
2144
-				}, $timezones),
2145
-			];
2146
-		}, $calendarObjects);
2147
-
2148
-		usort($calendarObjects, function (array $a, array $b) {
2149
-			/** @var DateTimeImmutable $startA */
2150
-			$startA = $a['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2151
-			/** @var DateTimeImmutable $startB */
2152
-			$startB = $b['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2153
-
2154
-			return $startA->getTimestamp() <=> $startB->getTimestamp();
2155
-		});
2156
-
2157
-		return $calendarObjects;
2158
-	}
2159
-
2160
-	private function searchCalendarObjects(IQueryBuilder $query, ?DateTimeInterface $start, ?DateTimeInterface $end): array {
2161
-		$calendarObjects = [];
2162
-		$filterByTimeRange = ($start instanceof DateTimeInterface) || ($end instanceof DateTimeInterface);
2163
-
2164
-		$result = $query->executeQuery();
2165
-
2166
-		while (($row = $result->fetch()) !== false) {
2167
-			if ($filterByTimeRange === false) {
2168
-				// No filter required
2169
-				$calendarObjects[] = $row;
2170
-				continue;
2171
-			}
2172
-
2173
-			try {
2174
-				$isValid = $this->validateFilterForObject($row, [
2175
-					'name' => 'VCALENDAR',
2176
-					'comp-filters' => [
2177
-						[
2178
-							'name' => 'VEVENT',
2179
-							'comp-filters' => [],
2180
-							'prop-filters' => [],
2181
-							'is-not-defined' => false,
2182
-							'time-range' => [
2183
-								'start' => $start,
2184
-								'end' => $end,
2185
-							],
2186
-						],
2187
-					],
2188
-					'prop-filters' => [],
2189
-					'is-not-defined' => false,
2190
-					'time-range' => null,
2191
-				]);
2192
-			} catch (MaxInstancesExceededException $ex) {
2193
-				$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'], [
2194
-					'app' => 'dav',
2195
-					'exception' => $ex,
2196
-				]);
2197
-				continue;
2198
-			}
2199
-
2200
-			if (is_resource($row['calendardata'])) {
2201
-				// Put the stream back to the beginning so it can be read another time
2202
-				rewind($row['calendardata']);
2203
-			}
2204
-
2205
-			if ($isValid) {
2206
-				$calendarObjects[] = $row;
2207
-			}
2208
-		}
2209
-
2210
-		$result->closeCursor();
2211
-
2212
-		return $calendarObjects;
2213
-	}
2214
-
2215
-	/**
2216
-	 * @param Component $comp
2217
-	 * @return array
2218
-	 */
2219
-	private function transformSearchData(Component $comp) {
2220
-		$data = [];
2221
-		/** @var Component[] $subComponents */
2222
-		$subComponents = $comp->getComponents();
2223
-		/** @var Property[] $properties */
2224
-		$properties = array_filter($comp->children(), function ($c) {
2225
-			return $c instanceof Property;
2226
-		});
2227
-		$validationRules = $comp->getValidationRules();
2228
-
2229
-		foreach ($subComponents as $subComponent) {
2230
-			$name = $subComponent->name;
2231
-			if (!isset($data[$name])) {
2232
-				$data[$name] = [];
2233
-			}
2234
-			$data[$name][] = $this->transformSearchData($subComponent);
2235
-		}
2236
-
2237
-		foreach ($properties as $property) {
2238
-			$name = $property->name;
2239
-			if (!isset($validationRules[$name])) {
2240
-				$validationRules[$name] = '*';
2241
-			}
2242
-
2243
-			$rule = $validationRules[$property->name];
2244
-			if ($rule === '+' || $rule === '*') { // multiple
2245
-				if (!isset($data[$name])) {
2246
-					$data[$name] = [];
2247
-				}
2248
-
2249
-				$data[$name][] = $this->transformSearchProperty($property);
2250
-			} else { // once
2251
-				$data[$name] = $this->transformSearchProperty($property);
2252
-			}
2253
-		}
2254
-
2255
-		return $data;
2256
-	}
2257
-
2258
-	/**
2259
-	 * @param Property $prop
2260
-	 * @return array
2261
-	 */
2262
-	private function transformSearchProperty(Property $prop) {
2263
-		// No need to check Date, as it extends DateTime
2264
-		if ($prop instanceof Property\ICalendar\DateTime) {
2265
-			$value = $prop->getDateTime();
2266
-		} else {
2267
-			$value = $prop->getValue();
2268
-		}
2269
-
2270
-		return [
2271
-			$value,
2272
-			$prop->parameters()
2273
-		];
2274
-	}
2275
-
2276
-	/**
2277
-	 * @param string $principalUri
2278
-	 * @param string $pattern
2279
-	 * @param array $componentTypes
2280
-	 * @param array $searchProperties
2281
-	 * @param array $searchParameters
2282
-	 * @param array $options
2283
-	 * @return array
2284
-	 */
2285
-	public function searchPrincipalUri(string $principalUri,
2286
-		string $pattern,
2287
-		array $componentTypes,
2288
-		array $searchProperties,
2289
-		array $searchParameters,
2290
-		array $options = [],
2291
-	): array {
2292
-		return $this->atomic(function () use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
2293
-			$escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
2294
-
2295
-			$calendarObjectIdQuery = $this->db->getQueryBuilder();
2296
-			$calendarOr = [];
2297
-			$searchOr = [];
2298
-
2299
-			// Fetch calendars and subscription
2300
-			$calendars = $this->getCalendarsForUser($principalUri);
2301
-			$subscriptions = $this->getSubscriptionsForUser($principalUri);
2302
-			foreach ($calendars as $calendar) {
2303
-				$calendarAnd = $calendarObjectIdQuery->expr()->andX(
2304
-					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])),
2305
-					$calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)),
2306
-				);
2307
-
2308
-				// If it's shared, limit search to public events
2309
-				if (isset($calendar['{http://owncloud.org/ns}owner-principal'])
2310
-					&& $calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
2311
-					$calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2312
-				}
2313
-
2314
-				$calendarOr[] = $calendarAnd;
2315
-			}
2316
-			foreach ($subscriptions as $subscription) {
2317
-				$subscriptionAnd = $calendarObjectIdQuery->expr()->andX(
2318
-					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])),
2319
-					$calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)),
2320
-				);
2321
-
2322
-				// If it's shared, limit search to public events
2323
-				if (isset($subscription['{http://owncloud.org/ns}owner-principal'])
2324
-					&& $subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
2325
-					$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2326
-				}
2327
-
2328
-				$calendarOr[] = $subscriptionAnd;
2329
-			}
2330
-
2331
-			foreach ($searchProperties as $property) {
2332
-				$propertyAnd = $calendarObjectIdQuery->expr()->andX(
2333
-					$calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2334
-					$calendarObjectIdQuery->expr()->isNull('cob.parameter'),
2335
-				);
2336
-
2337
-				$searchOr[] = $propertyAnd;
2338
-			}
2339
-			foreach ($searchParameters as $property => $parameter) {
2340
-				$parameterAnd = $calendarObjectIdQuery->expr()->andX(
2341
-					$calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2342
-					$calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)),
2343
-				);
2344
-
2345
-				$searchOr[] = $parameterAnd;
2346
-			}
2347
-
2348
-			if (empty($calendarOr)) {
2349
-				return [];
2350
-			}
2351
-			if (empty($searchOr)) {
2352
-				return [];
2353
-			}
2354
-
2355
-			$calendarObjectIdQuery->selectDistinct('cob.objectid')
2356
-				->from($this->dbObjectPropertiesTable, 'cob')
2357
-				->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
2358
-				->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
2359
-				->andWhere($calendarObjectIdQuery->expr()->orX(...$calendarOr))
2360
-				->andWhere($calendarObjectIdQuery->expr()->orX(...$searchOr))
2361
-				->andWhere($calendarObjectIdQuery->expr()->isNull('deleted_at'));
2362
-
2363
-			if ($pattern !== '') {
2364
-				if (!$escapePattern) {
2365
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
2366
-				} else {
2367
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
2368
-				}
2369
-			}
2370
-
2371
-			if (isset($options['limit'])) {
2372
-				$calendarObjectIdQuery->setMaxResults($options['limit']);
2373
-			}
2374
-			if (isset($options['offset'])) {
2375
-				$calendarObjectIdQuery->setFirstResult($options['offset']);
2376
-			}
2377
-			if (isset($options['timerange'])) {
2378
-				if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2379
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->gt(
2380
-						'lastoccurence',
2381
-						$calendarObjectIdQuery->createNamedParameter($options['timerange']['start']->getTimeStamp()),
2382
-					));
2383
-				}
2384
-				if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2385
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->lt(
2386
-						'firstoccurence',
2387
-						$calendarObjectIdQuery->createNamedParameter($options['timerange']['end']->getTimeStamp()),
2388
-					));
2389
-				}
2390
-			}
2391
-
2392
-			$result = $calendarObjectIdQuery->executeQuery();
2393
-			$matches = [];
2394
-			while (($row = $result->fetch()) !== false) {
2395
-				$matches[] = (int)$row['objectid'];
2396
-			}
2397
-			$result->closeCursor();
2398
-
2399
-			$query = $this->db->getQueryBuilder();
2400
-			$query->select('calendardata', 'uri', 'calendarid', 'calendartype')
2401
-				->from('calendarobjects')
2402
-				->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
2403
-
2404
-			$result = $query->executeQuery();
2405
-			$calendarObjects = [];
2406
-			while (($array = $result->fetch()) !== false) {
2407
-				$array['calendarid'] = (int)$array['calendarid'];
2408
-				$array['calendartype'] = (int)$array['calendartype'];
2409
-				$array['calendardata'] = $this->readBlob($array['calendardata']);
2410
-
2411
-				$calendarObjects[] = $array;
2412
-			}
2413
-			$result->closeCursor();
2414
-			return $calendarObjects;
2415
-		}, $this->db);
2416
-	}
2417
-
2418
-	/**
2419
-	 * Searches through all of a users calendars and calendar objects to find
2420
-	 * an object with a specific UID.
2421
-	 *
2422
-	 * This method should return the path to this object, relative to the
2423
-	 * calendar home, so this path usually only contains two parts:
2424
-	 *
2425
-	 * calendarpath/objectpath.ics
2426
-	 *
2427
-	 * If the uid is not found, return null.
2428
-	 *
2429
-	 * This method should only consider * objects that the principal owns, so
2430
-	 * any calendars owned by other principals that also appear in this
2431
-	 * collection should be ignored.
2432
-	 *
2433
-	 * @param string $principalUri
2434
-	 * @param string $uid
2435
-	 * @return string|null
2436
-	 */
2437
-	public function getCalendarObjectByUID($principalUri, $uid, $calendarUri = null) {
2438
-		$query = $this->db->getQueryBuilder();
2439
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
2440
-			->from('calendarobjects', 'co')
2441
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
2442
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2443
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
2444
-			->andWhere($query->expr()->isNull('co.deleted_at'));
2445
-
2446
-		if ($calendarUri !== null) {
2447
-			$query->andWhere($query->expr()->eq('c.uri', $query->createNamedParameter($calendarUri)));
2448
-		}
2449
-
2450
-		$stmt = $query->executeQuery();
2451
-		$row = $stmt->fetch();
2452
-		$stmt->closeCursor();
2453
-		if ($row) {
2454
-			return $row['calendaruri'] . '/' . $row['objecturi'];
2455
-		}
2456
-
2457
-		return null;
2458
-	}
2459
-
2460
-	public function getCalendarObjectById(string $principalUri, int $id): ?array {
2461
-		$query = $this->db->getQueryBuilder();
2462
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.calendardata', 'co.componenttype', 'co.classification', 'co.deleted_at'])
2463
-			->selectAlias('c.uri', 'calendaruri')
2464
-			->from('calendarobjects', 'co')
2465
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
2466
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2467
-			->andWhere($query->expr()->eq('co.id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
2468
-		$stmt = $query->executeQuery();
2469
-		$row = $stmt->fetch();
2470
-		$stmt->closeCursor();
2471
-
2472
-		if (!$row) {
2473
-			return null;
2474
-		}
2475
-
2476
-		return [
2477
-			'id' => $row['id'],
2478
-			'uri' => $row['uri'],
2479
-			'lastmodified' => $row['lastmodified'],
2480
-			'etag' => '"' . $row['etag'] . '"',
2481
-			'calendarid' => $row['calendarid'],
2482
-			'calendaruri' => $row['calendaruri'],
2483
-			'size' => (int)$row['size'],
2484
-			'calendardata' => $this->readBlob($row['calendardata']),
2485
-			'component' => strtolower($row['componenttype']),
2486
-			'classification' => (int)$row['classification'],
2487
-			'deleted_at' => isset($row['deleted_at']) ? ((int)$row['deleted_at']) : null,
2488
-		];
2489
-	}
2490
-
2491
-	/**
2492
-	 * The getChanges method returns all the changes that have happened, since
2493
-	 * the specified syncToken in the specified calendar.
2494
-	 *
2495
-	 * This function should return an array, such as the following:
2496
-	 *
2497
-	 * [
2498
-	 *   'syncToken' => 'The current synctoken',
2499
-	 *   'added'   => [
2500
-	 *      'new.txt',
2501
-	 *   ],
2502
-	 *   'modified'   => [
2503
-	 *      'modified.txt',
2504
-	 *   ],
2505
-	 *   'deleted' => [
2506
-	 *      'foo.php.bak',
2507
-	 *      'old.txt'
2508
-	 *   ]
2509
-	 * );
2510
-	 *
2511
-	 * The returned syncToken property should reflect the *current* syncToken
2512
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
2513
-	 * property This is * needed here too, to ensure the operation is atomic.
2514
-	 *
2515
-	 * If the $syncToken argument is specified as null, this is an initial
2516
-	 * sync, and all members should be reported.
2517
-	 *
2518
-	 * The modified property is an array of nodenames that have changed since
2519
-	 * the last token.
2520
-	 *
2521
-	 * The deleted property is an array with nodenames, that have been deleted
2522
-	 * from collection.
2523
-	 *
2524
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
2525
-	 * 1, you only have to report changes that happened only directly in
2526
-	 * immediate descendants. If it's 2, it should also include changes from
2527
-	 * the nodes below the child collections. (grandchildren)
2528
-	 *
2529
-	 * The $limit argument allows a client to specify how many results should
2530
-	 * be returned at most. If the limit is not specified, it should be treated
2531
-	 * as infinite.
2532
-	 *
2533
-	 * If the limit (infinite or not) is higher than you're willing to return,
2534
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
2535
-	 *
2536
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
2537
-	 * return null.
2538
-	 *
2539
-	 * The limit is 'suggestive'. You are free to ignore it.
2540
-	 *
2541
-	 * @param string $calendarId
2542
-	 * @param string $syncToken
2543
-	 * @param int $syncLevel
2544
-	 * @param int|null $limit
2545
-	 * @param int $calendarType
2546
-	 * @return ?array
2547
-	 */
2548
-	public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2549
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2550
-
2551
-		return $this->atomic(function () use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
2552
-			// Current synctoken
2553
-			$qb = $this->db->getQueryBuilder();
2554
-			$qb->select('synctoken')
2555
-				->from($table)
2556
-				->where(
2557
-					$qb->expr()->eq('id', $qb->createNamedParameter($calendarId))
2558
-				);
2559
-			$stmt = $qb->executeQuery();
2560
-			$currentToken = $stmt->fetchOne();
2561
-			$initialSync = !is_numeric($syncToken);
2562
-
2563
-			if ($currentToken === false) {
2564
-				return null;
2565
-			}
2566
-
2567
-			// evaluate if this is a initial sync and construct appropriate command
2568
-			if ($initialSync) {
2569
-				$qb = $this->db->getQueryBuilder();
2570
-				$qb->select('uri')
2571
-					->from('calendarobjects')
2572
-					->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2573
-					->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2574
-					->andWhere($qb->expr()->isNull('deleted_at'));
2575
-			} else {
2576
-				$qb = $this->db->getQueryBuilder();
2577
-				$qb->select('uri', $qb->func()->max('operation'))
2578
-					->from('calendarchanges')
2579
-					->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2580
-					->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2581
-					->andWhere($qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)))
2582
-					->andWhere($qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)))
2583
-					->groupBy('uri');
2584
-			}
2585
-			// evaluate if limit exists
2586
-			if (is_numeric($limit)) {
2587
-				$qb->setMaxResults($limit);
2588
-			}
2589
-			// execute command
2590
-			$stmt = $qb->executeQuery();
2591
-			// build results
2592
-			$result = ['syncToken' => $currentToken, 'added' => [], 'modified' => [], 'deleted' => []];
2593
-			// retrieve results
2594
-			if ($initialSync) {
2595
-				$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
2596
-			} else {
2597
-				// \PDO::FETCH_NUM is needed due to the inconsistent field names
2598
-				// produced by doctrine for MAX() with different databases
2599
-				while ($entry = $stmt->fetch(\PDO::FETCH_NUM)) {
2600
-					// assign uri (column 0) to appropriate mutation based on operation (column 1)
2601
-					// forced (int) is needed as doctrine with OCI returns the operation field as string not integer
2602
-					match ((int)$entry[1]) {
2603
-						1 => $result['added'][] = $entry[0],
2604
-						2 => $result['modified'][] = $entry[0],
2605
-						3 => $result['deleted'][] = $entry[0],
2606
-						default => $this->logger->debug('Unknown calendar change operation detected')
2607
-					};
2608
-				}
2609
-			}
2610
-			$stmt->closeCursor();
2611
-
2612
-			return $result;
2613
-		}, $this->db);
2614
-	}
2615
-
2616
-	/**
2617
-	 * Returns a list of subscriptions for a principal.
2618
-	 *
2619
-	 * Every subscription is an array with the following keys:
2620
-	 *  * id, a unique id that will be used by other functions to modify the
2621
-	 *    subscription. This can be the same as the uri or a database key.
2622
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
2623
-	 *  * principaluri. The owner of the subscription. Almost always the same as
2624
-	 *    principalUri passed to this method.
2625
-	 *
2626
-	 * Furthermore, all the subscription info must be returned too:
2627
-	 *
2628
-	 * 1. {DAV:}displayname
2629
-	 * 2. {http://apple.com/ns/ical/}refreshrate
2630
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
2631
-	 *    should not be stripped).
2632
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
2633
-	 *    should not be stripped).
2634
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
2635
-	 *    attachments should not be stripped).
2636
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
2637
-	 *     Sabre\DAV\Property\Href).
2638
-	 * 7. {http://apple.com/ns/ical/}calendar-color
2639
-	 * 8. {http://apple.com/ns/ical/}calendar-order
2640
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
2641
-	 *    (should just be an instance of
2642
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
2643
-	 *    default components).
2644
-	 *
2645
-	 * @param string $principalUri
2646
-	 * @return array
2647
-	 */
2648
-	public function getSubscriptionsForUser($principalUri) {
2649
-		$fields = array_column($this->subscriptionPropertyMap, 0);
2650
-		$fields[] = 'id';
2651
-		$fields[] = 'uri';
2652
-		$fields[] = 'source';
2653
-		$fields[] = 'principaluri';
2654
-		$fields[] = 'lastmodified';
2655
-		$fields[] = 'synctoken';
2656
-
2657
-		$query = $this->db->getQueryBuilder();
2658
-		$query->select($fields)
2659
-			->from('calendarsubscriptions')
2660
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2661
-			->orderBy('calendarorder', 'asc');
2662
-		$stmt = $query->executeQuery();
2663
-
2664
-		$subscriptions = [];
2665
-		while ($row = $stmt->fetch()) {
2666
-			$subscription = [
2667
-				'id' => $row['id'],
2668
-				'uri' => $row['uri'],
2669
-				'principaluri' => $row['principaluri'],
2670
-				'source' => $row['source'],
2671
-				'lastmodified' => $row['lastmodified'],
2672
-
2673
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2674
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
2675
-			];
2676
-
2677
-			$subscriptions[] = $this->rowToSubscription($row, $subscription);
2678
-		}
2679
-
2680
-		return $subscriptions;
2681
-	}
2682
-
2683
-	/**
2684
-	 * Creates a new subscription for a principal.
2685
-	 *
2686
-	 * If the creation was a success, an id must be returned that can be used to reference
2687
-	 * this subscription in other methods, such as updateSubscription.
2688
-	 *
2689
-	 * @param string $principalUri
2690
-	 * @param string $uri
2691
-	 * @param array $properties
2692
-	 * @return mixed
2693
-	 */
2694
-	public function createSubscription($principalUri, $uri, array $properties) {
2695
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2696
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2697
-		}
2698
-
2699
-		$values = [
2700
-			'principaluri' => $principalUri,
2701
-			'uri' => $uri,
2702
-			'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2703
-			'lastmodified' => time(),
2704
-		];
2705
-
2706
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2707
-
2708
-		foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
2709
-			if (array_key_exists($xmlName, $properties)) {
2710
-				$values[$dbName] = $properties[$xmlName];
2711
-				if (in_array($dbName, $propertiesBoolean)) {
2712
-					$values[$dbName] = true;
2713
-				}
2714
-			}
2715
-		}
2716
-
2717
-		[$subscriptionId, $subscriptionRow] = $this->atomic(function () use ($values) {
2718
-			$valuesToInsert = [];
2719
-			$query = $this->db->getQueryBuilder();
2720
-			foreach (array_keys($values) as $name) {
2721
-				$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2722
-			}
2723
-			$query->insert('calendarsubscriptions')
2724
-				->values($valuesToInsert)
2725
-				->executeStatement();
2726
-
2727
-			$subscriptionId = $query->getLastInsertId();
2728
-
2729
-			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2730
-			return [$subscriptionId, $subscriptionRow];
2731
-		}, $this->db);
2732
-
2733
-		$this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow));
2734
-
2735
-		return $subscriptionId;
2736
-	}
2737
-
2738
-	/**
2739
-	 * Updates a subscription
2740
-	 *
2741
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2742
-	 * To do the actual updates, you must tell this object which properties
2743
-	 * you're going to process with the handle() method.
2744
-	 *
2745
-	 * Calling the handle method is like telling the PropPatch object "I
2746
-	 * promise I can handle updating this property".
2747
-	 *
2748
-	 * Read the PropPatch documentation for more info and examples.
2749
-	 *
2750
-	 * @param mixed $subscriptionId
2751
-	 * @param PropPatch $propPatch
2752
-	 * @return void
2753
-	 */
2754
-	public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2755
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
2756
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
2757
-
2758
-		$propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2759
-			$newValues = [];
2760
-
2761
-			foreach ($mutations as $propertyName => $propertyValue) {
2762
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
2763
-					$newValues['source'] = $propertyValue->getHref();
2764
-				} else {
2765
-					$fieldName = $this->subscriptionPropertyMap[$propertyName][0];
2766
-					$newValues[$fieldName] = $propertyValue;
2767
-				}
2768
-			}
2769
-
2770
-			$subscriptionRow = $this->atomic(function () use ($subscriptionId, $newValues) {
2771
-				$query = $this->db->getQueryBuilder();
2772
-				$query->update('calendarsubscriptions')
2773
-					->set('lastmodified', $query->createNamedParameter(time()));
2774
-				foreach ($newValues as $fieldName => $value) {
2775
-					$query->set($fieldName, $query->createNamedParameter($value));
2776
-				}
2777
-				$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2778
-					->executeStatement();
2779
-
2780
-				return $this->getSubscriptionById($subscriptionId);
2781
-			}, $this->db);
2782
-
2783
-			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2784
-
2785
-			return true;
2786
-		});
2787
-	}
2788
-
2789
-	/**
2790
-	 * Deletes a subscription.
2791
-	 *
2792
-	 * @param mixed $subscriptionId
2793
-	 * @return void
2794
-	 */
2795
-	public function deleteSubscription($subscriptionId) {
2796
-		$this->atomic(function () use ($subscriptionId): void {
2797
-			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2798
-
2799
-			$query = $this->db->getQueryBuilder();
2800
-			$query->delete('calendarsubscriptions')
2801
-				->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2802
-				->executeStatement();
2803
-
2804
-			$query = $this->db->getQueryBuilder();
2805
-			$query->delete('calendarobjects')
2806
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2807
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2808
-				->executeStatement();
2809
-
2810
-			$query->delete('calendarchanges')
2811
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2812
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2813
-				->executeStatement();
2814
-
2815
-			$query->delete($this->dbObjectPropertiesTable)
2816
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2817
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2818
-				->executeStatement();
2819
-
2820
-			if ($subscriptionRow) {
2821
-				$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2822
-			}
2823
-		}, $this->db);
2824
-	}
2825
-
2826
-	/**
2827
-	 * Returns a single scheduling object for the inbox collection.
2828
-	 *
2829
-	 * The returned array should contain the following elements:
2830
-	 *   * uri - A unique basename for the object. This will be used to
2831
-	 *           construct a full uri.
2832
-	 *   * calendardata - The iCalendar object
2833
-	 *   * lastmodified - The last modification date. Can be an int for a unix
2834
-	 *                    timestamp, or a PHP DateTime object.
2835
-	 *   * etag - A unique token that must change if the object changed.
2836
-	 *   * size - The size of the object, in bytes.
2837
-	 *
2838
-	 * @param string $principalUri
2839
-	 * @param string $objectUri
2840
-	 * @return array
2841
-	 */
2842
-	public function getSchedulingObject($principalUri, $objectUri) {
2843
-		$query = $this->db->getQueryBuilder();
2844
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2845
-			->from('schedulingobjects')
2846
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2847
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2848
-			->executeQuery();
2849
-
2850
-		$row = $stmt->fetch();
2851
-
2852
-		if (!$row) {
2853
-			return null;
2854
-		}
2855
-
2856
-		return [
2857
-			'uri' => $row['uri'],
2858
-			'calendardata' => $row['calendardata'],
2859
-			'lastmodified' => $row['lastmodified'],
2860
-			'etag' => '"' . $row['etag'] . '"',
2861
-			'size' => (int)$row['size'],
2862
-		];
2863
-	}
2864
-
2865
-	/**
2866
-	 * Returns all scheduling objects for the inbox collection.
2867
-	 *
2868
-	 * These objects should be returned as an array. Every item in the array
2869
-	 * should follow the same structure as returned from getSchedulingObject.
2870
-	 *
2871
-	 * The main difference is that 'calendardata' is optional.
2872
-	 *
2873
-	 * @param string $principalUri
2874
-	 * @return array
2875
-	 */
2876
-	public function getSchedulingObjects($principalUri) {
2877
-		$query = $this->db->getQueryBuilder();
2878
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2879
-			->from('schedulingobjects')
2880
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2881
-			->executeQuery();
2882
-
2883
-		$results = [];
2884
-		while (($row = $stmt->fetch()) !== false) {
2885
-			$results[] = [
2886
-				'calendardata' => $row['calendardata'],
2887
-				'uri' => $row['uri'],
2888
-				'lastmodified' => $row['lastmodified'],
2889
-				'etag' => '"' . $row['etag'] . '"',
2890
-				'size' => (int)$row['size'],
2891
-			];
2892
-		}
2893
-		$stmt->closeCursor();
2894
-
2895
-		return $results;
2896
-	}
2897
-
2898
-	/**
2899
-	 * Deletes a scheduling object from the inbox collection.
2900
-	 *
2901
-	 * @param string $principalUri
2902
-	 * @param string $objectUri
2903
-	 * @return void
2904
-	 */
2905
-	public function deleteSchedulingObject($principalUri, $objectUri) {
2906
-		$this->cachedObjects = [];
2907
-		$query = $this->db->getQueryBuilder();
2908
-		$query->delete('schedulingobjects')
2909
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2910
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2911
-			->executeStatement();
2912
-	}
2913
-
2914
-	/**
2915
-	 * Deletes all scheduling objects last modified before $modifiedBefore from the inbox collection.
2916
-	 *
2917
-	 * @param int $modifiedBefore
2918
-	 * @param int $limit
2919
-	 * @return void
2920
-	 */
2921
-	public function deleteOutdatedSchedulingObjects(int $modifiedBefore, int $limit): void {
2922
-		$query = $this->db->getQueryBuilder();
2923
-		$query->select('id')
2924
-			->from('schedulingobjects')
2925
-			->where($query->expr()->lt('lastmodified', $query->createNamedParameter($modifiedBefore)))
2926
-			->setMaxResults($limit);
2927
-		$result = $query->executeQuery();
2928
-		$count = $result->rowCount();
2929
-		if ($count === 0) {
2930
-			return;
2931
-		}
2932
-		$ids = array_map(static function (array $id) {
2933
-			return (int)$id[0];
2934
-		}, $result->fetchAll(\PDO::FETCH_NUM));
2935
-		$result->closeCursor();
2936
-
2937
-		$numDeleted = 0;
2938
-		$deleteQuery = $this->db->getQueryBuilder();
2939
-		$deleteQuery->delete('schedulingobjects')
2940
-			->where($deleteQuery->expr()->in('id', $deleteQuery->createParameter('ids'), IQueryBuilder::PARAM_INT_ARRAY));
2941
-		foreach (array_chunk($ids, 1000) as $chunk) {
2942
-			$deleteQuery->setParameter('ids', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
2943
-			$numDeleted += $deleteQuery->executeStatement();
2944
-		}
2945
-
2946
-		if ($numDeleted === $limit) {
2947
-			$this->logger->info("Deleted $limit scheduling objects, continuing with next batch");
2948
-			$this->deleteOutdatedSchedulingObjects($modifiedBefore, $limit);
2949
-		}
2950
-	}
2951
-
2952
-	/**
2953
-	 * Creates a new scheduling object. This should land in a users' inbox.
2954
-	 *
2955
-	 * @param string $principalUri
2956
-	 * @param string $objectUri
2957
-	 * @param string $objectData
2958
-	 * @return void
2959
-	 */
2960
-	public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2961
-		$this->cachedObjects = [];
2962
-		$query = $this->db->getQueryBuilder();
2963
-		$query->insert('schedulingobjects')
2964
-			->values([
2965
-				'principaluri' => $query->createNamedParameter($principalUri),
2966
-				'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2967
-				'uri' => $query->createNamedParameter($objectUri),
2968
-				'lastmodified' => $query->createNamedParameter(time()),
2969
-				'etag' => $query->createNamedParameter(md5($objectData)),
2970
-				'size' => $query->createNamedParameter(strlen($objectData))
2971
-			])
2972
-			->executeStatement();
2973
-	}
2974
-
2975
-	/**
2976
-	 * Adds a change record to the calendarchanges table.
2977
-	 *
2978
-	 * @param mixed $calendarId
2979
-	 * @param string[] $objectUris
2980
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2981
-	 * @param int $calendarType
2982
-	 * @return void
2983
-	 */
2984
-	protected function addChanges(int $calendarId, array $objectUris, int $operation, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
2985
-		$this->cachedObjects = [];
2986
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2987
-
2988
-		$this->atomic(function () use ($calendarId, $objectUris, $operation, $calendarType, $table): void {
2989
-			$query = $this->db->getQueryBuilder();
2990
-			$query->select('synctoken')
2991
-				->from($table)
2992
-				->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2993
-			$result = $query->executeQuery();
2994
-			$syncToken = (int)$result->fetchOne();
2995
-			$result->closeCursor();
2996
-
2997
-			$query = $this->db->getQueryBuilder();
2998
-			$query->insert('calendarchanges')
2999
-				->values([
3000
-					'uri' => $query->createParameter('uri'),
3001
-					'synctoken' => $query->createNamedParameter($syncToken),
3002
-					'calendarid' => $query->createNamedParameter($calendarId),
3003
-					'operation' => $query->createNamedParameter($operation),
3004
-					'calendartype' => $query->createNamedParameter($calendarType),
3005
-					'created_at' => $query->createNamedParameter(time()),
3006
-				]);
3007
-			foreach ($objectUris as $uri) {
3008
-				$query->setParameter('uri', $uri);
3009
-				$query->executeStatement();
3010
-			}
3011
-
3012
-			$query = $this->db->getQueryBuilder();
3013
-			$query->update($table)
3014
-				->set('synctoken', $query->createNamedParameter($syncToken + 1, IQueryBuilder::PARAM_INT))
3015
-				->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
3016
-				->executeStatement();
3017
-		}, $this->db);
3018
-	}
3019
-
3020
-	public function restoreChanges(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
3021
-		$this->cachedObjects = [];
3022
-
3023
-		$this->atomic(function () use ($calendarId, $calendarType): void {
3024
-			$qbAdded = $this->db->getQueryBuilder();
3025
-			$qbAdded->select('uri')
3026
-				->from('calendarobjects')
3027
-				->where(
3028
-					$qbAdded->expr()->andX(
3029
-						$qbAdded->expr()->eq('calendarid', $qbAdded->createNamedParameter($calendarId)),
3030
-						$qbAdded->expr()->eq('calendartype', $qbAdded->createNamedParameter($calendarType)),
3031
-						$qbAdded->expr()->isNull('deleted_at'),
3032
-					)
3033
-				);
3034
-			$resultAdded = $qbAdded->executeQuery();
3035
-			$addedUris = $resultAdded->fetchAll(\PDO::FETCH_COLUMN);
3036
-			$resultAdded->closeCursor();
3037
-			// Track everything as changed
3038
-			// Tracking the creation is not necessary because \OCA\DAV\CalDAV\CalDavBackend::getChangesForCalendar
3039
-			// only returns the last change per object.
3040
-			$this->addChanges($calendarId, $addedUris, 2, $calendarType);
3041
-
3042
-			$qbDeleted = $this->db->getQueryBuilder();
3043
-			$qbDeleted->select('uri')
3044
-				->from('calendarobjects')
3045
-				->where(
3046
-					$qbDeleted->expr()->andX(
3047
-						$qbDeleted->expr()->eq('calendarid', $qbDeleted->createNamedParameter($calendarId)),
3048
-						$qbDeleted->expr()->eq('calendartype', $qbDeleted->createNamedParameter($calendarType)),
3049
-						$qbDeleted->expr()->isNotNull('deleted_at'),
3050
-					)
3051
-				);
3052
-			$resultDeleted = $qbDeleted->executeQuery();
3053
-			$deletedUris = array_map(function (string $uri) {
3054
-				return str_replace('-deleted.ics', '.ics', $uri);
3055
-			}, $resultDeleted->fetchAll(\PDO::FETCH_COLUMN));
3056
-			$resultDeleted->closeCursor();
3057
-			$this->addChanges($calendarId, $deletedUris, 3, $calendarType);
3058
-		}, $this->db);
3059
-	}
3060
-
3061
-	/**
3062
-	 * Parses some information from calendar objects, used for optimized
3063
-	 * calendar-queries.
3064
-	 *
3065
-	 * Returns an array with the following keys:
3066
-	 *   * etag - An md5 checksum of the object without the quotes.
3067
-	 *   * size - Size of the object in bytes
3068
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
3069
-	 *   * firstOccurence
3070
-	 *   * lastOccurence
3071
-	 *   * uid - value of the UID property
3072
-	 *
3073
-	 * @param string $calendarData
3074
-	 * @return array
3075
-	 */
3076
-	public function getDenormalizedData(string $calendarData): array {
3077
-		$vObject = Reader::read($calendarData);
3078
-		$vEvents = [];
3079
-		$componentType = null;
3080
-		$component = null;
3081
-		$firstOccurrence = null;
3082
-		$lastOccurrence = null;
3083
-		$uid = null;
3084
-		$classification = self::CLASSIFICATION_PUBLIC;
3085
-		$hasDTSTART = false;
3086
-		foreach ($vObject->getComponents() as $component) {
3087
-			if ($component->name !== 'VTIMEZONE') {
3088
-				// Finding all VEVENTs, and track them
3089
-				if ($component->name === 'VEVENT') {
3090
-					$vEvents[] = $component;
3091
-					if ($component->DTSTART) {
3092
-						$hasDTSTART = true;
3093
-					}
3094
-				}
3095
-				// Track first component type and uid
3096
-				if ($uid === null) {
3097
-					$componentType = $component->name;
3098
-					$uid = (string)$component->UID;
3099
-				}
3100
-			}
3101
-		}
3102
-		if (!$componentType) {
3103
-			throw new BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
3104
-		}
3105
-
3106
-		if ($hasDTSTART) {
3107
-			$component = $vEvents[0];
3108
-
3109
-			// Finding the last occurrence is a bit harder
3110
-			if (!isset($component->RRULE) && count($vEvents) === 1) {
3111
-				$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
3112
-				if (isset($component->DTEND)) {
3113
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
3114
-				} elseif (isset($component->DURATION)) {
3115
-					$endDate = clone $component->DTSTART->getDateTime();
3116
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
3117
-					$lastOccurrence = $endDate->getTimeStamp();
3118
-				} elseif (!$component->DTSTART->hasTime()) {
3119
-					$endDate = clone $component->DTSTART->getDateTime();
3120
-					$endDate->modify('+1 day');
3121
-					$lastOccurrence = $endDate->getTimeStamp();
3122
-				} else {
3123
-					$lastOccurrence = $firstOccurrence;
3124
-				}
3125
-			} else {
3126
-				try {
3127
-					$it = new EventIterator($vEvents);
3128
-				} catch (NoInstancesException $e) {
3129
-					$this->logger->debug('Caught no instance exception for calendar data. This usually indicates invalid calendar data.', [
3130
-						'app' => 'dav',
3131
-						'exception' => $e,
3132
-					]);
3133
-					throw new Forbidden($e->getMessage());
3134
-				}
3135
-				$maxDate = new DateTime(self::MAX_DATE);
3136
-				$firstOccurrence = $it->getDtStart()->getTimestamp();
3137
-				if ($it->isInfinite()) {
3138
-					$lastOccurrence = $maxDate->getTimestamp();
3139
-				} else {
3140
-					$end = $it->getDtEnd();
3141
-					while ($it->valid() && $end < $maxDate) {
3142
-						$end = $it->getDtEnd();
3143
-						$it->next();
3144
-					}
3145
-					$lastOccurrence = $end->getTimestamp();
3146
-				}
3147
-			}
3148
-		}
3149
-
3150
-		if ($component->CLASS) {
3151
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
3152
-			switch ($component->CLASS->getValue()) {
3153
-				case 'PUBLIC':
3154
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
3155
-					break;
3156
-				case 'CONFIDENTIAL':
3157
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
3158
-					break;
3159
-			}
3160
-		}
3161
-		return [
3162
-			'etag' => md5($calendarData),
3163
-			'size' => strlen($calendarData),
3164
-			'componentType' => $componentType,
3165
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
3166
-			'lastOccurence' => is_null($lastOccurrence) ? null : max(0, $lastOccurrence),
3167
-			'uid' => $uid,
3168
-			'classification' => $classification
3169
-		];
3170
-	}
3171
-
3172
-	/**
3173
-	 * @param $cardData
3174
-	 * @return bool|string
3175
-	 */
3176
-	private function readBlob($cardData) {
3177
-		if (is_resource($cardData)) {
3178
-			return stream_get_contents($cardData);
3179
-		}
3180
-
3181
-		return $cardData;
3182
-	}
3183
-
3184
-	/**
3185
-	 * @param list<array{href: string, commonName: string, readOnly: bool}> $add
3186
-	 * @param list<string> $remove
3187
-	 */
3188
-	public function updateShares(IShareable $shareable, array $add, array $remove): void {
3189
-		$this->atomic(function () use ($shareable, $add, $remove): void {
3190
-			$calendarId = $shareable->getResourceId();
3191
-			$calendarRow = $this->getCalendarById($calendarId);
3192
-			if ($calendarRow === null) {
3193
-				throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $calendarId);
3194
-			}
3195
-			$oldShares = $this->getShares($calendarId);
3196
-
3197
-			$this->calendarSharingBackend->updateShares($shareable, $add, $remove, $oldShares);
3198
-
3199
-			$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent($calendarId, $calendarRow, $oldShares, $add, $remove));
3200
-		}, $this->db);
3201
-	}
3202
-
3203
-	/**
3204
-	 * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
3205
-	 */
3206
-	public function getShares(int $resourceId): array {
3207
-		return $this->calendarSharingBackend->getShares($resourceId);
3208
-	}
3209
-
3210
-	public function getSharesByShareePrincipal(string $principal): array {
3211
-		return $this->calendarSharingBackend->getSharesByShareePrincipal($principal);
3212
-	}
3213
-
3214
-	public function preloadShares(array $resourceIds): void {
3215
-		$this->calendarSharingBackend->preloadShares($resourceIds);
3216
-	}
3217
-
3218
-	/**
3219
-	 * @param boolean $value
3220
-	 * @param Calendar $calendar
3221
-	 * @return string|null
3222
-	 */
3223
-	public function setPublishStatus($value, $calendar) {
3224
-		return $this->atomic(function () use ($value, $calendar) {
3225
-			$calendarId = $calendar->getResourceId();
3226
-			$calendarData = $this->getCalendarById($calendarId);
3227
-
3228
-			$query = $this->db->getQueryBuilder();
3229
-			if ($value) {
3230
-				$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
3231
-				$query->insert('dav_shares')
3232
-					->values([
3233
-						'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
3234
-						'type' => $query->createNamedParameter('calendar'),
3235
-						'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
3236
-						'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
3237
-						'publicuri' => $query->createNamedParameter($publicUri)
3238
-					]);
3239
-				$query->executeStatement();
3240
-
3241
-				$this->dispatcher->dispatchTyped(new CalendarPublishedEvent($calendarId, $calendarData, $publicUri));
3242
-				return $publicUri;
3243
-			}
3244
-			$query->delete('dav_shares')
3245
-				->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3246
-				->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
3247
-			$query->executeStatement();
3248
-
3249
-			$this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent($calendarId, $calendarData));
3250
-			return null;
3251
-		}, $this->db);
3252
-	}
3253
-
3254
-	/**
3255
-	 * @param Calendar $calendar
3256
-	 * @return mixed
3257
-	 */
3258
-	public function getPublishStatus($calendar) {
3259
-		$query = $this->db->getQueryBuilder();
3260
-		$result = $query->select('publicuri')
3261
-			->from('dav_shares')
3262
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3263
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
3264
-			->executeQuery();
3265
-
3266
-		$row = $result->fetch();
3267
-		$result->closeCursor();
3268
-		return $row ? reset($row) : false;
3269
-	}
3270
-
3271
-	/**
3272
-	 * @param int $resourceId
3273
-	 * @param list<array{privilege: string, principal: string, protected: bool}> $acl
3274
-	 * @return list<array{privilege: string, principal: string, protected: bool}>
3275
-	 */
3276
-	public function applyShareAcl(int $resourceId, array $acl): array {
3277
-		$shares = $this->calendarSharingBackend->getShares($resourceId);
3278
-		return $this->calendarSharingBackend->applyShareAcl($shares, $acl);
3279
-	}
3280
-
3281
-	/**
3282
-	 * update properties table
3283
-	 *
3284
-	 * @param int $calendarId
3285
-	 * @param string $objectUri
3286
-	 * @param string $calendarData
3287
-	 * @param int $calendarType
3288
-	 */
3289
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
3290
-		$this->cachedObjects = [];
3291
-		$this->atomic(function () use ($calendarId, $objectUri, $calendarData, $calendarType): void {
3292
-			$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
3293
-
3294
-			try {
3295
-				$vCalendar = $this->readCalendarData($calendarData);
3296
-			} catch (\Exception $ex) {
3297
-				return;
3298
-			}
3299
-
3300
-			$this->purgeProperties($calendarId, $objectId);
3301
-
3302
-			$query = $this->db->getQueryBuilder();
3303
-			$query->insert($this->dbObjectPropertiesTable)
3304
-				->values(
3305
-					[
3306
-						'calendarid' => $query->createNamedParameter($calendarId),
3307
-						'calendartype' => $query->createNamedParameter($calendarType),
3308
-						'objectid' => $query->createNamedParameter($objectId),
3309
-						'name' => $query->createParameter('name'),
3310
-						'parameter' => $query->createParameter('parameter'),
3311
-						'value' => $query->createParameter('value'),
3312
-					]
3313
-				);
3314
-
3315
-			$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
3316
-			foreach ($vCalendar->getComponents() as $component) {
3317
-				if (!in_array($component->name, $indexComponents)) {
3318
-					continue;
3319
-				}
3320
-
3321
-				foreach ($component->children() as $property) {
3322
-					if (in_array($property->name, self::INDEXED_PROPERTIES, true)) {
3323
-						$value = $property->getValue();
3324
-						// is this a shitty db?
3325
-						if (!$this->db->supports4ByteText()) {
3326
-							$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3327
-						}
3328
-						$value = mb_strcut($value, 0, 254);
3329
-
3330
-						$query->setParameter('name', $property->name);
3331
-						$query->setParameter('parameter', null);
3332
-						$query->setParameter('value', mb_strcut($value, 0, 254));
3333
-						$query->executeStatement();
3334
-					}
3335
-
3336
-					if (array_key_exists($property->name, self::$indexParameters)) {
3337
-						$parameters = $property->parameters();
3338
-						$indexedParametersForProperty = self::$indexParameters[$property->name];
3339
-
3340
-						foreach ($parameters as $key => $value) {
3341
-							if (in_array($key, $indexedParametersForProperty)) {
3342
-								// is this a shitty db?
3343
-								if ($this->db->supports4ByteText()) {
3344
-									$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3345
-								}
3346
-
3347
-								$query->setParameter('name', $property->name);
3348
-								$query->setParameter('parameter', mb_strcut($key, 0, 254));
3349
-								$query->setParameter('value', mb_strcut($value, 0, 254));
3350
-								$query->executeStatement();
3351
-							}
3352
-						}
3353
-					}
3354
-				}
3355
-			}
3356
-		}, $this->db);
3357
-	}
3358
-
3359
-	/**
3360
-	 * deletes all birthday calendars
3361
-	 */
3362
-	public function deleteAllBirthdayCalendars() {
3363
-		$this->atomic(function (): void {
3364
-			$query = $this->db->getQueryBuilder();
3365
-			$result = $query->select(['id'])->from('calendars')
3366
-				->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
3367
-				->executeQuery();
3368
-
3369
-			while (($row = $result->fetch()) !== false) {
3370
-				$this->deleteCalendar(
3371
-					$row['id'],
3372
-					true // No data to keep in the trashbin, if the user re-enables then we regenerate
3373
-				);
3374
-			}
3375
-			$result->closeCursor();
3376
-		}, $this->db);
3377
-	}
3378
-
3379
-	/**
3380
-	 * @param $subscriptionId
3381
-	 */
3382
-	public function purgeAllCachedEventsForSubscription($subscriptionId) {
3383
-		$this->atomic(function () use ($subscriptionId): void {
3384
-			$query = $this->db->getQueryBuilder();
3385
-			$query->select('uri')
3386
-				->from('calendarobjects')
3387
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3388
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
3389
-			$stmt = $query->executeQuery();
3390
-
3391
-			$uris = [];
3392
-			while (($row = $stmt->fetch()) !== false) {
3393
-				$uris[] = $row['uri'];
3394
-			}
3395
-			$stmt->closeCursor();
3396
-
3397
-			$query = $this->db->getQueryBuilder();
3398
-			$query->delete('calendarobjects')
3399
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3400
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3401
-				->executeStatement();
3402
-
3403
-			$query = $this->db->getQueryBuilder();
3404
-			$query->delete('calendarchanges')
3405
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3406
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3407
-				->executeStatement();
3408
-
3409
-			$query = $this->db->getQueryBuilder();
3410
-			$query->delete($this->dbObjectPropertiesTable)
3411
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3412
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3413
-				->executeStatement();
3414
-
3415
-			$this->addChanges($subscriptionId, $uris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3416
-		}, $this->db);
3417
-	}
3418
-
3419
-	/**
3420
-	 * @param int $subscriptionId
3421
-	 * @param array<int> $calendarObjectIds
3422
-	 * @param array<string> $calendarObjectUris
3423
-	 */
3424
-	public function purgeCachedEventsForSubscription(int $subscriptionId, array $calendarObjectIds, array $calendarObjectUris): void {
3425
-		if (empty($calendarObjectUris)) {
3426
-			return;
3427
-		}
3428
-
3429
-		$this->atomic(function () use ($subscriptionId, $calendarObjectIds, $calendarObjectUris): void {
3430
-			foreach (array_chunk($calendarObjectIds, 1000) as $chunk) {
3431
-				$query = $this->db->getQueryBuilder();
3432
-				$query->delete($this->dbObjectPropertiesTable)
3433
-					->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3434
-					->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3435
-					->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3436
-					->executeStatement();
3437
-
3438
-				$query = $this->db->getQueryBuilder();
3439
-				$query->delete('calendarobjects')
3440
-					->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3441
-					->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3442
-					->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3443
-					->executeStatement();
3444
-			}
3445
-
3446
-			foreach (array_chunk($calendarObjectUris, 1000) as $chunk) {
3447
-				$query = $this->db->getQueryBuilder();
3448
-				$query->delete('calendarchanges')
3449
-					->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3450
-					->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3451
-					->andWhere($query->expr()->in('uri', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
3452
-					->executeStatement();
3453
-			}
3454
-			$this->addChanges($subscriptionId, $calendarObjectUris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3455
-		}, $this->db);
3456
-	}
3457
-
3458
-	/**
3459
-	 * Move a calendar from one user to another
3460
-	 *
3461
-	 * @param string $uriName
3462
-	 * @param string $uriOrigin
3463
-	 * @param string $uriDestination
3464
-	 * @param string $newUriName (optional) the new uriName
3465
-	 */
3466
-	public function moveCalendar($uriName, $uriOrigin, $uriDestination, $newUriName = null) {
3467
-		$query = $this->db->getQueryBuilder();
3468
-		$query->update('calendars')
3469
-			->set('principaluri', $query->createNamedParameter($uriDestination))
3470
-			->set('uri', $query->createNamedParameter($newUriName ?: $uriName))
3471
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
3472
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
3473
-			->executeStatement();
3474
-	}
3475
-
3476
-	/**
3477
-	 * read VCalendar data into a VCalendar object
3478
-	 *
3479
-	 * @param string $objectData
3480
-	 * @return VCalendar
3481
-	 */
3482
-	protected function readCalendarData($objectData) {
3483
-		return Reader::read($objectData);
3484
-	}
3485
-
3486
-	/**
3487
-	 * delete all properties from a given calendar object
3488
-	 *
3489
-	 * @param int $calendarId
3490
-	 * @param int $objectId
3491
-	 */
3492
-	protected function purgeProperties($calendarId, $objectId) {
3493
-		$this->cachedObjects = [];
3494
-		$query = $this->db->getQueryBuilder();
3495
-		$query->delete($this->dbObjectPropertiesTable)
3496
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
3497
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
3498
-		$query->executeStatement();
3499
-	}
3500
-
3501
-	/**
3502
-	 * get ID from a given calendar object
3503
-	 *
3504
-	 * @param int $calendarId
3505
-	 * @param string $uri
3506
-	 * @param int $calendarType
3507
-	 * @return int
3508
-	 */
3509
-	protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
3510
-		$query = $this->db->getQueryBuilder();
3511
-		$query->select('id')
3512
-			->from('calendarobjects')
3513
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
3514
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
3515
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
3516
-
3517
-		$result = $query->executeQuery();
3518
-		$objectIds = $result->fetch();
3519
-		$result->closeCursor();
3520
-
3521
-		if (!isset($objectIds['id'])) {
3522
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
3523
-		}
3524
-
3525
-		return (int)$objectIds['id'];
3526
-	}
3527
-
3528
-	/**
3529
-	 * @throws \InvalidArgumentException
3530
-	 */
3531
-	public function pruneOutdatedSyncTokens(int $keep, int $retention): int {
3532
-		if ($keep < 0) {
3533
-			throw new \InvalidArgumentException();
3534
-		}
3535
-
3536
-		$query = $this->db->getQueryBuilder();
3537
-		$query->select($query->func()->max('id'))
3538
-			->from('calendarchanges');
3539
-
3540
-		$result = $query->executeQuery();
3541
-		$maxId = (int)$result->fetchOne();
3542
-		$result->closeCursor();
3543
-		if (!$maxId || $maxId < $keep) {
3544
-			return 0;
3545
-		}
3546
-
3547
-		$query = $this->db->getQueryBuilder();
3548
-		$query->delete('calendarchanges')
3549
-			->where(
3550
-				$query->expr()->lte('id', $query->createNamedParameter($maxId - $keep, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
3551
-				$query->expr()->lte('created_at', $query->createNamedParameter($retention)),
3552
-			);
3553
-		return $query->executeStatement();
3554
-	}
3555
-
3556
-	/**
3557
-	 * return legacy endpoint principal name to new principal name
3558
-	 *
3559
-	 * @param $principalUri
3560
-	 * @param $toV2
3561
-	 * @return string
3562
-	 */
3563
-	private function convertPrincipal($principalUri, $toV2) {
3564
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
3565
-			[, $name] = Uri\split($principalUri);
3566
-			if ($toV2 === true) {
3567
-				return "principals/users/$name";
3568
-			}
3569
-			return "principals/$name";
3570
-		}
3571
-		return $principalUri;
3572
-	}
3573
-
3574
-	/**
3575
-	 * adds information about an owner to the calendar data
3576
-	 *
3577
-	 */
3578
-	private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
3579
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
3580
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
3581
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
3582
-			$uri = $calendarInfo[$ownerPrincipalKey];
3583
-		} else {
3584
-			$uri = $calendarInfo['principaluri'];
3585
-		}
3586
-
3587
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
3588
-		if (isset($principalInformation['{DAV:}displayname'])) {
3589
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
3590
-		}
3591
-		return $calendarInfo;
3592
-	}
3593
-
3594
-	private function addResourceTypeToCalendar(array $row, array $calendar): array {
3595
-		if (isset($row['deleted_at'])) {
3596
-			// Columns is set and not null -> this is a deleted calendar
3597
-			// we send a custom resourcetype to hide the deleted calendar
3598
-			// from ordinary DAV clients, but the Calendar app will know
3599
-			// how to handle this special resource.
3600
-			$calendar['{DAV:}resourcetype'] = new DAV\Xml\Property\ResourceType([
3601
-				'{DAV:}collection',
3602
-				sprintf('{%s}deleted-calendar', \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD),
3603
-			]);
3604
-		}
3605
-		return $calendar;
3606
-	}
3607
-
3608
-	/**
3609
-	 * Amend the calendar info with database row data
3610
-	 *
3611
-	 * @param array $row
3612
-	 * @param array $calendar
3613
-	 *
3614
-	 * @return array
3615
-	 */
3616
-	private function rowToCalendar($row, array $calendar): array {
3617
-		foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
3618
-			$value = $row[$dbName];
3619
-			if ($value !== null) {
3620
-				settype($value, $type);
3621
-			}
3622
-			$calendar[$xmlName] = $value;
3623
-		}
3624
-		return $calendar;
3625
-	}
3626
-
3627
-	/**
3628
-	 * Amend the subscription info with database row data
3629
-	 *
3630
-	 * @param array $row
3631
-	 * @param array $subscription
3632
-	 *
3633
-	 * @return array
3634
-	 */
3635
-	private function rowToSubscription($row, array $subscription): array {
3636
-		foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
3637
-			$value = $row[$dbName];
3638
-			if ($value !== null) {
3639
-				settype($value, $type);
3640
-			}
3641
-			$subscription[$xmlName] = $value;
3642
-		}
3643
-		return $subscription;
3644
-	}
3645
-
3646
-	/**
3647
-	 * delete all invitations from a given calendar
3648
-	 *
3649
-	 * @since 31.0.0
3650
-	 *
3651
-	 * @param int $calendarId
3652
-	 *
3653
-	 * @return void
3654
-	 */
3655
-	protected function purgeCalendarInvitations(int $calendarId): void {
3656
-		// select all calendar object uid's
3657
-		$cmd = $this->db->getQueryBuilder();
3658
-		$cmd->select('uid')
3659
-			->from($this->dbObjectsTable)
3660
-			->where($cmd->expr()->eq('calendarid', $cmd->createNamedParameter($calendarId)));
3661
-		$allIds = $cmd->executeQuery()->fetchAll(\PDO::FETCH_COLUMN);
3662
-		// delete all links that match object uid's
3663
-		$cmd = $this->db->getQueryBuilder();
3664
-		$cmd->delete($this->dbObjectInvitationsTable)
3665
-			->where($cmd->expr()->in('uid', $cmd->createParameter('uids'), IQueryBuilder::PARAM_STR_ARRAY));
3666
-		foreach (array_chunk($allIds, 1000) as $chunkIds) {
3667
-			$cmd->setParameter('uids', $chunkIds, IQueryBuilder::PARAM_STR_ARRAY);
3668
-			$cmd->executeStatement();
3669
-		}
3670
-	}
3671
-
3672
-	/**
3673
-	 * Delete all invitations from a given calendar event
3674
-	 *
3675
-	 * @since 31.0.0
3676
-	 *
3677
-	 * @param string $eventId UID of the event
3678
-	 *
3679
-	 * @return void
3680
-	 */
3681
-	protected function purgeObjectInvitations(string $eventId): void {
3682
-		$cmd = $this->db->getQueryBuilder();
3683
-		$cmd->delete($this->dbObjectInvitationsTable)
3684
-			->where($cmd->expr()->eq('uid', $cmd->createNamedParameter($eventId, IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR));
3685
-		$cmd->executeStatement();
3686
-	}
3687
-
3688
-	public function unshare(IShareable $shareable, string $principal): void {
3689
-		$this->atomic(function () use ($shareable, $principal): void {
3690
-			$calendarData = $this->getCalendarById($shareable->getResourceId());
3691
-			if ($calendarData === null) {
3692
-				throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $shareable->getResourceId());
3693
-			}
3694
-
3695
-			$oldShares = $this->getShares($shareable->getResourceId());
3696
-			$unshare = $this->calendarSharingBackend->unshare($shareable, $principal);
3697
-
3698
-			if ($unshare) {
3699
-				$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent(
3700
-					$shareable->getResourceId(),
3701
-					$calendarData,
3702
-					$oldShares,
3703
-					[],
3704
-					[$principal]
3705
-				));
3706
-			}
3707
-		}, $this->db);
3708
-	}
3709
-
3710
-	/**
3711
-	 * @return array<string, mixed>[]
3712
-	 */
3713
-	public function getFederatedCalendarsForUser(string $principalUri): array {
3714
-		$federatedCalendars = $this->federatedCalendarMapper->findByPrincipalUri($principalUri);
3715
-		return array_map(
3716
-			static fn (FederatedCalendarEntity $entity) => $entity->toCalendarInfo(),
3717
-			$federatedCalendars,
3718
-		);
3719
-	}
3720
-
3721
-	public function getFederatedCalendarByUri(string $principalUri, string $uri): ?array {
3722
-		$federatedCalendar = $this->federatedCalendarMapper->findByUri($principalUri, $uri);
3723
-		return $federatedCalendar?->toCalendarInfo();
3724
-	}
111
+    use TTransactional;
112
+
113
+    public const CALENDAR_TYPE_CALENDAR = 0;
114
+    public const CALENDAR_TYPE_SUBSCRIPTION = 1;
115
+    public const CALENDAR_TYPE_FEDERATED = 2;
116
+
117
+    public const PERSONAL_CALENDAR_URI = 'personal';
118
+    public const PERSONAL_CALENDAR_NAME = 'Personal';
119
+
120
+    public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
121
+    public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
122
+
123
+    /**
124
+     * We need to specify a max date, because we need to stop *somewhere*
125
+     *
126
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
127
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
128
+     * in 2038-01-19 to avoid problems when the date is converted
129
+     * to a unix timestamp.
130
+     */
131
+    public const MAX_DATE = '2038-01-01';
132
+
133
+    public const ACCESS_PUBLIC = 4;
134
+    public const CLASSIFICATION_PUBLIC = 0;
135
+    public const CLASSIFICATION_PRIVATE = 1;
136
+    public const CLASSIFICATION_CONFIDENTIAL = 2;
137
+
138
+    /**
139
+     * List of CalDAV properties, and how they map to database field names and their type
140
+     * Add your own properties by simply adding on to this array.
141
+     *
142
+     * @var array
143
+     * @psalm-var array<string, string[]>
144
+     */
145
+    public array $propertyMap = [
146
+        '{DAV:}displayname' => ['displayname', 'string'],
147
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => ['description', 'string'],
148
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => ['timezone', 'string'],
149
+        '{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
150
+        '{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
151
+        '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => ['deleted_at', 'int'],
152
+    ];
153
+
154
+    /**
155
+     * List of subscription properties, and how they map to database field names.
156
+     *
157
+     * @var array
158
+     */
159
+    public array $subscriptionPropertyMap = [
160
+        '{DAV:}displayname' => ['displayname', 'string'],
161
+        '{http://apple.com/ns/ical/}refreshrate' => ['refreshrate', 'string'],
162
+        '{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
163
+        '{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
164
+        '{http://calendarserver.org/ns/}subscribed-strip-todos' => ['striptodos', 'bool'],
165
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms' => ['stripalarms', 'string'],
166
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => ['stripattachments', 'string'],
167
+    ];
168
+
169
+    /**
170
+     * properties to index
171
+     *
172
+     * This list has to be kept in sync with ICalendarQuery::SEARCH_PROPERTY_*
173
+     *
174
+     * @see \OCP\Calendar\ICalendarQuery
175
+     */
176
+    private const INDEXED_PROPERTIES = [
177
+        'CATEGORIES',
178
+        'COMMENT',
179
+        'DESCRIPTION',
180
+        'LOCATION',
181
+        'RESOURCES',
182
+        'STATUS',
183
+        'SUMMARY',
184
+        'ATTENDEE',
185
+        'CONTACT',
186
+        'ORGANIZER'
187
+    ];
188
+
189
+    /** @var array parameters to index */
190
+    public static array $indexParameters = [
191
+        'ATTENDEE' => ['CN'],
192
+        'ORGANIZER' => ['CN'],
193
+    ];
194
+
195
+    /**
196
+     * @var string[] Map of uid => display name
197
+     */
198
+    protected array $userDisplayNames;
199
+
200
+    private string $dbObjectsTable = 'calendarobjects';
201
+    private string $dbObjectPropertiesTable = 'calendarobjects_props';
202
+    private string $dbObjectInvitationsTable = 'calendar_invitations';
203
+    private array $cachedObjects = [];
204
+
205
+    public function __construct(
206
+        private IDBConnection $db,
207
+        private Principal $principalBackend,
208
+        private IUserManager $userManager,
209
+        private ISecureRandom $random,
210
+        private LoggerInterface $logger,
211
+        private IEventDispatcher $dispatcher,
212
+        private IConfig $config,
213
+        private Sharing\Backend $calendarSharingBackend,
214
+        private FederatedCalendarMapper $federatedCalendarMapper,
215
+        private bool $legacyEndpoint = false,
216
+    ) {
217
+    }
218
+
219
+    /**
220
+     * Return the number of calendars owned by the given principal.
221
+     *
222
+     * Calendars shared with the given principal are not counted!
223
+     *
224
+     * By default, this excludes the automatically generated birthday calendar.
225
+     */
226
+    public function getCalendarsForUserCount(string $principalUri, bool $excludeBirthday = true): int {
227
+        $principalUri = $this->convertPrincipal($principalUri, true);
228
+        $query = $this->db->getQueryBuilder();
229
+        $query->select($query->func()->count('*'))
230
+            ->from('calendars');
231
+
232
+        if ($principalUri === '') {
233
+            $query->where($query->expr()->emptyString('principaluri'));
234
+        } else {
235
+            $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
236
+        }
237
+
238
+        if ($excludeBirthday) {
239
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
240
+        }
241
+
242
+        $result = $query->executeQuery();
243
+        $column = (int)$result->fetchOne();
244
+        $result->closeCursor();
245
+        return $column;
246
+    }
247
+
248
+    /**
249
+     * Return the number of subscriptions for a principal
250
+     */
251
+    public function getSubscriptionsForUserCount(string $principalUri): int {
252
+        $principalUri = $this->convertPrincipal($principalUri, true);
253
+        $query = $this->db->getQueryBuilder();
254
+        $query->select($query->func()->count('*'))
255
+            ->from('calendarsubscriptions');
256
+
257
+        if ($principalUri === '') {
258
+            $query->where($query->expr()->emptyString('principaluri'));
259
+        } else {
260
+            $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
261
+        }
262
+
263
+        $result = $query->executeQuery();
264
+        $column = (int)$result->fetchOne();
265
+        $result->closeCursor();
266
+        return $column;
267
+    }
268
+
269
+    /**
270
+     * @return array{id: int, deleted_at: int}[]
271
+     */
272
+    public function getDeletedCalendars(int $deletedBefore): array {
273
+        $qb = $this->db->getQueryBuilder();
274
+        $qb->select(['id', 'deleted_at'])
275
+            ->from('calendars')
276
+            ->where($qb->expr()->isNotNull('deleted_at'))
277
+            ->andWhere($qb->expr()->lt('deleted_at', $qb->createNamedParameter($deletedBefore)));
278
+        $result = $qb->executeQuery();
279
+        $calendars = [];
280
+        while (($row = $result->fetch()) !== false) {
281
+            $calendars[] = [
282
+                'id' => (int)$row['id'],
283
+                'deleted_at' => (int)$row['deleted_at'],
284
+            ];
285
+        }
286
+        $result->closeCursor();
287
+        return $calendars;
288
+    }
289
+
290
+    /**
291
+     * Returns a list of calendars for a principal.
292
+     *
293
+     * Every project is an array with the following keys:
294
+     *  * id, a unique id that will be used by other functions to modify the
295
+     *    calendar. This can be the same as the uri or a database key.
296
+     *  * uri, which the basename of the uri with which the calendar is
297
+     *    accessed.
298
+     *  * principaluri. The owner of the calendar. Almost always the same as
299
+     *    principalUri passed to this method.
300
+     *
301
+     * Furthermore it can contain webdav properties in clark notation. A very
302
+     * common one is '{DAV:}displayname'.
303
+     *
304
+     * Many clients also require:
305
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
306
+     * For this property, you can just return an instance of
307
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
308
+     *
309
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
310
+     * ACL will automatically be put in read-only mode.
311
+     *
312
+     * @param string $principalUri
313
+     * @return array
314
+     */
315
+    public function getCalendarsForUser($principalUri) {
316
+        return $this->atomic(function () use ($principalUri) {
317
+            $principalUriOriginal = $principalUri;
318
+            $principalUri = $this->convertPrincipal($principalUri, true);
319
+            $fields = array_column($this->propertyMap, 0);
320
+            $fields[] = 'id';
321
+            $fields[] = 'uri';
322
+            $fields[] = 'synctoken';
323
+            $fields[] = 'components';
324
+            $fields[] = 'principaluri';
325
+            $fields[] = 'transparent';
326
+
327
+            // Making fields a comma-delimited list
328
+            $query = $this->db->getQueryBuilder();
329
+            $query->select($fields)
330
+                ->from('calendars')
331
+                ->orderBy('calendarorder', 'ASC');
332
+
333
+            if ($principalUri === '') {
334
+                $query->where($query->expr()->emptyString('principaluri'));
335
+            } else {
336
+                $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
337
+            }
338
+
339
+            $result = $query->executeQuery();
340
+
341
+            $calendars = [];
342
+            while ($row = $result->fetch()) {
343
+                $row['principaluri'] = (string)$row['principaluri'];
344
+                $components = [];
345
+                if ($row['components']) {
346
+                    $components = explode(',', $row['components']);
347
+                }
348
+
349
+                $calendar = [
350
+                    'id' => $row['id'],
351
+                    'uri' => $row['uri'],
352
+                    'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
353
+                    '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
354
+                    '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
355
+                    '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
356
+                    '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
357
+                    '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
358
+                ];
359
+
360
+                $calendar = $this->rowToCalendar($row, $calendar);
361
+                $calendar = $this->addOwnerPrincipalToCalendar($calendar);
362
+                $calendar = $this->addResourceTypeToCalendar($row, $calendar);
363
+
364
+                if (!isset($calendars[$calendar['id']])) {
365
+                    $calendars[$calendar['id']] = $calendar;
366
+                }
367
+            }
368
+            $result->closeCursor();
369
+
370
+            // query for shared calendars
371
+            $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
372
+            $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
373
+            $principals[] = $principalUri;
374
+
375
+            $fields = array_column($this->propertyMap, 0);
376
+            $fields = array_map(function (string $field) {
377
+                return 'a.' . $field;
378
+            }, $fields);
379
+            $fields[] = 'a.id';
380
+            $fields[] = 'a.uri';
381
+            $fields[] = 'a.synctoken';
382
+            $fields[] = 'a.components';
383
+            $fields[] = 'a.principaluri';
384
+            $fields[] = 'a.transparent';
385
+            $fields[] = 's.access';
386
+
387
+            $select = $this->db->getQueryBuilder();
388
+            $subSelect = $this->db->getQueryBuilder();
389
+
390
+            $subSelect->select('resourceid')
391
+                ->from('dav_shares', 'd')
392
+                ->where($subSelect->expr()->eq('d.access', $select->createNamedParameter(Backend::ACCESS_UNSHARED, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
393
+                ->andWhere($subSelect->expr()->in('d.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY));
394
+
395
+            $select->select($fields)
396
+                ->from('dav_shares', 's')
397
+                ->join('s', 'calendars', 'a', $select->expr()->eq('s.resourceid', 'a.id', IQueryBuilder::PARAM_INT))
398
+                ->where($select->expr()->in('s.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
399
+                ->andWhere($select->expr()->eq('s.type', $select->createNamedParameter('calendar', IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR))
400
+                ->andWhere($select->expr()->notIn('a.id', $select->createFunction($subSelect->getSQL()), IQueryBuilder::PARAM_INT_ARRAY));
401
+
402
+            $results = $select->executeQuery();
403
+
404
+            $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
405
+            while ($row = $results->fetch()) {
406
+                $row['principaluri'] = (string)$row['principaluri'];
407
+                if ($row['principaluri'] === $principalUri) {
408
+                    continue;
409
+                }
410
+
411
+                $readOnly = (int)$row['access'] === Backend::ACCESS_READ;
412
+                if (isset($calendars[$row['id']])) {
413
+                    if ($readOnly) {
414
+                        // New share can not have more permissions than the old one.
415
+                        continue;
416
+                    }
417
+                    if (isset($calendars[$row['id']][$readOnlyPropertyName])
418
+                        && $calendars[$row['id']][$readOnlyPropertyName] === 0) {
419
+                        // Old share is already read-write, no more permissions can be gained
420
+                        continue;
421
+                    }
422
+                }
423
+
424
+                [, $name] = Uri\split($row['principaluri']);
425
+                $uri = $row['uri'] . '_shared_by_' . $name;
426
+                $row['displayname'] = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? ($name ?? '')) . ')';
427
+                $components = [];
428
+                if ($row['components']) {
429
+                    $components = explode(',', $row['components']);
430
+                }
431
+                $calendar = [
432
+                    'id' => $row['id'],
433
+                    'uri' => $uri,
434
+                    'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
435
+                    '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
436
+                    '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
437
+                    '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
438
+                    '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
439
+                    '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
440
+                    $readOnlyPropertyName => $readOnly,
441
+                ];
442
+
443
+                $calendar = $this->rowToCalendar($row, $calendar);
444
+                $calendar = $this->addOwnerPrincipalToCalendar($calendar);
445
+                $calendar = $this->addResourceTypeToCalendar($row, $calendar);
446
+
447
+                $calendars[$calendar['id']] = $calendar;
448
+            }
449
+            $result->closeCursor();
450
+
451
+            return array_values($calendars);
452
+        }, $this->db);
453
+    }
454
+
455
+    /**
456
+     * @param $principalUri
457
+     * @return array
458
+     */
459
+    public function getUsersOwnCalendars($principalUri) {
460
+        $principalUri = $this->convertPrincipal($principalUri, true);
461
+        $fields = array_column($this->propertyMap, 0);
462
+        $fields[] = 'id';
463
+        $fields[] = 'uri';
464
+        $fields[] = 'synctoken';
465
+        $fields[] = 'components';
466
+        $fields[] = 'principaluri';
467
+        $fields[] = 'transparent';
468
+        // Making fields a comma-delimited list
469
+        $query = $this->db->getQueryBuilder();
470
+        $query->select($fields)->from('calendars')
471
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
472
+            ->orderBy('calendarorder', 'ASC');
473
+        $stmt = $query->executeQuery();
474
+        $calendars = [];
475
+        while ($row = $stmt->fetch()) {
476
+            $row['principaluri'] = (string)$row['principaluri'];
477
+            $components = [];
478
+            if ($row['components']) {
479
+                $components = explode(',', $row['components']);
480
+            }
481
+            $calendar = [
482
+                'id' => $row['id'],
483
+                'uri' => $row['uri'],
484
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
485
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
486
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
487
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
488
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
489
+            ];
490
+
491
+            $calendar = $this->rowToCalendar($row, $calendar);
492
+            $calendar = $this->addOwnerPrincipalToCalendar($calendar);
493
+            $calendar = $this->addResourceTypeToCalendar($row, $calendar);
494
+
495
+            if (!isset($calendars[$calendar['id']])) {
496
+                $calendars[$calendar['id']] = $calendar;
497
+            }
498
+        }
499
+        $stmt->closeCursor();
500
+        return array_values($calendars);
501
+    }
502
+
503
+    /**
504
+     * @return array
505
+     */
506
+    public function getPublicCalendars() {
507
+        $fields = array_column($this->propertyMap, 0);
508
+        $fields[] = 'a.id';
509
+        $fields[] = 'a.uri';
510
+        $fields[] = 'a.synctoken';
511
+        $fields[] = 'a.components';
512
+        $fields[] = 'a.principaluri';
513
+        $fields[] = 'a.transparent';
514
+        $fields[] = 's.access';
515
+        $fields[] = 's.publicuri';
516
+        $calendars = [];
517
+        $query = $this->db->getQueryBuilder();
518
+        $result = $query->select($fields)
519
+            ->from('dav_shares', 's')
520
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
521
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
522
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
523
+            ->executeQuery();
524
+
525
+        while ($row = $result->fetch()) {
526
+            $row['principaluri'] = (string)$row['principaluri'];
527
+            [, $name] = Uri\split($row['principaluri']);
528
+            $row['displayname'] = $row['displayname'] . "($name)";
529
+            $components = [];
530
+            if ($row['components']) {
531
+                $components = explode(',', $row['components']);
532
+            }
533
+            $calendar = [
534
+                'id' => $row['id'],
535
+                'uri' => $row['publicuri'],
536
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
537
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
538
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
539
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
540
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
541
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
542
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => true,
543
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
544
+            ];
545
+
546
+            $calendar = $this->rowToCalendar($row, $calendar);
547
+            $calendar = $this->addOwnerPrincipalToCalendar($calendar);
548
+            $calendar = $this->addResourceTypeToCalendar($row, $calendar);
549
+
550
+            if (!isset($calendars[$calendar['id']])) {
551
+                $calendars[$calendar['id']] = $calendar;
552
+            }
553
+        }
554
+        $result->closeCursor();
555
+
556
+        return array_values($calendars);
557
+    }
558
+
559
+    /**
560
+     * @param string $uri
561
+     * @return array
562
+     * @throws NotFound
563
+     */
564
+    public function getPublicCalendar($uri) {
565
+        $fields = array_column($this->propertyMap, 0);
566
+        $fields[] = 'a.id';
567
+        $fields[] = 'a.uri';
568
+        $fields[] = 'a.synctoken';
569
+        $fields[] = 'a.components';
570
+        $fields[] = 'a.principaluri';
571
+        $fields[] = 'a.transparent';
572
+        $fields[] = 's.access';
573
+        $fields[] = 's.publicuri';
574
+        $query = $this->db->getQueryBuilder();
575
+        $result = $query->select($fields)
576
+            ->from('dav_shares', 's')
577
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
578
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
579
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
580
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
581
+            ->executeQuery();
582
+
583
+        $row = $result->fetch();
584
+
585
+        $result->closeCursor();
586
+
587
+        if ($row === false) {
588
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
589
+        }
590
+
591
+        $row['principaluri'] = (string)$row['principaluri'];
592
+        [, $name] = Uri\split($row['principaluri']);
593
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
594
+        $components = [];
595
+        if ($row['components']) {
596
+            $components = explode(',', $row['components']);
597
+        }
598
+        $calendar = [
599
+            'id' => $row['id'],
600
+            'uri' => $row['publicuri'],
601
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
602
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
603
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
604
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
605
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
606
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
607
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => true,
608
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
609
+        ];
610
+
611
+        $calendar = $this->rowToCalendar($row, $calendar);
612
+        $calendar = $this->addOwnerPrincipalToCalendar($calendar);
613
+        $calendar = $this->addResourceTypeToCalendar($row, $calendar);
614
+
615
+        return $calendar;
616
+    }
617
+
618
+    /**
619
+     * @param string $principal
620
+     * @param string $uri
621
+     * @return array|null
622
+     */
623
+    public function getCalendarByUri($principal, $uri) {
624
+        $fields = array_column($this->propertyMap, 0);
625
+        $fields[] = 'id';
626
+        $fields[] = 'uri';
627
+        $fields[] = 'synctoken';
628
+        $fields[] = 'components';
629
+        $fields[] = 'principaluri';
630
+        $fields[] = 'transparent';
631
+
632
+        // Making fields a comma-delimited list
633
+        $query = $this->db->getQueryBuilder();
634
+        $query->select($fields)->from('calendars')
635
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
636
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
637
+            ->setMaxResults(1);
638
+        $stmt = $query->executeQuery();
639
+
640
+        $row = $stmt->fetch();
641
+        $stmt->closeCursor();
642
+        if ($row === false) {
643
+            return null;
644
+        }
645
+
646
+        $row['principaluri'] = (string)$row['principaluri'];
647
+        $components = [];
648
+        if ($row['components']) {
649
+            $components = explode(',', $row['components']);
650
+        }
651
+
652
+        $calendar = [
653
+            'id' => $row['id'],
654
+            'uri' => $row['uri'],
655
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
656
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
657
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
658
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
659
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
660
+        ];
661
+
662
+        $calendar = $this->rowToCalendar($row, $calendar);
663
+        $calendar = $this->addOwnerPrincipalToCalendar($calendar);
664
+        $calendar = $this->addResourceTypeToCalendar($row, $calendar);
665
+
666
+        return $calendar;
667
+    }
668
+
669
+    /**
670
+     * @psalm-return CalendarInfo|null
671
+     * @return array|null
672
+     */
673
+    public function getCalendarById(int $calendarId): ?array {
674
+        $fields = array_column($this->propertyMap, 0);
675
+        $fields[] = 'id';
676
+        $fields[] = 'uri';
677
+        $fields[] = 'synctoken';
678
+        $fields[] = 'components';
679
+        $fields[] = 'principaluri';
680
+        $fields[] = 'transparent';
681
+
682
+        // Making fields a comma-delimited list
683
+        $query = $this->db->getQueryBuilder();
684
+        $query->select($fields)->from('calendars')
685
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
686
+            ->setMaxResults(1);
687
+        $stmt = $query->executeQuery();
688
+
689
+        $row = $stmt->fetch();
690
+        $stmt->closeCursor();
691
+        if ($row === false) {
692
+            return null;
693
+        }
694
+
695
+        $row['principaluri'] = (string)$row['principaluri'];
696
+        $components = [];
697
+        if ($row['components']) {
698
+            $components = explode(',', $row['components']);
699
+        }
700
+
701
+        $calendar = [
702
+            'id' => $row['id'],
703
+            'uri' => $row['uri'],
704
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
705
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
706
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?? 0,
707
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
708
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
709
+        ];
710
+
711
+        $calendar = $this->rowToCalendar($row, $calendar);
712
+        $calendar = $this->addOwnerPrincipalToCalendar($calendar);
713
+        $calendar = $this->addResourceTypeToCalendar($row, $calendar);
714
+
715
+        return $calendar;
716
+    }
717
+
718
+    /**
719
+     * @param $subscriptionId
720
+     */
721
+    public function getSubscriptionById($subscriptionId) {
722
+        $fields = array_column($this->subscriptionPropertyMap, 0);
723
+        $fields[] = 'id';
724
+        $fields[] = 'uri';
725
+        $fields[] = 'source';
726
+        $fields[] = 'synctoken';
727
+        $fields[] = 'principaluri';
728
+        $fields[] = 'lastmodified';
729
+
730
+        $query = $this->db->getQueryBuilder();
731
+        $query->select($fields)
732
+            ->from('calendarsubscriptions')
733
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
734
+            ->orderBy('calendarorder', 'asc');
735
+        $stmt = $query->executeQuery();
736
+
737
+        $row = $stmt->fetch();
738
+        $stmt->closeCursor();
739
+        if ($row === false) {
740
+            return null;
741
+        }
742
+
743
+        $row['principaluri'] = (string)$row['principaluri'];
744
+        $subscription = [
745
+            'id' => $row['id'],
746
+            'uri' => $row['uri'],
747
+            'principaluri' => $row['principaluri'],
748
+            'source' => $row['source'],
749
+            'lastmodified' => $row['lastmodified'],
750
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
751
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
752
+        ];
753
+
754
+        return $this->rowToSubscription($row, $subscription);
755
+    }
756
+
757
+    public function getSubscriptionByUri(string $principal, string $uri): ?array {
758
+        $fields = array_column($this->subscriptionPropertyMap, 0);
759
+        $fields[] = 'id';
760
+        $fields[] = 'uri';
761
+        $fields[] = 'source';
762
+        $fields[] = 'synctoken';
763
+        $fields[] = 'principaluri';
764
+        $fields[] = 'lastmodified';
765
+
766
+        $query = $this->db->getQueryBuilder();
767
+        $query->select($fields)
768
+            ->from('calendarsubscriptions')
769
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
770
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
771
+            ->setMaxResults(1);
772
+        $stmt = $query->executeQuery();
773
+
774
+        $row = $stmt->fetch();
775
+        $stmt->closeCursor();
776
+        if ($row === false) {
777
+            return null;
778
+        }
779
+
780
+        $row['principaluri'] = (string)$row['principaluri'];
781
+        $subscription = [
782
+            'id' => $row['id'],
783
+            'uri' => $row['uri'],
784
+            'principaluri' => $row['principaluri'],
785
+            'source' => $row['source'],
786
+            'lastmodified' => $row['lastmodified'],
787
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
788
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
789
+        ];
790
+
791
+        return $this->rowToSubscription($row, $subscription);
792
+    }
793
+
794
+    /**
795
+     * Creates a new calendar for a principal.
796
+     *
797
+     * If the creation was a success, an id must be returned that can be used to reference
798
+     * this calendar in other methods, such as updateCalendar.
799
+     *
800
+     * @param string $principalUri
801
+     * @param string $calendarUri
802
+     * @param array $properties
803
+     * @return int
804
+     *
805
+     * @throws CalendarException
806
+     */
807
+    public function createCalendar($principalUri, $calendarUri, array $properties) {
808
+        if (strlen($calendarUri) > 255) {
809
+            throw new CalendarException('URI too long. Calendar not created');
810
+        }
811
+
812
+        $values = [
813
+            'principaluri' => $this->convertPrincipal($principalUri, true),
814
+            'uri' => $calendarUri,
815
+            'synctoken' => 1,
816
+            'transparent' => 0,
817
+            'components' => 'VEVENT,VTODO,VJOURNAL',
818
+            'displayname' => $calendarUri
819
+        ];
820
+
821
+        // Default value
822
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
823
+        if (isset($properties[$sccs])) {
824
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
825
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
826
+            }
827
+            $values['components'] = implode(',', $properties[$sccs]->getValue());
828
+        } elseif (isset($properties['components'])) {
829
+            // Allow to provide components internally without having
830
+            // to create a SupportedCalendarComponentSet object
831
+            $values['components'] = $properties['components'];
832
+        }
833
+
834
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
835
+        if (isset($properties[$transp])) {
836
+            $values['transparent'] = (int)($properties[$transp]->getValue() === 'transparent');
837
+        }
838
+
839
+        foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
840
+            if (isset($properties[$xmlName])) {
841
+                $values[$dbName] = $properties[$xmlName];
842
+            }
843
+        }
844
+
845
+        [$calendarId, $calendarData] = $this->atomic(function () use ($values) {
846
+            $query = $this->db->getQueryBuilder();
847
+            $query->insert('calendars');
848
+            foreach ($values as $column => $value) {
849
+                $query->setValue($column, $query->createNamedParameter($value));
850
+            }
851
+            $query->executeStatement();
852
+            $calendarId = $query->getLastInsertId();
853
+
854
+            $calendarData = $this->getCalendarById($calendarId);
855
+            return [$calendarId, $calendarData];
856
+        }, $this->db);
857
+
858
+        $this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
859
+
860
+        return $calendarId;
861
+    }
862
+
863
+    /**
864
+     * Updates properties for a calendar.
865
+     *
866
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
867
+     * To do the actual updates, you must tell this object which properties
868
+     * you're going to process with the handle() method.
869
+     *
870
+     * Calling the handle method is like telling the PropPatch object "I
871
+     * promise I can handle updating this property".
872
+     *
873
+     * Read the PropPatch documentation for more info and examples.
874
+     *
875
+     * @param mixed $calendarId
876
+     * @param PropPatch $propPatch
877
+     * @return void
878
+     */
879
+    public function updateCalendar($calendarId, PropPatch $propPatch) {
880
+        $supportedProperties = array_keys($this->propertyMap);
881
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
882
+
883
+        $propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
884
+            $newValues = [];
885
+            foreach ($mutations as $propertyName => $propertyValue) {
886
+                switch ($propertyName) {
887
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
888
+                        $fieldName = 'transparent';
889
+                        $newValues[$fieldName] = (int)($propertyValue->getValue() === 'transparent');
890
+                        break;
891
+                    default:
892
+                        $fieldName = $this->propertyMap[$propertyName][0];
893
+                        $newValues[$fieldName] = $propertyValue;
894
+                        break;
895
+                }
896
+            }
897
+            [$calendarData, $shares] = $this->atomic(function () use ($calendarId, $newValues) {
898
+                $query = $this->db->getQueryBuilder();
899
+                $query->update('calendars');
900
+                foreach ($newValues as $fieldName => $value) {
901
+                    $query->set($fieldName, $query->createNamedParameter($value));
902
+                }
903
+                $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
904
+                $query->executeStatement();
905
+
906
+                $this->addChanges($calendarId, [''], 2);
907
+
908
+                $calendarData = $this->getCalendarById($calendarId);
909
+                $shares = $this->getShares($calendarId);
910
+                return [$calendarData, $shares];
911
+            }, $this->db);
912
+
913
+            $this->dispatcher->dispatchTyped(new CalendarUpdatedEvent($calendarId, $calendarData, $shares, $mutations));
914
+
915
+            return true;
916
+        });
917
+    }
918
+
919
+    /**
920
+     * Delete a calendar and all it's objects
921
+     *
922
+     * @param mixed $calendarId
923
+     * @return void
924
+     */
925
+    public function deleteCalendar($calendarId, bool $forceDeletePermanently = false) {
926
+        $this->atomic(function () use ($calendarId, $forceDeletePermanently): void {
927
+            // The calendar is deleted right away if this is either enforced by the caller
928
+            // or the special contacts birthday calendar or when the preference of an empty
929
+            // retention (0 seconds) is set, which signals a disabled trashbin.
930
+            $calendarData = $this->getCalendarById($calendarId);
931
+            $isBirthdayCalendar = isset($calendarData['uri']) && $calendarData['uri'] === BirthdayService::BIRTHDAY_CALENDAR_URI;
932
+            $trashbinDisabled = $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0';
933
+            if ($forceDeletePermanently || $isBirthdayCalendar || $trashbinDisabled) {
934
+                $calendarData = $this->getCalendarById($calendarId);
935
+                $shares = $this->getShares($calendarId);
936
+
937
+                $this->purgeCalendarInvitations($calendarId);
938
+
939
+                $qbDeleteCalendarObjectProps = $this->db->getQueryBuilder();
940
+                $qbDeleteCalendarObjectProps->delete($this->dbObjectPropertiesTable)
941
+                    ->where($qbDeleteCalendarObjectProps->expr()->eq('calendarid', $qbDeleteCalendarObjectProps->createNamedParameter($calendarId)))
942
+                    ->andWhere($qbDeleteCalendarObjectProps->expr()->eq('calendartype', $qbDeleteCalendarObjectProps->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
943
+                    ->executeStatement();
944
+
945
+                $qbDeleteCalendarObjects = $this->db->getQueryBuilder();
946
+                $qbDeleteCalendarObjects->delete('calendarobjects')
947
+                    ->where($qbDeleteCalendarObjects->expr()->eq('calendarid', $qbDeleteCalendarObjects->createNamedParameter($calendarId)))
948
+                    ->andWhere($qbDeleteCalendarObjects->expr()->eq('calendartype', $qbDeleteCalendarObjects->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
949
+                    ->executeStatement();
950
+
951
+                $qbDeleteCalendarChanges = $this->db->getQueryBuilder();
952
+                $qbDeleteCalendarChanges->delete('calendarchanges')
953
+                    ->where($qbDeleteCalendarChanges->expr()->eq('calendarid', $qbDeleteCalendarChanges->createNamedParameter($calendarId)))
954
+                    ->andWhere($qbDeleteCalendarChanges->expr()->eq('calendartype', $qbDeleteCalendarChanges->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
955
+                    ->executeStatement();
956
+
957
+                $this->calendarSharingBackend->deleteAllShares($calendarId);
958
+
959
+                $qbDeleteCalendar = $this->db->getQueryBuilder();
960
+                $qbDeleteCalendar->delete('calendars')
961
+                    ->where($qbDeleteCalendar->expr()->eq('id', $qbDeleteCalendar->createNamedParameter($calendarId)))
962
+                    ->executeStatement();
963
+
964
+                // Only dispatch if we actually deleted anything
965
+                if ($calendarData) {
966
+                    $this->dispatcher->dispatchTyped(new CalendarDeletedEvent($calendarId, $calendarData, $shares));
967
+                }
968
+            } else {
969
+                $qbMarkCalendarDeleted = $this->db->getQueryBuilder();
970
+                $qbMarkCalendarDeleted->update('calendars')
971
+                    ->set('deleted_at', $qbMarkCalendarDeleted->createNamedParameter(time()))
972
+                    ->where($qbMarkCalendarDeleted->expr()->eq('id', $qbMarkCalendarDeleted->createNamedParameter($calendarId)))
973
+                    ->executeStatement();
974
+
975
+                $calendarData = $this->getCalendarById($calendarId);
976
+                $shares = $this->getShares($calendarId);
977
+                if ($calendarData) {
978
+                    $this->dispatcher->dispatchTyped(new CalendarMovedToTrashEvent(
979
+                        $calendarId,
980
+                        $calendarData,
981
+                        $shares
982
+                    ));
983
+                }
984
+            }
985
+        }, $this->db);
986
+    }
987
+
988
+    public function restoreCalendar(int $id): void {
989
+        $this->atomic(function () use ($id): void {
990
+            $qb = $this->db->getQueryBuilder();
991
+            $update = $qb->update('calendars')
992
+                ->set('deleted_at', $qb->createNamedParameter(null))
993
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
994
+            $update->executeStatement();
995
+
996
+            $calendarData = $this->getCalendarById($id);
997
+            $shares = $this->getShares($id);
998
+            if ($calendarData === null) {
999
+                throw new RuntimeException('Calendar data that was just written can\'t be read back. Check your database configuration.');
1000
+            }
1001
+            $this->dispatcher->dispatchTyped(new CalendarRestoredEvent(
1002
+                $id,
1003
+                $calendarData,
1004
+                $shares
1005
+            ));
1006
+        }, $this->db);
1007
+    }
1008
+
1009
+    /**
1010
+     * Returns all calendar entries as a stream of data
1011
+     *
1012
+     * @since 32.0.0
1013
+     *
1014
+     * @return Generator<array>
1015
+     */
1016
+    public function exportCalendar(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR, ?CalendarExportOptions $options = null): Generator {
1017
+        // extract options
1018
+        $rangeStart = $options?->getRangeStart();
1019
+        $rangeCount = $options?->getRangeCount();
1020
+        // construct query
1021
+        $qb = $this->db->getQueryBuilder();
1022
+        $qb->select('*')
1023
+            ->from('calendarobjects')
1024
+            ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1025
+            ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1026
+            ->andWhere($qb->expr()->isNull('deleted_at'));
1027
+        if ($rangeStart !== null) {
1028
+            $qb->andWhere($qb->expr()->gt('uid', $qb->createNamedParameter($rangeStart)));
1029
+        }
1030
+        if ($rangeCount !== null) {
1031
+            $qb->setMaxResults($rangeCount);
1032
+        }
1033
+        if ($rangeStart !== null || $rangeCount !== null) {
1034
+            $qb->orderBy('uid', 'ASC');
1035
+        }
1036
+        $rs = $qb->executeQuery();
1037
+        // iterate through results
1038
+        try {
1039
+            while (($row = $rs->fetch()) !== false) {
1040
+                yield $row;
1041
+            }
1042
+        } finally {
1043
+            $rs->closeCursor();
1044
+        }
1045
+    }
1046
+
1047
+    /**
1048
+     * Returns all calendar objects with limited metadata for a calendar
1049
+     *
1050
+     * Every item contains an array with the following keys:
1051
+     *   * id - the table row id
1052
+     *   * etag - An arbitrary string
1053
+     *   * uri - a unique key which will be used to construct the uri. This can
1054
+     *     be any arbitrary string.
1055
+     *   * calendardata - The iCalendar-compatible calendar data
1056
+     *
1057
+     * @param mixed $calendarId
1058
+     * @param int $calendarType
1059
+     * @return array
1060
+     */
1061
+    public function getLimitedCalendarObjects(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1062
+        $query = $this->db->getQueryBuilder();
1063
+        $query->select(['id','uid', 'etag', 'uri', 'calendardata'])
1064
+            ->from('calendarobjects')
1065
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1066
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1067
+            ->andWhere($query->expr()->isNull('deleted_at'));
1068
+        $stmt = $query->executeQuery();
1069
+
1070
+        $result = [];
1071
+        while (($row = $stmt->fetch()) !== false) {
1072
+            $result[$row['uid']] = [
1073
+                'id' => $row['id'],
1074
+                'etag' => $row['etag'],
1075
+                'uri' => $row['uri'],
1076
+                'calendardata' => $row['calendardata'],
1077
+            ];
1078
+        }
1079
+        $stmt->closeCursor();
1080
+
1081
+        return $result;
1082
+    }
1083
+
1084
+    /**
1085
+     * Delete all of an user's shares
1086
+     *
1087
+     * @param string $principaluri
1088
+     * @return void
1089
+     */
1090
+    public function deleteAllSharesByUser($principaluri) {
1091
+        $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
1092
+    }
1093
+
1094
+    /**
1095
+     * Returns all calendar objects within a calendar.
1096
+     *
1097
+     * Every item contains an array with the following keys:
1098
+     *   * calendardata - The iCalendar-compatible calendar data
1099
+     *   * uri - a unique key which will be used to construct the uri. This can
1100
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
1101
+     *     good idea. This is only the basename, or filename, not the full
1102
+     *     path.
1103
+     *   * lastmodified - a timestamp of the last modification time
1104
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
1105
+     *   '"abcdef"')
1106
+     *   * size - The size of the calendar objects, in bytes.
1107
+     *   * component - optional, a string containing the type of object, such
1108
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
1109
+     *     the Content-Type header.
1110
+     *
1111
+     * Note that the etag is optional, but it's highly encouraged to return for
1112
+     * speed reasons.
1113
+     *
1114
+     * The calendardata is also optional. If it's not returned
1115
+     * 'getCalendarObject' will be called later, which *is* expected to return
1116
+     * calendardata.
1117
+     *
1118
+     * If neither etag or size are specified, the calendardata will be
1119
+     * used/fetched to determine these numbers. If both are specified the
1120
+     * amount of times this is needed is reduced by a great degree.
1121
+     *
1122
+     * @param mixed $calendarId
1123
+     * @param int $calendarType
1124
+     * @return array
1125
+     */
1126
+    public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1127
+        $query = $this->db->getQueryBuilder();
1128
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
1129
+            ->from('calendarobjects')
1130
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1131
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1132
+            ->andWhere($query->expr()->isNull('deleted_at'));
1133
+        $stmt = $query->executeQuery();
1134
+
1135
+        $result = [];
1136
+        while (($row = $stmt->fetch()) !== false) {
1137
+            $result[] = [
1138
+                'id' => $row['id'],
1139
+                'uri' => $row['uri'],
1140
+                'lastmodified' => $row['lastmodified'],
1141
+                'etag' => '"' . $row['etag'] . '"',
1142
+                'calendarid' => $row['calendarid'],
1143
+                'size' => (int)$row['size'],
1144
+                'component' => strtolower($row['componenttype']),
1145
+                'classification' => (int)$row['classification']
1146
+            ];
1147
+        }
1148
+        $stmt->closeCursor();
1149
+
1150
+        return $result;
1151
+    }
1152
+
1153
+    public function getDeletedCalendarObjects(int $deletedBefore): array {
1154
+        $query = $this->db->getQueryBuilder();
1155
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.calendartype', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1156
+            ->from('calendarobjects', 'co')
1157
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1158
+            ->where($query->expr()->isNotNull('co.deleted_at'))
1159
+            ->andWhere($query->expr()->lt('co.deleted_at', $query->createNamedParameter($deletedBefore)));
1160
+        $stmt = $query->executeQuery();
1161
+
1162
+        $result = [];
1163
+        while (($row = $stmt->fetch()) !== false) {
1164
+            $result[] = [
1165
+                'id' => $row['id'],
1166
+                'uri' => $row['uri'],
1167
+                'lastmodified' => $row['lastmodified'],
1168
+                'etag' => '"' . $row['etag'] . '"',
1169
+                'calendarid' => (int)$row['calendarid'],
1170
+                'calendartype' => (int)$row['calendartype'],
1171
+                'size' => (int)$row['size'],
1172
+                'component' => strtolower($row['componenttype']),
1173
+                'classification' => (int)$row['classification'],
1174
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1175
+            ];
1176
+        }
1177
+        $stmt->closeCursor();
1178
+
1179
+        return $result;
1180
+    }
1181
+
1182
+    /**
1183
+     * Return all deleted calendar objects by the given principal that are not
1184
+     * in deleted calendars.
1185
+     *
1186
+     * @param string $principalUri
1187
+     * @return array
1188
+     * @throws Exception
1189
+     */
1190
+    public function getDeletedCalendarObjectsByPrincipal(string $principalUri): array {
1191
+        $query = $this->db->getQueryBuilder();
1192
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1193
+            ->selectAlias('c.uri', 'calendaruri')
1194
+            ->from('calendarobjects', 'co')
1195
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1196
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1197
+            ->andWhere($query->expr()->isNotNull('co.deleted_at'))
1198
+            ->andWhere($query->expr()->isNull('c.deleted_at'));
1199
+        $stmt = $query->executeQuery();
1200
+
1201
+        $result = [];
1202
+        while ($row = $stmt->fetch()) {
1203
+            $result[] = [
1204
+                'id' => $row['id'],
1205
+                'uri' => $row['uri'],
1206
+                'lastmodified' => $row['lastmodified'],
1207
+                'etag' => '"' . $row['etag'] . '"',
1208
+                'calendarid' => $row['calendarid'],
1209
+                'calendaruri' => $row['calendaruri'],
1210
+                'size' => (int)$row['size'],
1211
+                'component' => strtolower($row['componenttype']),
1212
+                'classification' => (int)$row['classification'],
1213
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1214
+            ];
1215
+        }
1216
+        $stmt->closeCursor();
1217
+
1218
+        return $result;
1219
+    }
1220
+
1221
+    /**
1222
+     * Returns information from a single calendar object, based on it's object
1223
+     * uri.
1224
+     *
1225
+     * The object uri is only the basename, or filename and not a full path.
1226
+     *
1227
+     * The returned array must have the same keys as getCalendarObjects. The
1228
+     * 'calendardata' object is required here though, while it's not required
1229
+     * for getCalendarObjects.
1230
+     *
1231
+     * This method must return null if the object did not exist.
1232
+     *
1233
+     * @param mixed $calendarId
1234
+     * @param string $objectUri
1235
+     * @param int $calendarType
1236
+     * @return array|null
1237
+     */
1238
+    public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1239
+        $key = $calendarId . '::' . $objectUri . '::' . $calendarType;
1240
+        if (isset($this->cachedObjects[$key])) {
1241
+            return $this->cachedObjects[$key];
1242
+        }
1243
+        $query = $this->db->getQueryBuilder();
1244
+        $query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1245
+            ->from('calendarobjects')
1246
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1247
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1248
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1249
+        $stmt = $query->executeQuery();
1250
+        $row = $stmt->fetch();
1251
+        $stmt->closeCursor();
1252
+
1253
+        if (!$row) {
1254
+            return null;
1255
+        }
1256
+
1257
+        $object = $this->rowToCalendarObject($row);
1258
+        $this->cachedObjects[$key] = $object;
1259
+        return $object;
1260
+    }
1261
+
1262
+    private function rowToCalendarObject(array $row): array {
1263
+        return [
1264
+            'id' => $row['id'],
1265
+            'uri' => $row['uri'],
1266
+            'uid' => $row['uid'],
1267
+            'lastmodified' => $row['lastmodified'],
1268
+            'etag' => '"' . $row['etag'] . '"',
1269
+            'calendarid' => $row['calendarid'],
1270
+            'size' => (int)$row['size'],
1271
+            'calendardata' => $this->readBlob($row['calendardata']),
1272
+            'component' => strtolower($row['componenttype']),
1273
+            'classification' => (int)$row['classification'],
1274
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1275
+        ];
1276
+    }
1277
+
1278
+    /**
1279
+     * Returns a list of calendar objects.
1280
+     *
1281
+     * This method should work identical to getCalendarObject, but instead
1282
+     * return all the calendar objects in the list as an array.
1283
+     *
1284
+     * If the backend supports this, it may allow for some speed-ups.
1285
+     *
1286
+     * @param mixed $calendarId
1287
+     * @param string[] $uris
1288
+     * @param int $calendarType
1289
+     * @return array
1290
+     */
1291
+    public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1292
+        if (empty($uris)) {
1293
+            return [];
1294
+        }
1295
+
1296
+        $chunks = array_chunk($uris, 100);
1297
+        $objects = [];
1298
+
1299
+        $query = $this->db->getQueryBuilder();
1300
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1301
+            ->from('calendarobjects')
1302
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1303
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1304
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1305
+            ->andWhere($query->expr()->isNull('deleted_at'));
1306
+
1307
+        foreach ($chunks as $uris) {
1308
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1309
+            $result = $query->executeQuery();
1310
+
1311
+            while ($row = $result->fetch()) {
1312
+                $objects[] = [
1313
+                    'id' => $row['id'],
1314
+                    'uri' => $row['uri'],
1315
+                    'lastmodified' => $row['lastmodified'],
1316
+                    'etag' => '"' . $row['etag'] . '"',
1317
+                    'calendarid' => $row['calendarid'],
1318
+                    'size' => (int)$row['size'],
1319
+                    'calendardata' => $this->readBlob($row['calendardata']),
1320
+                    'component' => strtolower($row['componenttype']),
1321
+                    'classification' => (int)$row['classification']
1322
+                ];
1323
+            }
1324
+            $result->closeCursor();
1325
+        }
1326
+
1327
+        return $objects;
1328
+    }
1329
+
1330
+    /**
1331
+     * Creates a new calendar object.
1332
+     *
1333
+     * The object uri is only the basename, or filename and not a full path.
1334
+     *
1335
+     * It is possible return an etag from this function, which will be used in
1336
+     * the response to this PUT request. Note that the ETag must be surrounded
1337
+     * by double-quotes.
1338
+     *
1339
+     * However, you should only really return this ETag if you don't mangle the
1340
+     * calendar-data. If the result of a subsequent GET to this object is not
1341
+     * the exact same as this request body, you should omit the ETag.
1342
+     *
1343
+     * @param mixed $calendarId
1344
+     * @param string $objectUri
1345
+     * @param string $calendarData
1346
+     * @param int $calendarType
1347
+     * @return string
1348
+     */
1349
+    public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1350
+        $this->cachedObjects = [];
1351
+        $extraData = $this->getDenormalizedData($calendarData);
1352
+
1353
+        return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1354
+            // Try to detect duplicates
1355
+            $qb = $this->db->getQueryBuilder();
1356
+            $qb->select($qb->func()->count('*'))
1357
+                ->from('calendarobjects')
1358
+                ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1359
+                ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($extraData['uid'])))
1360
+                ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1361
+                ->andWhere($qb->expr()->isNull('deleted_at'));
1362
+            $result = $qb->executeQuery();
1363
+            $count = (int)$result->fetchOne();
1364
+            $result->closeCursor();
1365
+
1366
+            if ($count !== 0) {
1367
+                throw new BadRequest('Calendar object with uid already exists in this calendar collection.');
1368
+            }
1369
+            // For a more specific error message we also try to explicitly look up the UID but as a deleted entry
1370
+            $qbDel = $this->db->getQueryBuilder();
1371
+            $qbDel->select('*')
1372
+                ->from('calendarobjects')
1373
+                ->where($qbDel->expr()->eq('calendarid', $qbDel->createNamedParameter($calendarId)))
1374
+                ->andWhere($qbDel->expr()->eq('uid', $qbDel->createNamedParameter($extraData['uid'])))
1375
+                ->andWhere($qbDel->expr()->eq('calendartype', $qbDel->createNamedParameter($calendarType)))
1376
+                ->andWhere($qbDel->expr()->isNotNull('deleted_at'));
1377
+            $result = $qbDel->executeQuery();
1378
+            $found = $result->fetch();
1379
+            $result->closeCursor();
1380
+            if ($found !== false) {
1381
+                // the object existed previously but has been deleted
1382
+                // remove the trashbin entry and continue as if it was a new object
1383
+                $this->deleteCalendarObject($calendarId, $found['uri']);
1384
+            }
1385
+
1386
+            $query = $this->db->getQueryBuilder();
1387
+            $query->insert('calendarobjects')
1388
+                ->values([
1389
+                    'calendarid' => $query->createNamedParameter($calendarId),
1390
+                    'uri' => $query->createNamedParameter($objectUri),
1391
+                    'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1392
+                    'lastmodified' => $query->createNamedParameter(time()),
1393
+                    'etag' => $query->createNamedParameter($extraData['etag']),
1394
+                    'size' => $query->createNamedParameter($extraData['size']),
1395
+                    'componenttype' => $query->createNamedParameter($extraData['componentType']),
1396
+                    'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1397
+                    'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1398
+                    'classification' => $query->createNamedParameter($extraData['classification']),
1399
+                    'uid' => $query->createNamedParameter($extraData['uid']),
1400
+                    'calendartype' => $query->createNamedParameter($calendarType),
1401
+                ])
1402
+                ->executeStatement();
1403
+
1404
+            $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1405
+            $this->addChanges($calendarId, [$objectUri], 1, $calendarType);
1406
+
1407
+            $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1408
+            assert($objectRow !== null);
1409
+
1410
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1411
+                $calendarRow = $this->getCalendarById($calendarId);
1412
+                $shares = $this->getShares($calendarId);
1413
+
1414
+                $this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1415
+            } elseif ($calendarType === self::CALENDAR_TYPE_SUBSCRIPTION) {
1416
+                $subscriptionRow = $this->getSubscriptionById($calendarId);
1417
+
1418
+                $this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1419
+            } elseif ($calendarType === self::CALENDAR_TYPE_FEDERATED) {
1420
+                // TODO: implement custom event for federated calendars
1421
+            }
1422
+
1423
+            return '"' . $extraData['etag'] . '"';
1424
+        }, $this->db);
1425
+    }
1426
+
1427
+    /**
1428
+     * Updates an existing calendarobject, based on it's uri.
1429
+     *
1430
+     * The object uri is only the basename, or filename and not a full path.
1431
+     *
1432
+     * It is possible return an etag from this function, which will be used in
1433
+     * the response to this PUT request. Note that the ETag must be surrounded
1434
+     * by double-quotes.
1435
+     *
1436
+     * However, you should only really return this ETag if you don't mangle the
1437
+     * calendar-data. If the result of a subsequent GET to this object is not
1438
+     * the exact same as this request body, you should omit the ETag.
1439
+     *
1440
+     * @param mixed $calendarId
1441
+     * @param string $objectUri
1442
+     * @param string $calendarData
1443
+     * @param int $calendarType
1444
+     * @return string
1445
+     */
1446
+    public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1447
+        $this->cachedObjects = [];
1448
+        $extraData = $this->getDenormalizedData($calendarData);
1449
+
1450
+        return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1451
+            $query = $this->db->getQueryBuilder();
1452
+            $query->update('calendarobjects')
1453
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1454
+                ->set('lastmodified', $query->createNamedParameter(time()))
1455
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1456
+                ->set('size', $query->createNamedParameter($extraData['size']))
1457
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1458
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1459
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1460
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1461
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1462
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1463
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1464
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1465
+                ->executeStatement();
1466
+
1467
+            $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1468
+            $this->addChanges($calendarId, [$objectUri], 2, $calendarType);
1469
+
1470
+            $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1471
+            if (is_array($objectRow)) {
1472
+                if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1473
+                    $calendarRow = $this->getCalendarById($calendarId);
1474
+                    $shares = $this->getShares($calendarId);
1475
+
1476
+                    $this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1477
+                } elseif ($calendarType === self::CALENDAR_TYPE_SUBSCRIPTION) {
1478
+                    $subscriptionRow = $this->getSubscriptionById($calendarId);
1479
+
1480
+                    $this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1481
+                } elseif ($calendarType === self::CALENDAR_TYPE_FEDERATED) {
1482
+                    // TODO: implement custom event for federated calendars
1483
+                }
1484
+            }
1485
+
1486
+            return '"' . $extraData['etag'] . '"';
1487
+        }, $this->db);
1488
+    }
1489
+
1490
+    /**
1491
+     * Moves a calendar object from calendar to calendar.
1492
+     *
1493
+     * @param string $sourcePrincipalUri
1494
+     * @param int $sourceObjectId
1495
+     * @param string $targetPrincipalUri
1496
+     * @param int $targetCalendarId
1497
+     * @param string $tragetObjectUri
1498
+     * @param int $calendarType
1499
+     * @return bool
1500
+     * @throws Exception
1501
+     */
1502
+    public function moveCalendarObject(string $sourcePrincipalUri, int $sourceObjectId, string $targetPrincipalUri, int $targetCalendarId, string $tragetObjectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR): bool {
1503
+        $this->cachedObjects = [];
1504
+        return $this->atomic(function () use ($sourcePrincipalUri, $sourceObjectId, $targetPrincipalUri, $targetCalendarId, $tragetObjectUri, $calendarType) {
1505
+            $object = $this->getCalendarObjectById($sourcePrincipalUri, $sourceObjectId);
1506
+            if (empty($object)) {
1507
+                return false;
1508
+            }
1509
+
1510
+            $sourceCalendarId = $object['calendarid'];
1511
+            $sourceObjectUri = $object['uri'];
1512
+
1513
+            $query = $this->db->getQueryBuilder();
1514
+            $query->update('calendarobjects')
1515
+                ->set('calendarid', $query->createNamedParameter($targetCalendarId, IQueryBuilder::PARAM_INT))
1516
+                ->set('uri', $query->createNamedParameter($tragetObjectUri, IQueryBuilder::PARAM_STR))
1517
+                ->where($query->expr()->eq('id', $query->createNamedParameter($sourceObjectId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
1518
+                ->executeStatement();
1519
+
1520
+            $this->purgeProperties($sourceCalendarId, $sourceObjectId);
1521
+            $this->updateProperties($targetCalendarId, $tragetObjectUri, $object['calendardata'], $calendarType);
1522
+
1523
+            $this->addChanges($sourceCalendarId, [$sourceObjectUri], 3, $calendarType);
1524
+            $this->addChanges($targetCalendarId, [$tragetObjectUri], 1, $calendarType);
1525
+
1526
+            $object = $this->getCalendarObjectById($targetPrincipalUri, $sourceObjectId);
1527
+            // Calendar Object wasn't found - possibly because it was deleted in the meantime by a different client
1528
+            if (empty($object)) {
1529
+                return false;
1530
+            }
1531
+
1532
+            $targetCalendarRow = $this->getCalendarById($targetCalendarId);
1533
+            // the calendar this event is being moved to does not exist any longer
1534
+            if (empty($targetCalendarRow)) {
1535
+                return false;
1536
+            }
1537
+
1538
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1539
+                $sourceShares = $this->getShares($sourceCalendarId);
1540
+                $targetShares = $this->getShares($targetCalendarId);
1541
+                $sourceCalendarRow = $this->getCalendarById($sourceCalendarId);
1542
+                $this->dispatcher->dispatchTyped(new CalendarObjectMovedEvent($sourceCalendarId, $sourceCalendarRow, $targetCalendarId, $targetCalendarRow, $sourceShares, $targetShares, $object));
1543
+            }
1544
+            return true;
1545
+        }, $this->db);
1546
+    }
1547
+
1548
+    /**
1549
+     * Deletes an existing calendar object.
1550
+     *
1551
+     * The object uri is only the basename, or filename and not a full path.
1552
+     *
1553
+     * @param mixed $calendarId
1554
+     * @param string $objectUri
1555
+     * @param int $calendarType
1556
+     * @param bool $forceDeletePermanently
1557
+     * @return void
1558
+     */
1559
+    public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
1560
+        $this->cachedObjects = [];
1561
+        $this->atomic(function () use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently): void {
1562
+            $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1563
+
1564
+            if ($data === null) {
1565
+                // Nothing to delete
1566
+                return;
1567
+            }
1568
+
1569
+            if ($forceDeletePermanently || $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0') {
1570
+                $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1571
+                $stmt->execute([$calendarId, $objectUri, $calendarType]);
1572
+
1573
+                $this->purgeProperties($calendarId, $data['id']);
1574
+
1575
+                $this->purgeObjectInvitations($data['uid']);
1576
+
1577
+                if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1578
+                    $calendarRow = $this->getCalendarById($calendarId);
1579
+                    $shares = $this->getShares($calendarId);
1580
+
1581
+                    $this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent($calendarId, $calendarRow, $shares, $data));
1582
+                } else {
1583
+                    $subscriptionRow = $this->getSubscriptionById($calendarId);
1584
+
1585
+                    $this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent($calendarId, $subscriptionRow, [], $data));
1586
+                }
1587
+            } else {
1588
+                $pathInfo = pathinfo($data['uri']);
1589
+                if (!empty($pathInfo['extension'])) {
1590
+                    // Append a suffix to "free" the old URI for recreation
1591
+                    $newUri = sprintf(
1592
+                        '%s-deleted.%s',
1593
+                        $pathInfo['filename'],
1594
+                        $pathInfo['extension']
1595
+                    );
1596
+                } else {
1597
+                    $newUri = sprintf(
1598
+                        '%s-deleted',
1599
+                        $pathInfo['filename']
1600
+                    );
1601
+                }
1602
+
1603
+                // Try to detect conflicts before the DB does
1604
+                // As unlikely as it seems, this can happen when the user imports, then deletes, imports and deletes again
1605
+                $newObject = $this->getCalendarObject($calendarId, $newUri, $calendarType);
1606
+                if ($newObject !== null) {
1607
+                    throw new Forbidden("A calendar object with URI $newUri already exists in calendar $calendarId, therefore this object can't be moved into the trashbin");
1608
+                }
1609
+
1610
+                $qb = $this->db->getQueryBuilder();
1611
+                $markObjectDeletedQuery = $qb->update('calendarobjects')
1612
+                    ->set('deleted_at', $qb->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
1613
+                    ->set('uri', $qb->createNamedParameter($newUri))
1614
+                    ->where(
1615
+                        $qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
1616
+                        $qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
1617
+                        $qb->expr()->eq('uri', $qb->createNamedParameter($objectUri))
1618
+                    );
1619
+                $markObjectDeletedQuery->executeStatement();
1620
+
1621
+                $calendarData = $this->getCalendarById($calendarId);
1622
+                if ($calendarData !== null) {
1623
+                    $this->dispatcher->dispatchTyped(
1624
+                        new CalendarObjectMovedToTrashEvent(
1625
+                            $calendarId,
1626
+                            $calendarData,
1627
+                            $this->getShares($calendarId),
1628
+                            $data
1629
+                        )
1630
+                    );
1631
+                }
1632
+            }
1633
+
1634
+            $this->addChanges($calendarId, [$objectUri], 3, $calendarType);
1635
+        }, $this->db);
1636
+    }
1637
+
1638
+    /**
1639
+     * @param mixed $objectData
1640
+     *
1641
+     * @throws Forbidden
1642
+     */
1643
+    public function restoreCalendarObject(array $objectData): void {
1644
+        $this->cachedObjects = [];
1645
+        $this->atomic(function () use ($objectData): void {
1646
+            $id = (int)$objectData['id'];
1647
+            $restoreUri = str_replace('-deleted.ics', '.ics', $objectData['uri']);
1648
+            $targetObject = $this->getCalendarObject(
1649
+                $objectData['calendarid'],
1650
+                $restoreUri
1651
+            );
1652
+            if ($targetObject !== null) {
1653
+                throw new Forbidden("Can not restore calendar $id because a calendar object with the URI $restoreUri already exists");
1654
+            }
1655
+
1656
+            $qb = $this->db->getQueryBuilder();
1657
+            $update = $qb->update('calendarobjects')
1658
+                ->set('uri', $qb->createNamedParameter($restoreUri))
1659
+                ->set('deleted_at', $qb->createNamedParameter(null))
1660
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1661
+            $update->executeStatement();
1662
+
1663
+            // Make sure this change is tracked in the changes table
1664
+            $qb2 = $this->db->getQueryBuilder();
1665
+            $selectObject = $qb2->select('calendardata', 'uri', 'calendarid', 'calendartype')
1666
+                ->selectAlias('componenttype', 'component')
1667
+                ->from('calendarobjects')
1668
+                ->where($qb2->expr()->eq('id', $qb2->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1669
+            $result = $selectObject->executeQuery();
1670
+            $row = $result->fetch();
1671
+            $result->closeCursor();
1672
+            if ($row === false) {
1673
+                // Welp, this should possibly not have happened, but let's ignore
1674
+                return;
1675
+            }
1676
+            $this->addChanges($row['calendarid'], [$row['uri']], 1, (int)$row['calendartype']);
1677
+
1678
+            $calendarRow = $this->getCalendarById((int)$row['calendarid']);
1679
+            if ($calendarRow === null) {
1680
+                throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
1681
+            }
1682
+            $this->dispatcher->dispatchTyped(
1683
+                new CalendarObjectRestoredEvent(
1684
+                    (int)$objectData['calendarid'],
1685
+                    $calendarRow,
1686
+                    $this->getShares((int)$row['calendarid']),
1687
+                    $row
1688
+                )
1689
+            );
1690
+        }, $this->db);
1691
+    }
1692
+
1693
+    /**
1694
+     * Performs a calendar-query on the contents of this calendar.
1695
+     *
1696
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1697
+     * calendar-query it is possible for a client to request a specific set of
1698
+     * object, based on contents of iCalendar properties, date-ranges and
1699
+     * iCalendar component types (VTODO, VEVENT).
1700
+     *
1701
+     * This method should just return a list of (relative) urls that match this
1702
+     * query.
1703
+     *
1704
+     * The list of filters are specified as an array. The exact array is
1705
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1706
+     *
1707
+     * Note that it is extremely likely that getCalendarObject for every path
1708
+     * returned from this method will be called almost immediately after. You
1709
+     * may want to anticipate this to speed up these requests.
1710
+     *
1711
+     * This method provides a default implementation, which parses *all* the
1712
+     * iCalendar objects in the specified calendar.
1713
+     *
1714
+     * This default may well be good enough for personal use, and calendars
1715
+     * that aren't very large. But if you anticipate high usage, big calendars
1716
+     * or high loads, you are strongly advised to optimize certain paths.
1717
+     *
1718
+     * The best way to do so is override this method and to optimize
1719
+     * specifically for 'common filters'.
1720
+     *
1721
+     * Requests that are extremely common are:
1722
+     *   * requests for just VEVENTS
1723
+     *   * requests for just VTODO
1724
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1725
+     *
1726
+     * ..and combinations of these requests. It may not be worth it to try to
1727
+     * handle every possible situation and just rely on the (relatively
1728
+     * easy to use) CalendarQueryValidator to handle the rest.
1729
+     *
1730
+     * Note that especially time-range-filters may be difficult to parse. A
1731
+     * time-range filter specified on a VEVENT must for instance also handle
1732
+     * recurrence rules correctly.
1733
+     * A good example of how to interpret all these filters can also simply
1734
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1735
+     * as possible, so it gives you a good idea on what type of stuff you need
1736
+     * to think of.
1737
+     *
1738
+     * @param mixed $calendarId
1739
+     * @param array $filters
1740
+     * @param int $calendarType
1741
+     * @return array
1742
+     */
1743
+    public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1744
+        $componentType = null;
1745
+        $requirePostFilter = true;
1746
+        $timeRange = null;
1747
+
1748
+        // if no filters were specified, we don't need to filter after a query
1749
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1750
+            $requirePostFilter = false;
1751
+        }
1752
+
1753
+        // Figuring out if there's a component filter
1754
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1755
+            $componentType = $filters['comp-filters'][0]['name'];
1756
+
1757
+            // Checking if we need post-filters
1758
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1759
+                $requirePostFilter = false;
1760
+            }
1761
+            // There was a time-range filter
1762
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
1763
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1764
+
1765
+                // If start time OR the end time is not specified, we can do a
1766
+                // 100% accurate mysql query.
1767
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1768
+                    $requirePostFilter = false;
1769
+                }
1770
+            }
1771
+        }
1772
+        $query = $this->db->getQueryBuilder();
1773
+        $query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1774
+            ->from('calendarobjects')
1775
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1776
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1777
+            ->andWhere($query->expr()->isNull('deleted_at'));
1778
+
1779
+        if ($componentType) {
1780
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1781
+        }
1782
+
1783
+        if ($timeRange && $timeRange['start']) {
1784
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1785
+        }
1786
+        if ($timeRange && $timeRange['end']) {
1787
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1788
+        }
1789
+
1790
+        $stmt = $query->executeQuery();
1791
+
1792
+        $result = [];
1793
+        while ($row = $stmt->fetch()) {
1794
+            // if we leave it as a blob we can't read it both from the post filter and the rowToCalendarObject
1795
+            if (isset($row['calendardata'])) {
1796
+                $row['calendardata'] = $this->readBlob($row['calendardata']);
1797
+            }
1798
+
1799
+            if ($requirePostFilter) {
1800
+                // validateFilterForObject will parse the calendar data
1801
+                // catch parsing errors
1802
+                try {
1803
+                    $matches = $this->validateFilterForObject($row, $filters);
1804
+                } catch (ParseException $ex) {
1805
+                    $this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1806
+                        'app' => 'dav',
1807
+                        'exception' => $ex,
1808
+                    ]);
1809
+                    continue;
1810
+                } catch (InvalidDataException $ex) {
1811
+                    $this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1812
+                        'app' => 'dav',
1813
+                        'exception' => $ex,
1814
+                    ]);
1815
+                    continue;
1816
+                } catch (MaxInstancesExceededException $ex) {
1817
+                    $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'], [
1818
+                        'app' => 'dav',
1819
+                        'exception' => $ex,
1820
+                    ]);
1821
+                    continue;
1822
+                }
1823
+
1824
+                if (!$matches) {
1825
+                    continue;
1826
+                }
1827
+            }
1828
+            $result[] = $row['uri'];
1829
+            $key = $calendarId . '::' . $row['uri'] . '::' . $calendarType;
1830
+            $this->cachedObjects[$key] = $this->rowToCalendarObject($row);
1831
+        }
1832
+
1833
+        return $result;
1834
+    }
1835
+
1836
+    /**
1837
+     * custom Nextcloud search extension for CalDAV
1838
+     *
1839
+     * TODO - this should optionally cover cached calendar objects as well
1840
+     *
1841
+     * @param string $principalUri
1842
+     * @param array $filters
1843
+     * @param integer|null $limit
1844
+     * @param integer|null $offset
1845
+     * @return array
1846
+     */
1847
+    public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1848
+        return $this->atomic(function () use ($principalUri, $filters, $limit, $offset) {
1849
+            $calendars = $this->getCalendarsForUser($principalUri);
1850
+            $ownCalendars = [];
1851
+            $sharedCalendars = [];
1852
+
1853
+            $uriMapper = [];
1854
+
1855
+            foreach ($calendars as $calendar) {
1856
+                if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1857
+                    $ownCalendars[] = $calendar['id'];
1858
+                } else {
1859
+                    $sharedCalendars[] = $calendar['id'];
1860
+                }
1861
+                $uriMapper[$calendar['id']] = $calendar['uri'];
1862
+            }
1863
+            if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1864
+                return [];
1865
+            }
1866
+
1867
+            $query = $this->db->getQueryBuilder();
1868
+            // Calendar id expressions
1869
+            $calendarExpressions = [];
1870
+            foreach ($ownCalendars as $id) {
1871
+                $calendarExpressions[] = $query->expr()->andX(
1872
+                    $query->expr()->eq('c.calendarid',
1873
+                        $query->createNamedParameter($id)),
1874
+                    $query->expr()->eq('c.calendartype',
1875
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1876
+            }
1877
+            foreach ($sharedCalendars as $id) {
1878
+                $calendarExpressions[] = $query->expr()->andX(
1879
+                    $query->expr()->eq('c.calendarid',
1880
+                        $query->createNamedParameter($id)),
1881
+                    $query->expr()->eq('c.classification',
1882
+                        $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1883
+                    $query->expr()->eq('c.calendartype',
1884
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1885
+            }
1886
+
1887
+            if (count($calendarExpressions) === 1) {
1888
+                $calExpr = $calendarExpressions[0];
1889
+            } else {
1890
+                $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1891
+            }
1892
+
1893
+            // Component expressions
1894
+            $compExpressions = [];
1895
+            foreach ($filters['comps'] as $comp) {
1896
+                $compExpressions[] = $query->expr()
1897
+                    ->eq('c.componenttype', $query->createNamedParameter($comp));
1898
+            }
1899
+
1900
+            if (count($compExpressions) === 1) {
1901
+                $compExpr = $compExpressions[0];
1902
+            } else {
1903
+                $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1904
+            }
1905
+
1906
+            if (!isset($filters['props'])) {
1907
+                $filters['props'] = [];
1908
+            }
1909
+            if (!isset($filters['params'])) {
1910
+                $filters['params'] = [];
1911
+            }
1912
+
1913
+            $propParamExpressions = [];
1914
+            foreach ($filters['props'] as $prop) {
1915
+                $propParamExpressions[] = $query->expr()->andX(
1916
+                    $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1917
+                    $query->expr()->isNull('i.parameter')
1918
+                );
1919
+            }
1920
+            foreach ($filters['params'] as $param) {
1921
+                $propParamExpressions[] = $query->expr()->andX(
1922
+                    $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1923
+                    $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1924
+                );
1925
+            }
1926
+
1927
+            if (count($propParamExpressions) === 1) {
1928
+                $propParamExpr = $propParamExpressions[0];
1929
+            } else {
1930
+                $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1931
+            }
1932
+
1933
+            $query->select(['c.calendarid', 'c.uri'])
1934
+                ->from($this->dbObjectPropertiesTable, 'i')
1935
+                ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1936
+                ->where($calExpr)
1937
+                ->andWhere($compExpr)
1938
+                ->andWhere($propParamExpr)
1939
+                ->andWhere($query->expr()->iLike('i.value',
1940
+                    $query->createNamedParameter('%' . $this->db->escapeLikeParameter($filters['search-term']) . '%')))
1941
+                ->andWhere($query->expr()->isNull('deleted_at'));
1942
+
1943
+            if ($offset) {
1944
+                $query->setFirstResult($offset);
1945
+            }
1946
+            if ($limit) {
1947
+                $query->setMaxResults($limit);
1948
+            }
1949
+
1950
+            $stmt = $query->executeQuery();
1951
+
1952
+            $result = [];
1953
+            while ($row = $stmt->fetch()) {
1954
+                $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1955
+                if (!in_array($path, $result)) {
1956
+                    $result[] = $path;
1957
+                }
1958
+            }
1959
+
1960
+            return $result;
1961
+        }, $this->db);
1962
+    }
1963
+
1964
+    /**
1965
+     * used for Nextcloud's calendar API
1966
+     *
1967
+     * @param array $calendarInfo
1968
+     * @param string $pattern
1969
+     * @param array $searchProperties
1970
+     * @param array $options
1971
+     * @param integer|null $limit
1972
+     * @param integer|null $offset
1973
+     *
1974
+     * @return array
1975
+     */
1976
+    public function search(
1977
+        array $calendarInfo,
1978
+        $pattern,
1979
+        array $searchProperties,
1980
+        array $options,
1981
+        $limit,
1982
+        $offset,
1983
+    ) {
1984
+        $outerQuery = $this->db->getQueryBuilder();
1985
+        $innerQuery = $this->db->getQueryBuilder();
1986
+
1987
+        if (isset($calendarInfo['source'])) {
1988
+            $calendarType = self::CALENDAR_TYPE_SUBSCRIPTION;
1989
+        } elseif (isset($calendarInfo['federated'])) {
1990
+            $calendarType = self::CALENDAR_TYPE_FEDERATED;
1991
+        } else {
1992
+            $calendarType = self::CALENDAR_TYPE_CALENDAR;
1993
+        }
1994
+
1995
+        $innerQuery->selectDistinct('op.objectid')
1996
+            ->from($this->dbObjectPropertiesTable, 'op')
1997
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
1998
+                $outerQuery->createNamedParameter($calendarInfo['id'])))
1999
+            ->andWhere($innerQuery->expr()->eq('op.calendartype',
2000
+                $outerQuery->createNamedParameter($calendarType)));
2001
+
2002
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
2003
+            ->from('calendarobjects', 'c')
2004
+            ->where($outerQuery->expr()->isNull('deleted_at'));
2005
+
2006
+        // only return public items for shared calendars for now
2007
+        if (isset($calendarInfo['{http://owncloud.org/ns}owner-principal']) === false || $calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
2008
+            $outerQuery->andWhere($outerQuery->expr()->eq('c.classification',
2009
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2010
+        }
2011
+
2012
+        if (!empty($searchProperties)) {
2013
+            $or = [];
2014
+            foreach ($searchProperties as $searchProperty) {
2015
+                $or[] = $innerQuery->expr()->eq('op.name',
2016
+                    $outerQuery->createNamedParameter($searchProperty));
2017
+            }
2018
+            $innerQuery->andWhere($innerQuery->expr()->orX(...$or));
2019
+        }
2020
+
2021
+        if ($pattern !== '') {
2022
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
2023
+                $outerQuery->createNamedParameter('%'
2024
+                    . $this->db->escapeLikeParameter($pattern) . '%')));
2025
+        }
2026
+
2027
+        $start = null;
2028
+        $end = null;
2029
+
2030
+        $hasLimit = is_int($limit);
2031
+        $hasTimeRange = false;
2032
+
2033
+        if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2034
+            /** @var DateTimeInterface $start */
2035
+            $start = $options['timerange']['start'];
2036
+            $outerQuery->andWhere(
2037
+                $outerQuery->expr()->gt(
2038
+                    'lastoccurence',
2039
+                    $outerQuery->createNamedParameter($start->getTimestamp())
2040
+                )
2041
+            );
2042
+            $hasTimeRange = true;
2043
+        }
2044
+
2045
+        if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2046
+            /** @var DateTimeInterface $end */
2047
+            $end = $options['timerange']['end'];
2048
+            $outerQuery->andWhere(
2049
+                $outerQuery->expr()->lt(
2050
+                    'firstoccurence',
2051
+                    $outerQuery->createNamedParameter($end->getTimestamp())
2052
+                )
2053
+            );
2054
+            $hasTimeRange = true;
2055
+        }
2056
+
2057
+        if (isset($options['uid'])) {
2058
+            $outerQuery->andWhere($outerQuery->expr()->eq('uid', $outerQuery->createNamedParameter($options['uid'])));
2059
+        }
2060
+
2061
+        if (!empty($options['types'])) {
2062
+            $or = [];
2063
+            foreach ($options['types'] as $type) {
2064
+                $or[] = $outerQuery->expr()->eq('componenttype',
2065
+                    $outerQuery->createNamedParameter($type));
2066
+            }
2067
+            $outerQuery->andWhere($outerQuery->expr()->orX(...$or));
2068
+        }
2069
+
2070
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id', $outerQuery->createFunction($innerQuery->getSQL())));
2071
+
2072
+        // Without explicit order by its undefined in which order the SQL server returns the events.
2073
+        // For the pagination with hasLimit and hasTimeRange, a stable ordering is helpful.
2074
+        $outerQuery->addOrderBy('id');
2075
+
2076
+        $offset = (int)$offset;
2077
+        $outerQuery->setFirstResult($offset);
2078
+
2079
+        $calendarObjects = [];
2080
+
2081
+        if ($hasLimit && $hasTimeRange) {
2082
+            /**
2083
+             * Event recurrences are evaluated at runtime because the database only knows the first and last occurrence.
2084
+             *
2085
+             * Given, a user created 8 events with a yearly reoccurrence and two for events tomorrow.
2086
+             * The upcoming event widget asks the CalDAV backend for 7 events within the next 14 days.
2087
+             *
2088
+             * If limit 7 is applied to the SQL query, we find the 7 events with a yearly reoccurrence
2089
+             * and discard the events after evaluating the reoccurrence rules because they are not due within
2090
+             * the next 14 days and end up with an empty result even if there are two events to show.
2091
+             *
2092
+             * The workaround for search requests with a limit and time range is asking for more row than requested
2093
+             * and retrying if we have not reached the limit.
2094
+             *
2095
+             * 25 rows and 3 retries is entirely arbitrary.
2096
+             */
2097
+            $maxResults = (int)max($limit, 25);
2098
+            $outerQuery->setMaxResults($maxResults);
2099
+
2100
+            for ($attempt = $objectsCount = 0; $attempt < 3 && $objectsCount < $limit; $attempt++) {
2101
+                $objectsCount = array_push($calendarObjects, ...$this->searchCalendarObjects($outerQuery, $start, $end));
2102
+                $outerQuery->setFirstResult($offset += $maxResults);
2103
+            }
2104
+
2105
+            $calendarObjects = array_slice($calendarObjects, 0, $limit, false);
2106
+        } else {
2107
+            $outerQuery->setMaxResults($limit);
2108
+            $calendarObjects = $this->searchCalendarObjects($outerQuery, $start, $end);
2109
+        }
2110
+
2111
+        $calendarObjects = array_map(function ($o) use ($options) {
2112
+            $calendarData = Reader::read($o['calendardata']);
2113
+
2114
+            // Expand recurrences if an explicit time range is requested
2115
+            if ($calendarData instanceof VCalendar
2116
+                && isset($options['timerange']['start'], $options['timerange']['end'])) {
2117
+                $calendarData = $calendarData->expand(
2118
+                    $options['timerange']['start'],
2119
+                    $options['timerange']['end'],
2120
+                );
2121
+            }
2122
+
2123
+            $comps = $calendarData->getComponents();
2124
+            $objects = [];
2125
+            $timezones = [];
2126
+            foreach ($comps as $comp) {
2127
+                if ($comp instanceof VTimeZone) {
2128
+                    $timezones[] = $comp;
2129
+                } else {
2130
+                    $objects[] = $comp;
2131
+                }
2132
+            }
2133
+
2134
+            return [
2135
+                'id' => $o['id'],
2136
+                'type' => $o['componenttype'],
2137
+                'uid' => $o['uid'],
2138
+                'uri' => $o['uri'],
2139
+                'objects' => array_map(function ($c) {
2140
+                    return $this->transformSearchData($c);
2141
+                }, $objects),
2142
+                'timezones' => array_map(function ($c) {
2143
+                    return $this->transformSearchData($c);
2144
+                }, $timezones),
2145
+            ];
2146
+        }, $calendarObjects);
2147
+
2148
+        usort($calendarObjects, function (array $a, array $b) {
2149
+            /** @var DateTimeImmutable $startA */
2150
+            $startA = $a['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2151
+            /** @var DateTimeImmutable $startB */
2152
+            $startB = $b['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2153
+
2154
+            return $startA->getTimestamp() <=> $startB->getTimestamp();
2155
+        });
2156
+
2157
+        return $calendarObjects;
2158
+    }
2159
+
2160
+    private function searchCalendarObjects(IQueryBuilder $query, ?DateTimeInterface $start, ?DateTimeInterface $end): array {
2161
+        $calendarObjects = [];
2162
+        $filterByTimeRange = ($start instanceof DateTimeInterface) || ($end instanceof DateTimeInterface);
2163
+
2164
+        $result = $query->executeQuery();
2165
+
2166
+        while (($row = $result->fetch()) !== false) {
2167
+            if ($filterByTimeRange === false) {
2168
+                // No filter required
2169
+                $calendarObjects[] = $row;
2170
+                continue;
2171
+            }
2172
+
2173
+            try {
2174
+                $isValid = $this->validateFilterForObject($row, [
2175
+                    'name' => 'VCALENDAR',
2176
+                    'comp-filters' => [
2177
+                        [
2178
+                            'name' => 'VEVENT',
2179
+                            'comp-filters' => [],
2180
+                            'prop-filters' => [],
2181
+                            'is-not-defined' => false,
2182
+                            'time-range' => [
2183
+                                'start' => $start,
2184
+                                'end' => $end,
2185
+                            ],
2186
+                        ],
2187
+                    ],
2188
+                    'prop-filters' => [],
2189
+                    'is-not-defined' => false,
2190
+                    'time-range' => null,
2191
+                ]);
2192
+            } catch (MaxInstancesExceededException $ex) {
2193
+                $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'], [
2194
+                    'app' => 'dav',
2195
+                    'exception' => $ex,
2196
+                ]);
2197
+                continue;
2198
+            }
2199
+
2200
+            if (is_resource($row['calendardata'])) {
2201
+                // Put the stream back to the beginning so it can be read another time
2202
+                rewind($row['calendardata']);
2203
+            }
2204
+
2205
+            if ($isValid) {
2206
+                $calendarObjects[] = $row;
2207
+            }
2208
+        }
2209
+
2210
+        $result->closeCursor();
2211
+
2212
+        return $calendarObjects;
2213
+    }
2214
+
2215
+    /**
2216
+     * @param Component $comp
2217
+     * @return array
2218
+     */
2219
+    private function transformSearchData(Component $comp) {
2220
+        $data = [];
2221
+        /** @var Component[] $subComponents */
2222
+        $subComponents = $comp->getComponents();
2223
+        /** @var Property[] $properties */
2224
+        $properties = array_filter($comp->children(), function ($c) {
2225
+            return $c instanceof Property;
2226
+        });
2227
+        $validationRules = $comp->getValidationRules();
2228
+
2229
+        foreach ($subComponents as $subComponent) {
2230
+            $name = $subComponent->name;
2231
+            if (!isset($data[$name])) {
2232
+                $data[$name] = [];
2233
+            }
2234
+            $data[$name][] = $this->transformSearchData($subComponent);
2235
+        }
2236
+
2237
+        foreach ($properties as $property) {
2238
+            $name = $property->name;
2239
+            if (!isset($validationRules[$name])) {
2240
+                $validationRules[$name] = '*';
2241
+            }
2242
+
2243
+            $rule = $validationRules[$property->name];
2244
+            if ($rule === '+' || $rule === '*') { // multiple
2245
+                if (!isset($data[$name])) {
2246
+                    $data[$name] = [];
2247
+                }
2248
+
2249
+                $data[$name][] = $this->transformSearchProperty($property);
2250
+            } else { // once
2251
+                $data[$name] = $this->transformSearchProperty($property);
2252
+            }
2253
+        }
2254
+
2255
+        return $data;
2256
+    }
2257
+
2258
+    /**
2259
+     * @param Property $prop
2260
+     * @return array
2261
+     */
2262
+    private function transformSearchProperty(Property $prop) {
2263
+        // No need to check Date, as it extends DateTime
2264
+        if ($prop instanceof Property\ICalendar\DateTime) {
2265
+            $value = $prop->getDateTime();
2266
+        } else {
2267
+            $value = $prop->getValue();
2268
+        }
2269
+
2270
+        return [
2271
+            $value,
2272
+            $prop->parameters()
2273
+        ];
2274
+    }
2275
+
2276
+    /**
2277
+     * @param string $principalUri
2278
+     * @param string $pattern
2279
+     * @param array $componentTypes
2280
+     * @param array $searchProperties
2281
+     * @param array $searchParameters
2282
+     * @param array $options
2283
+     * @return array
2284
+     */
2285
+    public function searchPrincipalUri(string $principalUri,
2286
+        string $pattern,
2287
+        array $componentTypes,
2288
+        array $searchProperties,
2289
+        array $searchParameters,
2290
+        array $options = [],
2291
+    ): array {
2292
+        return $this->atomic(function () use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
2293
+            $escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
2294
+
2295
+            $calendarObjectIdQuery = $this->db->getQueryBuilder();
2296
+            $calendarOr = [];
2297
+            $searchOr = [];
2298
+
2299
+            // Fetch calendars and subscription
2300
+            $calendars = $this->getCalendarsForUser($principalUri);
2301
+            $subscriptions = $this->getSubscriptionsForUser($principalUri);
2302
+            foreach ($calendars as $calendar) {
2303
+                $calendarAnd = $calendarObjectIdQuery->expr()->andX(
2304
+                    $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])),
2305
+                    $calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)),
2306
+                );
2307
+
2308
+                // If it's shared, limit search to public events
2309
+                if (isset($calendar['{http://owncloud.org/ns}owner-principal'])
2310
+                    && $calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
2311
+                    $calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2312
+                }
2313
+
2314
+                $calendarOr[] = $calendarAnd;
2315
+            }
2316
+            foreach ($subscriptions as $subscription) {
2317
+                $subscriptionAnd = $calendarObjectIdQuery->expr()->andX(
2318
+                    $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])),
2319
+                    $calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)),
2320
+                );
2321
+
2322
+                // If it's shared, limit search to public events
2323
+                if (isset($subscription['{http://owncloud.org/ns}owner-principal'])
2324
+                    && $subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
2325
+                    $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2326
+                }
2327
+
2328
+                $calendarOr[] = $subscriptionAnd;
2329
+            }
2330
+
2331
+            foreach ($searchProperties as $property) {
2332
+                $propertyAnd = $calendarObjectIdQuery->expr()->andX(
2333
+                    $calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2334
+                    $calendarObjectIdQuery->expr()->isNull('cob.parameter'),
2335
+                );
2336
+
2337
+                $searchOr[] = $propertyAnd;
2338
+            }
2339
+            foreach ($searchParameters as $property => $parameter) {
2340
+                $parameterAnd = $calendarObjectIdQuery->expr()->andX(
2341
+                    $calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2342
+                    $calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)),
2343
+                );
2344
+
2345
+                $searchOr[] = $parameterAnd;
2346
+            }
2347
+
2348
+            if (empty($calendarOr)) {
2349
+                return [];
2350
+            }
2351
+            if (empty($searchOr)) {
2352
+                return [];
2353
+            }
2354
+
2355
+            $calendarObjectIdQuery->selectDistinct('cob.objectid')
2356
+                ->from($this->dbObjectPropertiesTable, 'cob')
2357
+                ->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
2358
+                ->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
2359
+                ->andWhere($calendarObjectIdQuery->expr()->orX(...$calendarOr))
2360
+                ->andWhere($calendarObjectIdQuery->expr()->orX(...$searchOr))
2361
+                ->andWhere($calendarObjectIdQuery->expr()->isNull('deleted_at'));
2362
+
2363
+            if ($pattern !== '') {
2364
+                if (!$escapePattern) {
2365
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
2366
+                } else {
2367
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
2368
+                }
2369
+            }
2370
+
2371
+            if (isset($options['limit'])) {
2372
+                $calendarObjectIdQuery->setMaxResults($options['limit']);
2373
+            }
2374
+            if (isset($options['offset'])) {
2375
+                $calendarObjectIdQuery->setFirstResult($options['offset']);
2376
+            }
2377
+            if (isset($options['timerange'])) {
2378
+                if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2379
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->gt(
2380
+                        'lastoccurence',
2381
+                        $calendarObjectIdQuery->createNamedParameter($options['timerange']['start']->getTimeStamp()),
2382
+                    ));
2383
+                }
2384
+                if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2385
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->lt(
2386
+                        'firstoccurence',
2387
+                        $calendarObjectIdQuery->createNamedParameter($options['timerange']['end']->getTimeStamp()),
2388
+                    ));
2389
+                }
2390
+            }
2391
+
2392
+            $result = $calendarObjectIdQuery->executeQuery();
2393
+            $matches = [];
2394
+            while (($row = $result->fetch()) !== false) {
2395
+                $matches[] = (int)$row['objectid'];
2396
+            }
2397
+            $result->closeCursor();
2398
+
2399
+            $query = $this->db->getQueryBuilder();
2400
+            $query->select('calendardata', 'uri', 'calendarid', 'calendartype')
2401
+                ->from('calendarobjects')
2402
+                ->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
2403
+
2404
+            $result = $query->executeQuery();
2405
+            $calendarObjects = [];
2406
+            while (($array = $result->fetch()) !== false) {
2407
+                $array['calendarid'] = (int)$array['calendarid'];
2408
+                $array['calendartype'] = (int)$array['calendartype'];
2409
+                $array['calendardata'] = $this->readBlob($array['calendardata']);
2410
+
2411
+                $calendarObjects[] = $array;
2412
+            }
2413
+            $result->closeCursor();
2414
+            return $calendarObjects;
2415
+        }, $this->db);
2416
+    }
2417
+
2418
+    /**
2419
+     * Searches through all of a users calendars and calendar objects to find
2420
+     * an object with a specific UID.
2421
+     *
2422
+     * This method should return the path to this object, relative to the
2423
+     * calendar home, so this path usually only contains two parts:
2424
+     *
2425
+     * calendarpath/objectpath.ics
2426
+     *
2427
+     * If the uid is not found, return null.
2428
+     *
2429
+     * This method should only consider * objects that the principal owns, so
2430
+     * any calendars owned by other principals that also appear in this
2431
+     * collection should be ignored.
2432
+     *
2433
+     * @param string $principalUri
2434
+     * @param string $uid
2435
+     * @return string|null
2436
+     */
2437
+    public function getCalendarObjectByUID($principalUri, $uid, $calendarUri = null) {
2438
+        $query = $this->db->getQueryBuilder();
2439
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
2440
+            ->from('calendarobjects', 'co')
2441
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
2442
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2443
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
2444
+            ->andWhere($query->expr()->isNull('co.deleted_at'));
2445
+
2446
+        if ($calendarUri !== null) {
2447
+            $query->andWhere($query->expr()->eq('c.uri', $query->createNamedParameter($calendarUri)));
2448
+        }
2449
+
2450
+        $stmt = $query->executeQuery();
2451
+        $row = $stmt->fetch();
2452
+        $stmt->closeCursor();
2453
+        if ($row) {
2454
+            return $row['calendaruri'] . '/' . $row['objecturi'];
2455
+        }
2456
+
2457
+        return null;
2458
+    }
2459
+
2460
+    public function getCalendarObjectById(string $principalUri, int $id): ?array {
2461
+        $query = $this->db->getQueryBuilder();
2462
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.calendardata', 'co.componenttype', 'co.classification', 'co.deleted_at'])
2463
+            ->selectAlias('c.uri', 'calendaruri')
2464
+            ->from('calendarobjects', 'co')
2465
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
2466
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2467
+            ->andWhere($query->expr()->eq('co.id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
2468
+        $stmt = $query->executeQuery();
2469
+        $row = $stmt->fetch();
2470
+        $stmt->closeCursor();
2471
+
2472
+        if (!$row) {
2473
+            return null;
2474
+        }
2475
+
2476
+        return [
2477
+            'id' => $row['id'],
2478
+            'uri' => $row['uri'],
2479
+            'lastmodified' => $row['lastmodified'],
2480
+            'etag' => '"' . $row['etag'] . '"',
2481
+            'calendarid' => $row['calendarid'],
2482
+            'calendaruri' => $row['calendaruri'],
2483
+            'size' => (int)$row['size'],
2484
+            'calendardata' => $this->readBlob($row['calendardata']),
2485
+            'component' => strtolower($row['componenttype']),
2486
+            'classification' => (int)$row['classification'],
2487
+            'deleted_at' => isset($row['deleted_at']) ? ((int)$row['deleted_at']) : null,
2488
+        ];
2489
+    }
2490
+
2491
+    /**
2492
+     * The getChanges method returns all the changes that have happened, since
2493
+     * the specified syncToken in the specified calendar.
2494
+     *
2495
+     * This function should return an array, such as the following:
2496
+     *
2497
+     * [
2498
+     *   'syncToken' => 'The current synctoken',
2499
+     *   'added'   => [
2500
+     *      'new.txt',
2501
+     *   ],
2502
+     *   'modified'   => [
2503
+     *      'modified.txt',
2504
+     *   ],
2505
+     *   'deleted' => [
2506
+     *      'foo.php.bak',
2507
+     *      'old.txt'
2508
+     *   ]
2509
+     * );
2510
+     *
2511
+     * The returned syncToken property should reflect the *current* syncToken
2512
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
2513
+     * property This is * needed here too, to ensure the operation is atomic.
2514
+     *
2515
+     * If the $syncToken argument is specified as null, this is an initial
2516
+     * sync, and all members should be reported.
2517
+     *
2518
+     * The modified property is an array of nodenames that have changed since
2519
+     * the last token.
2520
+     *
2521
+     * The deleted property is an array with nodenames, that have been deleted
2522
+     * from collection.
2523
+     *
2524
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
2525
+     * 1, you only have to report changes that happened only directly in
2526
+     * immediate descendants. If it's 2, it should also include changes from
2527
+     * the nodes below the child collections. (grandchildren)
2528
+     *
2529
+     * The $limit argument allows a client to specify how many results should
2530
+     * be returned at most. If the limit is not specified, it should be treated
2531
+     * as infinite.
2532
+     *
2533
+     * If the limit (infinite or not) is higher than you're willing to return,
2534
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
2535
+     *
2536
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
2537
+     * return null.
2538
+     *
2539
+     * The limit is 'suggestive'. You are free to ignore it.
2540
+     *
2541
+     * @param string $calendarId
2542
+     * @param string $syncToken
2543
+     * @param int $syncLevel
2544
+     * @param int|null $limit
2545
+     * @param int $calendarType
2546
+     * @return ?array
2547
+     */
2548
+    public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2549
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2550
+
2551
+        return $this->atomic(function () use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
2552
+            // Current synctoken
2553
+            $qb = $this->db->getQueryBuilder();
2554
+            $qb->select('synctoken')
2555
+                ->from($table)
2556
+                ->where(
2557
+                    $qb->expr()->eq('id', $qb->createNamedParameter($calendarId))
2558
+                );
2559
+            $stmt = $qb->executeQuery();
2560
+            $currentToken = $stmt->fetchOne();
2561
+            $initialSync = !is_numeric($syncToken);
2562
+
2563
+            if ($currentToken === false) {
2564
+                return null;
2565
+            }
2566
+
2567
+            // evaluate if this is a initial sync and construct appropriate command
2568
+            if ($initialSync) {
2569
+                $qb = $this->db->getQueryBuilder();
2570
+                $qb->select('uri')
2571
+                    ->from('calendarobjects')
2572
+                    ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2573
+                    ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2574
+                    ->andWhere($qb->expr()->isNull('deleted_at'));
2575
+            } else {
2576
+                $qb = $this->db->getQueryBuilder();
2577
+                $qb->select('uri', $qb->func()->max('operation'))
2578
+                    ->from('calendarchanges')
2579
+                    ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2580
+                    ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2581
+                    ->andWhere($qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)))
2582
+                    ->andWhere($qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)))
2583
+                    ->groupBy('uri');
2584
+            }
2585
+            // evaluate if limit exists
2586
+            if (is_numeric($limit)) {
2587
+                $qb->setMaxResults($limit);
2588
+            }
2589
+            // execute command
2590
+            $stmt = $qb->executeQuery();
2591
+            // build results
2592
+            $result = ['syncToken' => $currentToken, 'added' => [], 'modified' => [], 'deleted' => []];
2593
+            // retrieve results
2594
+            if ($initialSync) {
2595
+                $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
2596
+            } else {
2597
+                // \PDO::FETCH_NUM is needed due to the inconsistent field names
2598
+                // produced by doctrine for MAX() with different databases
2599
+                while ($entry = $stmt->fetch(\PDO::FETCH_NUM)) {
2600
+                    // assign uri (column 0) to appropriate mutation based on operation (column 1)
2601
+                    // forced (int) is needed as doctrine with OCI returns the operation field as string not integer
2602
+                    match ((int)$entry[1]) {
2603
+                        1 => $result['added'][] = $entry[0],
2604
+                        2 => $result['modified'][] = $entry[0],
2605
+                        3 => $result['deleted'][] = $entry[0],
2606
+                        default => $this->logger->debug('Unknown calendar change operation detected')
2607
+                    };
2608
+                }
2609
+            }
2610
+            $stmt->closeCursor();
2611
+
2612
+            return $result;
2613
+        }, $this->db);
2614
+    }
2615
+
2616
+    /**
2617
+     * Returns a list of subscriptions for a principal.
2618
+     *
2619
+     * Every subscription is an array with the following keys:
2620
+     *  * id, a unique id that will be used by other functions to modify the
2621
+     *    subscription. This can be the same as the uri or a database key.
2622
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
2623
+     *  * principaluri. The owner of the subscription. Almost always the same as
2624
+     *    principalUri passed to this method.
2625
+     *
2626
+     * Furthermore, all the subscription info must be returned too:
2627
+     *
2628
+     * 1. {DAV:}displayname
2629
+     * 2. {http://apple.com/ns/ical/}refreshrate
2630
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
2631
+     *    should not be stripped).
2632
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
2633
+     *    should not be stripped).
2634
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
2635
+     *    attachments should not be stripped).
2636
+     * 6. {http://calendarserver.org/ns/}source (Must be a
2637
+     *     Sabre\DAV\Property\Href).
2638
+     * 7. {http://apple.com/ns/ical/}calendar-color
2639
+     * 8. {http://apple.com/ns/ical/}calendar-order
2640
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
2641
+     *    (should just be an instance of
2642
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
2643
+     *    default components).
2644
+     *
2645
+     * @param string $principalUri
2646
+     * @return array
2647
+     */
2648
+    public function getSubscriptionsForUser($principalUri) {
2649
+        $fields = array_column($this->subscriptionPropertyMap, 0);
2650
+        $fields[] = 'id';
2651
+        $fields[] = 'uri';
2652
+        $fields[] = 'source';
2653
+        $fields[] = 'principaluri';
2654
+        $fields[] = 'lastmodified';
2655
+        $fields[] = 'synctoken';
2656
+
2657
+        $query = $this->db->getQueryBuilder();
2658
+        $query->select($fields)
2659
+            ->from('calendarsubscriptions')
2660
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2661
+            ->orderBy('calendarorder', 'asc');
2662
+        $stmt = $query->executeQuery();
2663
+
2664
+        $subscriptions = [];
2665
+        while ($row = $stmt->fetch()) {
2666
+            $subscription = [
2667
+                'id' => $row['id'],
2668
+                'uri' => $row['uri'],
2669
+                'principaluri' => $row['principaluri'],
2670
+                'source' => $row['source'],
2671
+                'lastmodified' => $row['lastmodified'],
2672
+
2673
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2674
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
2675
+            ];
2676
+
2677
+            $subscriptions[] = $this->rowToSubscription($row, $subscription);
2678
+        }
2679
+
2680
+        return $subscriptions;
2681
+    }
2682
+
2683
+    /**
2684
+     * Creates a new subscription for a principal.
2685
+     *
2686
+     * If the creation was a success, an id must be returned that can be used to reference
2687
+     * this subscription in other methods, such as updateSubscription.
2688
+     *
2689
+     * @param string $principalUri
2690
+     * @param string $uri
2691
+     * @param array $properties
2692
+     * @return mixed
2693
+     */
2694
+    public function createSubscription($principalUri, $uri, array $properties) {
2695
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2696
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2697
+        }
2698
+
2699
+        $values = [
2700
+            'principaluri' => $principalUri,
2701
+            'uri' => $uri,
2702
+            'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2703
+            'lastmodified' => time(),
2704
+        ];
2705
+
2706
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2707
+
2708
+        foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
2709
+            if (array_key_exists($xmlName, $properties)) {
2710
+                $values[$dbName] = $properties[$xmlName];
2711
+                if (in_array($dbName, $propertiesBoolean)) {
2712
+                    $values[$dbName] = true;
2713
+                }
2714
+            }
2715
+        }
2716
+
2717
+        [$subscriptionId, $subscriptionRow] = $this->atomic(function () use ($values) {
2718
+            $valuesToInsert = [];
2719
+            $query = $this->db->getQueryBuilder();
2720
+            foreach (array_keys($values) as $name) {
2721
+                $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2722
+            }
2723
+            $query->insert('calendarsubscriptions')
2724
+                ->values($valuesToInsert)
2725
+                ->executeStatement();
2726
+
2727
+            $subscriptionId = $query->getLastInsertId();
2728
+
2729
+            $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2730
+            return [$subscriptionId, $subscriptionRow];
2731
+        }, $this->db);
2732
+
2733
+        $this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow));
2734
+
2735
+        return $subscriptionId;
2736
+    }
2737
+
2738
+    /**
2739
+     * Updates a subscription
2740
+     *
2741
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2742
+     * To do the actual updates, you must tell this object which properties
2743
+     * you're going to process with the handle() method.
2744
+     *
2745
+     * Calling the handle method is like telling the PropPatch object "I
2746
+     * promise I can handle updating this property".
2747
+     *
2748
+     * Read the PropPatch documentation for more info and examples.
2749
+     *
2750
+     * @param mixed $subscriptionId
2751
+     * @param PropPatch $propPatch
2752
+     * @return void
2753
+     */
2754
+    public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2755
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
2756
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
2757
+
2758
+        $propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2759
+            $newValues = [];
2760
+
2761
+            foreach ($mutations as $propertyName => $propertyValue) {
2762
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
2763
+                    $newValues['source'] = $propertyValue->getHref();
2764
+                } else {
2765
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName][0];
2766
+                    $newValues[$fieldName] = $propertyValue;
2767
+                }
2768
+            }
2769
+
2770
+            $subscriptionRow = $this->atomic(function () use ($subscriptionId, $newValues) {
2771
+                $query = $this->db->getQueryBuilder();
2772
+                $query->update('calendarsubscriptions')
2773
+                    ->set('lastmodified', $query->createNamedParameter(time()));
2774
+                foreach ($newValues as $fieldName => $value) {
2775
+                    $query->set($fieldName, $query->createNamedParameter($value));
2776
+                }
2777
+                $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2778
+                    ->executeStatement();
2779
+
2780
+                return $this->getSubscriptionById($subscriptionId);
2781
+            }, $this->db);
2782
+
2783
+            $this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2784
+
2785
+            return true;
2786
+        });
2787
+    }
2788
+
2789
+    /**
2790
+     * Deletes a subscription.
2791
+     *
2792
+     * @param mixed $subscriptionId
2793
+     * @return void
2794
+     */
2795
+    public function deleteSubscription($subscriptionId) {
2796
+        $this->atomic(function () use ($subscriptionId): void {
2797
+            $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2798
+
2799
+            $query = $this->db->getQueryBuilder();
2800
+            $query->delete('calendarsubscriptions')
2801
+                ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2802
+                ->executeStatement();
2803
+
2804
+            $query = $this->db->getQueryBuilder();
2805
+            $query->delete('calendarobjects')
2806
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2807
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2808
+                ->executeStatement();
2809
+
2810
+            $query->delete('calendarchanges')
2811
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2812
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2813
+                ->executeStatement();
2814
+
2815
+            $query->delete($this->dbObjectPropertiesTable)
2816
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2817
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2818
+                ->executeStatement();
2819
+
2820
+            if ($subscriptionRow) {
2821
+                $this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2822
+            }
2823
+        }, $this->db);
2824
+    }
2825
+
2826
+    /**
2827
+     * Returns a single scheduling object for the inbox collection.
2828
+     *
2829
+     * The returned array should contain the following elements:
2830
+     *   * uri - A unique basename for the object. This will be used to
2831
+     *           construct a full uri.
2832
+     *   * calendardata - The iCalendar object
2833
+     *   * lastmodified - The last modification date. Can be an int for a unix
2834
+     *                    timestamp, or a PHP DateTime object.
2835
+     *   * etag - A unique token that must change if the object changed.
2836
+     *   * size - The size of the object, in bytes.
2837
+     *
2838
+     * @param string $principalUri
2839
+     * @param string $objectUri
2840
+     * @return array
2841
+     */
2842
+    public function getSchedulingObject($principalUri, $objectUri) {
2843
+        $query = $this->db->getQueryBuilder();
2844
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2845
+            ->from('schedulingobjects')
2846
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2847
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2848
+            ->executeQuery();
2849
+
2850
+        $row = $stmt->fetch();
2851
+
2852
+        if (!$row) {
2853
+            return null;
2854
+        }
2855
+
2856
+        return [
2857
+            'uri' => $row['uri'],
2858
+            'calendardata' => $row['calendardata'],
2859
+            'lastmodified' => $row['lastmodified'],
2860
+            'etag' => '"' . $row['etag'] . '"',
2861
+            'size' => (int)$row['size'],
2862
+        ];
2863
+    }
2864
+
2865
+    /**
2866
+     * Returns all scheduling objects for the inbox collection.
2867
+     *
2868
+     * These objects should be returned as an array. Every item in the array
2869
+     * should follow the same structure as returned from getSchedulingObject.
2870
+     *
2871
+     * The main difference is that 'calendardata' is optional.
2872
+     *
2873
+     * @param string $principalUri
2874
+     * @return array
2875
+     */
2876
+    public function getSchedulingObjects($principalUri) {
2877
+        $query = $this->db->getQueryBuilder();
2878
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2879
+            ->from('schedulingobjects')
2880
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2881
+            ->executeQuery();
2882
+
2883
+        $results = [];
2884
+        while (($row = $stmt->fetch()) !== false) {
2885
+            $results[] = [
2886
+                'calendardata' => $row['calendardata'],
2887
+                'uri' => $row['uri'],
2888
+                'lastmodified' => $row['lastmodified'],
2889
+                'etag' => '"' . $row['etag'] . '"',
2890
+                'size' => (int)$row['size'],
2891
+            ];
2892
+        }
2893
+        $stmt->closeCursor();
2894
+
2895
+        return $results;
2896
+    }
2897
+
2898
+    /**
2899
+     * Deletes a scheduling object from the inbox collection.
2900
+     *
2901
+     * @param string $principalUri
2902
+     * @param string $objectUri
2903
+     * @return void
2904
+     */
2905
+    public function deleteSchedulingObject($principalUri, $objectUri) {
2906
+        $this->cachedObjects = [];
2907
+        $query = $this->db->getQueryBuilder();
2908
+        $query->delete('schedulingobjects')
2909
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2910
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2911
+            ->executeStatement();
2912
+    }
2913
+
2914
+    /**
2915
+     * Deletes all scheduling objects last modified before $modifiedBefore from the inbox collection.
2916
+     *
2917
+     * @param int $modifiedBefore
2918
+     * @param int $limit
2919
+     * @return void
2920
+     */
2921
+    public function deleteOutdatedSchedulingObjects(int $modifiedBefore, int $limit): void {
2922
+        $query = $this->db->getQueryBuilder();
2923
+        $query->select('id')
2924
+            ->from('schedulingobjects')
2925
+            ->where($query->expr()->lt('lastmodified', $query->createNamedParameter($modifiedBefore)))
2926
+            ->setMaxResults($limit);
2927
+        $result = $query->executeQuery();
2928
+        $count = $result->rowCount();
2929
+        if ($count === 0) {
2930
+            return;
2931
+        }
2932
+        $ids = array_map(static function (array $id) {
2933
+            return (int)$id[0];
2934
+        }, $result->fetchAll(\PDO::FETCH_NUM));
2935
+        $result->closeCursor();
2936
+
2937
+        $numDeleted = 0;
2938
+        $deleteQuery = $this->db->getQueryBuilder();
2939
+        $deleteQuery->delete('schedulingobjects')
2940
+            ->where($deleteQuery->expr()->in('id', $deleteQuery->createParameter('ids'), IQueryBuilder::PARAM_INT_ARRAY));
2941
+        foreach (array_chunk($ids, 1000) as $chunk) {
2942
+            $deleteQuery->setParameter('ids', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
2943
+            $numDeleted += $deleteQuery->executeStatement();
2944
+        }
2945
+
2946
+        if ($numDeleted === $limit) {
2947
+            $this->logger->info("Deleted $limit scheduling objects, continuing with next batch");
2948
+            $this->deleteOutdatedSchedulingObjects($modifiedBefore, $limit);
2949
+        }
2950
+    }
2951
+
2952
+    /**
2953
+     * Creates a new scheduling object. This should land in a users' inbox.
2954
+     *
2955
+     * @param string $principalUri
2956
+     * @param string $objectUri
2957
+     * @param string $objectData
2958
+     * @return void
2959
+     */
2960
+    public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2961
+        $this->cachedObjects = [];
2962
+        $query = $this->db->getQueryBuilder();
2963
+        $query->insert('schedulingobjects')
2964
+            ->values([
2965
+                'principaluri' => $query->createNamedParameter($principalUri),
2966
+                'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2967
+                'uri' => $query->createNamedParameter($objectUri),
2968
+                'lastmodified' => $query->createNamedParameter(time()),
2969
+                'etag' => $query->createNamedParameter(md5($objectData)),
2970
+                'size' => $query->createNamedParameter(strlen($objectData))
2971
+            ])
2972
+            ->executeStatement();
2973
+    }
2974
+
2975
+    /**
2976
+     * Adds a change record to the calendarchanges table.
2977
+     *
2978
+     * @param mixed $calendarId
2979
+     * @param string[] $objectUris
2980
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2981
+     * @param int $calendarType
2982
+     * @return void
2983
+     */
2984
+    protected function addChanges(int $calendarId, array $objectUris, int $operation, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
2985
+        $this->cachedObjects = [];
2986
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2987
+
2988
+        $this->atomic(function () use ($calendarId, $objectUris, $operation, $calendarType, $table): void {
2989
+            $query = $this->db->getQueryBuilder();
2990
+            $query->select('synctoken')
2991
+                ->from($table)
2992
+                ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2993
+            $result = $query->executeQuery();
2994
+            $syncToken = (int)$result->fetchOne();
2995
+            $result->closeCursor();
2996
+
2997
+            $query = $this->db->getQueryBuilder();
2998
+            $query->insert('calendarchanges')
2999
+                ->values([
3000
+                    'uri' => $query->createParameter('uri'),
3001
+                    'synctoken' => $query->createNamedParameter($syncToken),
3002
+                    'calendarid' => $query->createNamedParameter($calendarId),
3003
+                    'operation' => $query->createNamedParameter($operation),
3004
+                    'calendartype' => $query->createNamedParameter($calendarType),
3005
+                    'created_at' => $query->createNamedParameter(time()),
3006
+                ]);
3007
+            foreach ($objectUris as $uri) {
3008
+                $query->setParameter('uri', $uri);
3009
+                $query->executeStatement();
3010
+            }
3011
+
3012
+            $query = $this->db->getQueryBuilder();
3013
+            $query->update($table)
3014
+                ->set('synctoken', $query->createNamedParameter($syncToken + 1, IQueryBuilder::PARAM_INT))
3015
+                ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
3016
+                ->executeStatement();
3017
+        }, $this->db);
3018
+    }
3019
+
3020
+    public function restoreChanges(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
3021
+        $this->cachedObjects = [];
3022
+
3023
+        $this->atomic(function () use ($calendarId, $calendarType): void {
3024
+            $qbAdded = $this->db->getQueryBuilder();
3025
+            $qbAdded->select('uri')
3026
+                ->from('calendarobjects')
3027
+                ->where(
3028
+                    $qbAdded->expr()->andX(
3029
+                        $qbAdded->expr()->eq('calendarid', $qbAdded->createNamedParameter($calendarId)),
3030
+                        $qbAdded->expr()->eq('calendartype', $qbAdded->createNamedParameter($calendarType)),
3031
+                        $qbAdded->expr()->isNull('deleted_at'),
3032
+                    )
3033
+                );
3034
+            $resultAdded = $qbAdded->executeQuery();
3035
+            $addedUris = $resultAdded->fetchAll(\PDO::FETCH_COLUMN);
3036
+            $resultAdded->closeCursor();
3037
+            // Track everything as changed
3038
+            // Tracking the creation is not necessary because \OCA\DAV\CalDAV\CalDavBackend::getChangesForCalendar
3039
+            // only returns the last change per object.
3040
+            $this->addChanges($calendarId, $addedUris, 2, $calendarType);
3041
+
3042
+            $qbDeleted = $this->db->getQueryBuilder();
3043
+            $qbDeleted->select('uri')
3044
+                ->from('calendarobjects')
3045
+                ->where(
3046
+                    $qbDeleted->expr()->andX(
3047
+                        $qbDeleted->expr()->eq('calendarid', $qbDeleted->createNamedParameter($calendarId)),
3048
+                        $qbDeleted->expr()->eq('calendartype', $qbDeleted->createNamedParameter($calendarType)),
3049
+                        $qbDeleted->expr()->isNotNull('deleted_at'),
3050
+                    )
3051
+                );
3052
+            $resultDeleted = $qbDeleted->executeQuery();
3053
+            $deletedUris = array_map(function (string $uri) {
3054
+                return str_replace('-deleted.ics', '.ics', $uri);
3055
+            }, $resultDeleted->fetchAll(\PDO::FETCH_COLUMN));
3056
+            $resultDeleted->closeCursor();
3057
+            $this->addChanges($calendarId, $deletedUris, 3, $calendarType);
3058
+        }, $this->db);
3059
+    }
3060
+
3061
+    /**
3062
+     * Parses some information from calendar objects, used for optimized
3063
+     * calendar-queries.
3064
+     *
3065
+     * Returns an array with the following keys:
3066
+     *   * etag - An md5 checksum of the object without the quotes.
3067
+     *   * size - Size of the object in bytes
3068
+     *   * componentType - VEVENT, VTODO or VJOURNAL
3069
+     *   * firstOccurence
3070
+     *   * lastOccurence
3071
+     *   * uid - value of the UID property
3072
+     *
3073
+     * @param string $calendarData
3074
+     * @return array
3075
+     */
3076
+    public function getDenormalizedData(string $calendarData): array {
3077
+        $vObject = Reader::read($calendarData);
3078
+        $vEvents = [];
3079
+        $componentType = null;
3080
+        $component = null;
3081
+        $firstOccurrence = null;
3082
+        $lastOccurrence = null;
3083
+        $uid = null;
3084
+        $classification = self::CLASSIFICATION_PUBLIC;
3085
+        $hasDTSTART = false;
3086
+        foreach ($vObject->getComponents() as $component) {
3087
+            if ($component->name !== 'VTIMEZONE') {
3088
+                // Finding all VEVENTs, and track them
3089
+                if ($component->name === 'VEVENT') {
3090
+                    $vEvents[] = $component;
3091
+                    if ($component->DTSTART) {
3092
+                        $hasDTSTART = true;
3093
+                    }
3094
+                }
3095
+                // Track first component type and uid
3096
+                if ($uid === null) {
3097
+                    $componentType = $component->name;
3098
+                    $uid = (string)$component->UID;
3099
+                }
3100
+            }
3101
+        }
3102
+        if (!$componentType) {
3103
+            throw new BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
3104
+        }
3105
+
3106
+        if ($hasDTSTART) {
3107
+            $component = $vEvents[0];
3108
+
3109
+            // Finding the last occurrence is a bit harder
3110
+            if (!isset($component->RRULE) && count($vEvents) === 1) {
3111
+                $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
3112
+                if (isset($component->DTEND)) {
3113
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
3114
+                } elseif (isset($component->DURATION)) {
3115
+                    $endDate = clone $component->DTSTART->getDateTime();
3116
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
3117
+                    $lastOccurrence = $endDate->getTimeStamp();
3118
+                } elseif (!$component->DTSTART->hasTime()) {
3119
+                    $endDate = clone $component->DTSTART->getDateTime();
3120
+                    $endDate->modify('+1 day');
3121
+                    $lastOccurrence = $endDate->getTimeStamp();
3122
+                } else {
3123
+                    $lastOccurrence = $firstOccurrence;
3124
+                }
3125
+            } else {
3126
+                try {
3127
+                    $it = new EventIterator($vEvents);
3128
+                } catch (NoInstancesException $e) {
3129
+                    $this->logger->debug('Caught no instance exception for calendar data. This usually indicates invalid calendar data.', [
3130
+                        'app' => 'dav',
3131
+                        'exception' => $e,
3132
+                    ]);
3133
+                    throw new Forbidden($e->getMessage());
3134
+                }
3135
+                $maxDate = new DateTime(self::MAX_DATE);
3136
+                $firstOccurrence = $it->getDtStart()->getTimestamp();
3137
+                if ($it->isInfinite()) {
3138
+                    $lastOccurrence = $maxDate->getTimestamp();
3139
+                } else {
3140
+                    $end = $it->getDtEnd();
3141
+                    while ($it->valid() && $end < $maxDate) {
3142
+                        $end = $it->getDtEnd();
3143
+                        $it->next();
3144
+                    }
3145
+                    $lastOccurrence = $end->getTimestamp();
3146
+                }
3147
+            }
3148
+        }
3149
+
3150
+        if ($component->CLASS) {
3151
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
3152
+            switch ($component->CLASS->getValue()) {
3153
+                case 'PUBLIC':
3154
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
3155
+                    break;
3156
+                case 'CONFIDENTIAL':
3157
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
3158
+                    break;
3159
+            }
3160
+        }
3161
+        return [
3162
+            'etag' => md5($calendarData),
3163
+            'size' => strlen($calendarData),
3164
+            'componentType' => $componentType,
3165
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
3166
+            'lastOccurence' => is_null($lastOccurrence) ? null : max(0, $lastOccurrence),
3167
+            'uid' => $uid,
3168
+            'classification' => $classification
3169
+        ];
3170
+    }
3171
+
3172
+    /**
3173
+     * @param $cardData
3174
+     * @return bool|string
3175
+     */
3176
+    private function readBlob($cardData) {
3177
+        if (is_resource($cardData)) {
3178
+            return stream_get_contents($cardData);
3179
+        }
3180
+
3181
+        return $cardData;
3182
+    }
3183
+
3184
+    /**
3185
+     * @param list<array{href: string, commonName: string, readOnly: bool}> $add
3186
+     * @param list<string> $remove
3187
+     */
3188
+    public function updateShares(IShareable $shareable, array $add, array $remove): void {
3189
+        $this->atomic(function () use ($shareable, $add, $remove): void {
3190
+            $calendarId = $shareable->getResourceId();
3191
+            $calendarRow = $this->getCalendarById($calendarId);
3192
+            if ($calendarRow === null) {
3193
+                throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $calendarId);
3194
+            }
3195
+            $oldShares = $this->getShares($calendarId);
3196
+
3197
+            $this->calendarSharingBackend->updateShares($shareable, $add, $remove, $oldShares);
3198
+
3199
+            $this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent($calendarId, $calendarRow, $oldShares, $add, $remove));
3200
+        }, $this->db);
3201
+    }
3202
+
3203
+    /**
3204
+     * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
3205
+     */
3206
+    public function getShares(int $resourceId): array {
3207
+        return $this->calendarSharingBackend->getShares($resourceId);
3208
+    }
3209
+
3210
+    public function getSharesByShareePrincipal(string $principal): array {
3211
+        return $this->calendarSharingBackend->getSharesByShareePrincipal($principal);
3212
+    }
3213
+
3214
+    public function preloadShares(array $resourceIds): void {
3215
+        $this->calendarSharingBackend->preloadShares($resourceIds);
3216
+    }
3217
+
3218
+    /**
3219
+     * @param boolean $value
3220
+     * @param Calendar $calendar
3221
+     * @return string|null
3222
+     */
3223
+    public function setPublishStatus($value, $calendar) {
3224
+        return $this->atomic(function () use ($value, $calendar) {
3225
+            $calendarId = $calendar->getResourceId();
3226
+            $calendarData = $this->getCalendarById($calendarId);
3227
+
3228
+            $query = $this->db->getQueryBuilder();
3229
+            if ($value) {
3230
+                $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
3231
+                $query->insert('dav_shares')
3232
+                    ->values([
3233
+                        'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
3234
+                        'type' => $query->createNamedParameter('calendar'),
3235
+                        'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
3236
+                        'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
3237
+                        'publicuri' => $query->createNamedParameter($publicUri)
3238
+                    ]);
3239
+                $query->executeStatement();
3240
+
3241
+                $this->dispatcher->dispatchTyped(new CalendarPublishedEvent($calendarId, $calendarData, $publicUri));
3242
+                return $publicUri;
3243
+            }
3244
+            $query->delete('dav_shares')
3245
+                ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3246
+                ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
3247
+            $query->executeStatement();
3248
+
3249
+            $this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent($calendarId, $calendarData));
3250
+            return null;
3251
+        }, $this->db);
3252
+    }
3253
+
3254
+    /**
3255
+     * @param Calendar $calendar
3256
+     * @return mixed
3257
+     */
3258
+    public function getPublishStatus($calendar) {
3259
+        $query = $this->db->getQueryBuilder();
3260
+        $result = $query->select('publicuri')
3261
+            ->from('dav_shares')
3262
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3263
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
3264
+            ->executeQuery();
3265
+
3266
+        $row = $result->fetch();
3267
+        $result->closeCursor();
3268
+        return $row ? reset($row) : false;
3269
+    }
3270
+
3271
+    /**
3272
+     * @param int $resourceId
3273
+     * @param list<array{privilege: string, principal: string, protected: bool}> $acl
3274
+     * @return list<array{privilege: string, principal: string, protected: bool}>
3275
+     */
3276
+    public function applyShareAcl(int $resourceId, array $acl): array {
3277
+        $shares = $this->calendarSharingBackend->getShares($resourceId);
3278
+        return $this->calendarSharingBackend->applyShareAcl($shares, $acl);
3279
+    }
3280
+
3281
+    /**
3282
+     * update properties table
3283
+     *
3284
+     * @param int $calendarId
3285
+     * @param string $objectUri
3286
+     * @param string $calendarData
3287
+     * @param int $calendarType
3288
+     */
3289
+    public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
3290
+        $this->cachedObjects = [];
3291
+        $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $calendarType): void {
3292
+            $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
3293
+
3294
+            try {
3295
+                $vCalendar = $this->readCalendarData($calendarData);
3296
+            } catch (\Exception $ex) {
3297
+                return;
3298
+            }
3299
+
3300
+            $this->purgeProperties($calendarId, $objectId);
3301
+
3302
+            $query = $this->db->getQueryBuilder();
3303
+            $query->insert($this->dbObjectPropertiesTable)
3304
+                ->values(
3305
+                    [
3306
+                        'calendarid' => $query->createNamedParameter($calendarId),
3307
+                        'calendartype' => $query->createNamedParameter($calendarType),
3308
+                        'objectid' => $query->createNamedParameter($objectId),
3309
+                        'name' => $query->createParameter('name'),
3310
+                        'parameter' => $query->createParameter('parameter'),
3311
+                        'value' => $query->createParameter('value'),
3312
+                    ]
3313
+                );
3314
+
3315
+            $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
3316
+            foreach ($vCalendar->getComponents() as $component) {
3317
+                if (!in_array($component->name, $indexComponents)) {
3318
+                    continue;
3319
+                }
3320
+
3321
+                foreach ($component->children() as $property) {
3322
+                    if (in_array($property->name, self::INDEXED_PROPERTIES, true)) {
3323
+                        $value = $property->getValue();
3324
+                        // is this a shitty db?
3325
+                        if (!$this->db->supports4ByteText()) {
3326
+                            $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3327
+                        }
3328
+                        $value = mb_strcut($value, 0, 254);
3329
+
3330
+                        $query->setParameter('name', $property->name);
3331
+                        $query->setParameter('parameter', null);
3332
+                        $query->setParameter('value', mb_strcut($value, 0, 254));
3333
+                        $query->executeStatement();
3334
+                    }
3335
+
3336
+                    if (array_key_exists($property->name, self::$indexParameters)) {
3337
+                        $parameters = $property->parameters();
3338
+                        $indexedParametersForProperty = self::$indexParameters[$property->name];
3339
+
3340
+                        foreach ($parameters as $key => $value) {
3341
+                            if (in_array($key, $indexedParametersForProperty)) {
3342
+                                // is this a shitty db?
3343
+                                if ($this->db->supports4ByteText()) {
3344
+                                    $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3345
+                                }
3346
+
3347
+                                $query->setParameter('name', $property->name);
3348
+                                $query->setParameter('parameter', mb_strcut($key, 0, 254));
3349
+                                $query->setParameter('value', mb_strcut($value, 0, 254));
3350
+                                $query->executeStatement();
3351
+                            }
3352
+                        }
3353
+                    }
3354
+                }
3355
+            }
3356
+        }, $this->db);
3357
+    }
3358
+
3359
+    /**
3360
+     * deletes all birthday calendars
3361
+     */
3362
+    public function deleteAllBirthdayCalendars() {
3363
+        $this->atomic(function (): void {
3364
+            $query = $this->db->getQueryBuilder();
3365
+            $result = $query->select(['id'])->from('calendars')
3366
+                ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
3367
+                ->executeQuery();
3368
+
3369
+            while (($row = $result->fetch()) !== false) {
3370
+                $this->deleteCalendar(
3371
+                    $row['id'],
3372
+                    true // No data to keep in the trashbin, if the user re-enables then we regenerate
3373
+                );
3374
+            }
3375
+            $result->closeCursor();
3376
+        }, $this->db);
3377
+    }
3378
+
3379
+    /**
3380
+     * @param $subscriptionId
3381
+     */
3382
+    public function purgeAllCachedEventsForSubscription($subscriptionId) {
3383
+        $this->atomic(function () use ($subscriptionId): void {
3384
+            $query = $this->db->getQueryBuilder();
3385
+            $query->select('uri')
3386
+                ->from('calendarobjects')
3387
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3388
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
3389
+            $stmt = $query->executeQuery();
3390
+
3391
+            $uris = [];
3392
+            while (($row = $stmt->fetch()) !== false) {
3393
+                $uris[] = $row['uri'];
3394
+            }
3395
+            $stmt->closeCursor();
3396
+
3397
+            $query = $this->db->getQueryBuilder();
3398
+            $query->delete('calendarobjects')
3399
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3400
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3401
+                ->executeStatement();
3402
+
3403
+            $query = $this->db->getQueryBuilder();
3404
+            $query->delete('calendarchanges')
3405
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3406
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3407
+                ->executeStatement();
3408
+
3409
+            $query = $this->db->getQueryBuilder();
3410
+            $query->delete($this->dbObjectPropertiesTable)
3411
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3412
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3413
+                ->executeStatement();
3414
+
3415
+            $this->addChanges($subscriptionId, $uris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3416
+        }, $this->db);
3417
+    }
3418
+
3419
+    /**
3420
+     * @param int $subscriptionId
3421
+     * @param array<int> $calendarObjectIds
3422
+     * @param array<string> $calendarObjectUris
3423
+     */
3424
+    public function purgeCachedEventsForSubscription(int $subscriptionId, array $calendarObjectIds, array $calendarObjectUris): void {
3425
+        if (empty($calendarObjectUris)) {
3426
+            return;
3427
+        }
3428
+
3429
+        $this->atomic(function () use ($subscriptionId, $calendarObjectIds, $calendarObjectUris): void {
3430
+            foreach (array_chunk($calendarObjectIds, 1000) as $chunk) {
3431
+                $query = $this->db->getQueryBuilder();
3432
+                $query->delete($this->dbObjectPropertiesTable)
3433
+                    ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3434
+                    ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3435
+                    ->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3436
+                    ->executeStatement();
3437
+
3438
+                $query = $this->db->getQueryBuilder();
3439
+                $query->delete('calendarobjects')
3440
+                    ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3441
+                    ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3442
+                    ->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3443
+                    ->executeStatement();
3444
+            }
3445
+
3446
+            foreach (array_chunk($calendarObjectUris, 1000) as $chunk) {
3447
+                $query = $this->db->getQueryBuilder();
3448
+                $query->delete('calendarchanges')
3449
+                    ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3450
+                    ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3451
+                    ->andWhere($query->expr()->in('uri', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
3452
+                    ->executeStatement();
3453
+            }
3454
+            $this->addChanges($subscriptionId, $calendarObjectUris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3455
+        }, $this->db);
3456
+    }
3457
+
3458
+    /**
3459
+     * Move a calendar from one user to another
3460
+     *
3461
+     * @param string $uriName
3462
+     * @param string $uriOrigin
3463
+     * @param string $uriDestination
3464
+     * @param string $newUriName (optional) the new uriName
3465
+     */
3466
+    public function moveCalendar($uriName, $uriOrigin, $uriDestination, $newUriName = null) {
3467
+        $query = $this->db->getQueryBuilder();
3468
+        $query->update('calendars')
3469
+            ->set('principaluri', $query->createNamedParameter($uriDestination))
3470
+            ->set('uri', $query->createNamedParameter($newUriName ?: $uriName))
3471
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
3472
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
3473
+            ->executeStatement();
3474
+    }
3475
+
3476
+    /**
3477
+     * read VCalendar data into a VCalendar object
3478
+     *
3479
+     * @param string $objectData
3480
+     * @return VCalendar
3481
+     */
3482
+    protected function readCalendarData($objectData) {
3483
+        return Reader::read($objectData);
3484
+    }
3485
+
3486
+    /**
3487
+     * delete all properties from a given calendar object
3488
+     *
3489
+     * @param int $calendarId
3490
+     * @param int $objectId
3491
+     */
3492
+    protected function purgeProperties($calendarId, $objectId) {
3493
+        $this->cachedObjects = [];
3494
+        $query = $this->db->getQueryBuilder();
3495
+        $query->delete($this->dbObjectPropertiesTable)
3496
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
3497
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
3498
+        $query->executeStatement();
3499
+    }
3500
+
3501
+    /**
3502
+     * get ID from a given calendar object
3503
+     *
3504
+     * @param int $calendarId
3505
+     * @param string $uri
3506
+     * @param int $calendarType
3507
+     * @return int
3508
+     */
3509
+    protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
3510
+        $query = $this->db->getQueryBuilder();
3511
+        $query->select('id')
3512
+            ->from('calendarobjects')
3513
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
3514
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
3515
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
3516
+
3517
+        $result = $query->executeQuery();
3518
+        $objectIds = $result->fetch();
3519
+        $result->closeCursor();
3520
+
3521
+        if (!isset($objectIds['id'])) {
3522
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
3523
+        }
3524
+
3525
+        return (int)$objectIds['id'];
3526
+    }
3527
+
3528
+    /**
3529
+     * @throws \InvalidArgumentException
3530
+     */
3531
+    public function pruneOutdatedSyncTokens(int $keep, int $retention): int {
3532
+        if ($keep < 0) {
3533
+            throw new \InvalidArgumentException();
3534
+        }
3535
+
3536
+        $query = $this->db->getQueryBuilder();
3537
+        $query->select($query->func()->max('id'))
3538
+            ->from('calendarchanges');
3539
+
3540
+        $result = $query->executeQuery();
3541
+        $maxId = (int)$result->fetchOne();
3542
+        $result->closeCursor();
3543
+        if (!$maxId || $maxId < $keep) {
3544
+            return 0;
3545
+        }
3546
+
3547
+        $query = $this->db->getQueryBuilder();
3548
+        $query->delete('calendarchanges')
3549
+            ->where(
3550
+                $query->expr()->lte('id', $query->createNamedParameter($maxId - $keep, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
3551
+                $query->expr()->lte('created_at', $query->createNamedParameter($retention)),
3552
+            );
3553
+        return $query->executeStatement();
3554
+    }
3555
+
3556
+    /**
3557
+     * return legacy endpoint principal name to new principal name
3558
+     *
3559
+     * @param $principalUri
3560
+     * @param $toV2
3561
+     * @return string
3562
+     */
3563
+    private function convertPrincipal($principalUri, $toV2) {
3564
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
3565
+            [, $name] = Uri\split($principalUri);
3566
+            if ($toV2 === true) {
3567
+                return "principals/users/$name";
3568
+            }
3569
+            return "principals/$name";
3570
+        }
3571
+        return $principalUri;
3572
+    }
3573
+
3574
+    /**
3575
+     * adds information about an owner to the calendar data
3576
+     *
3577
+     */
3578
+    private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
3579
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
3580
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
3581
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
3582
+            $uri = $calendarInfo[$ownerPrincipalKey];
3583
+        } else {
3584
+            $uri = $calendarInfo['principaluri'];
3585
+        }
3586
+
3587
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
3588
+        if (isset($principalInformation['{DAV:}displayname'])) {
3589
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
3590
+        }
3591
+        return $calendarInfo;
3592
+    }
3593
+
3594
+    private function addResourceTypeToCalendar(array $row, array $calendar): array {
3595
+        if (isset($row['deleted_at'])) {
3596
+            // Columns is set and not null -> this is a deleted calendar
3597
+            // we send a custom resourcetype to hide the deleted calendar
3598
+            // from ordinary DAV clients, but the Calendar app will know
3599
+            // how to handle this special resource.
3600
+            $calendar['{DAV:}resourcetype'] = new DAV\Xml\Property\ResourceType([
3601
+                '{DAV:}collection',
3602
+                sprintf('{%s}deleted-calendar', \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD),
3603
+            ]);
3604
+        }
3605
+        return $calendar;
3606
+    }
3607
+
3608
+    /**
3609
+     * Amend the calendar info with database row data
3610
+     *
3611
+     * @param array $row
3612
+     * @param array $calendar
3613
+     *
3614
+     * @return array
3615
+     */
3616
+    private function rowToCalendar($row, array $calendar): array {
3617
+        foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
3618
+            $value = $row[$dbName];
3619
+            if ($value !== null) {
3620
+                settype($value, $type);
3621
+            }
3622
+            $calendar[$xmlName] = $value;
3623
+        }
3624
+        return $calendar;
3625
+    }
3626
+
3627
+    /**
3628
+     * Amend the subscription info with database row data
3629
+     *
3630
+     * @param array $row
3631
+     * @param array $subscription
3632
+     *
3633
+     * @return array
3634
+     */
3635
+    private function rowToSubscription($row, array $subscription): array {
3636
+        foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
3637
+            $value = $row[$dbName];
3638
+            if ($value !== null) {
3639
+                settype($value, $type);
3640
+            }
3641
+            $subscription[$xmlName] = $value;
3642
+        }
3643
+        return $subscription;
3644
+    }
3645
+
3646
+    /**
3647
+     * delete all invitations from a given calendar
3648
+     *
3649
+     * @since 31.0.0
3650
+     *
3651
+     * @param int $calendarId
3652
+     *
3653
+     * @return void
3654
+     */
3655
+    protected function purgeCalendarInvitations(int $calendarId): void {
3656
+        // select all calendar object uid's
3657
+        $cmd = $this->db->getQueryBuilder();
3658
+        $cmd->select('uid')
3659
+            ->from($this->dbObjectsTable)
3660
+            ->where($cmd->expr()->eq('calendarid', $cmd->createNamedParameter($calendarId)));
3661
+        $allIds = $cmd->executeQuery()->fetchAll(\PDO::FETCH_COLUMN);
3662
+        // delete all links that match object uid's
3663
+        $cmd = $this->db->getQueryBuilder();
3664
+        $cmd->delete($this->dbObjectInvitationsTable)
3665
+            ->where($cmd->expr()->in('uid', $cmd->createParameter('uids'), IQueryBuilder::PARAM_STR_ARRAY));
3666
+        foreach (array_chunk($allIds, 1000) as $chunkIds) {
3667
+            $cmd->setParameter('uids', $chunkIds, IQueryBuilder::PARAM_STR_ARRAY);
3668
+            $cmd->executeStatement();
3669
+        }
3670
+    }
3671
+
3672
+    /**
3673
+     * Delete all invitations from a given calendar event
3674
+     *
3675
+     * @since 31.0.0
3676
+     *
3677
+     * @param string $eventId UID of the event
3678
+     *
3679
+     * @return void
3680
+     */
3681
+    protected function purgeObjectInvitations(string $eventId): void {
3682
+        $cmd = $this->db->getQueryBuilder();
3683
+        $cmd->delete($this->dbObjectInvitationsTable)
3684
+            ->where($cmd->expr()->eq('uid', $cmd->createNamedParameter($eventId, IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR));
3685
+        $cmd->executeStatement();
3686
+    }
3687
+
3688
+    public function unshare(IShareable $shareable, string $principal): void {
3689
+        $this->atomic(function () use ($shareable, $principal): void {
3690
+            $calendarData = $this->getCalendarById($shareable->getResourceId());
3691
+            if ($calendarData === null) {
3692
+                throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $shareable->getResourceId());
3693
+            }
3694
+
3695
+            $oldShares = $this->getShares($shareable->getResourceId());
3696
+            $unshare = $this->calendarSharingBackend->unshare($shareable, $principal);
3697
+
3698
+            if ($unshare) {
3699
+                $this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent(
3700
+                    $shareable->getResourceId(),
3701
+                    $calendarData,
3702
+                    $oldShares,
3703
+                    [],
3704
+                    [$principal]
3705
+                ));
3706
+            }
3707
+        }, $this->db);
3708
+    }
3709
+
3710
+    /**
3711
+     * @return array<string, mixed>[]
3712
+     */
3713
+    public function getFederatedCalendarsForUser(string $principalUri): array {
3714
+        $federatedCalendars = $this->federatedCalendarMapper->findByPrincipalUri($principalUri);
3715
+        return array_map(
3716
+            static fn (FederatedCalendarEntity $entity) => $entity->toCalendarInfo(),
3717
+            $federatedCalendars,
3718
+        );
3719
+    }
3720
+
3721
+    public function getFederatedCalendarByUri(string $principalUri, string $uri): ?array {
3722
+        $federatedCalendar = $this->federatedCalendarMapper->findByUri($principalUri, $uri);
3723
+        return $federatedCalendar?->toCalendarInfo();
3724
+    }
3725 3725
 }
Please login to merge, or discard this patch.
Spacing   +166 added lines, -166 removed lines patch added patch discarded remove patch
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
 		'{urn:ietf:params:xml:ns:caldav}calendar-timezone' => ['timezone', 'string'],
149 149
 		'{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
150 150
 		'{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
151
-		'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => ['deleted_at', 'int'],
151
+		'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}deleted-at' => ['deleted_at', 'int'],
152 152
 	];
153 153
 
154 154
 	/**
@@ -240,7 +240,7 @@  discard block
 block discarded – undo
240 240
 		}
241 241
 
242 242
 		$result = $query->executeQuery();
243
-		$column = (int)$result->fetchOne();
243
+		$column = (int) $result->fetchOne();
244 244
 		$result->closeCursor();
245 245
 		return $column;
246 246
 	}
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 		}
262 262
 
263 263
 		$result = $query->executeQuery();
264
-		$column = (int)$result->fetchOne();
264
+		$column = (int) $result->fetchOne();
265 265
 		$result->closeCursor();
266 266
 		return $column;
267 267
 	}
@@ -279,8 +279,8 @@  discard block
 block discarded – undo
279 279
 		$calendars = [];
280 280
 		while (($row = $result->fetch()) !== false) {
281 281
 			$calendars[] = [
282
-				'id' => (int)$row['id'],
283
-				'deleted_at' => (int)$row['deleted_at'],
282
+				'id' => (int) $row['id'],
283
+				'deleted_at' => (int) $row['deleted_at'],
284 284
 			];
285 285
 		}
286 286
 		$result->closeCursor();
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
313 313
 	 * @return array
314 314
 	 */
315 315
 	public function getCalendarsForUser($principalUri) {
316
-		return $this->atomic(function () use ($principalUri) {
316
+		return $this->atomic(function() use ($principalUri) {
317 317
 			$principalUriOriginal = $principalUri;
318 318
 			$principalUri = $this->convertPrincipal($principalUri, true);
319 319
 			$fields = array_column($this->propertyMap, 0);
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
 
341 341
 			$calendars = [];
342 342
 			while ($row = $result->fetch()) {
343
-				$row['principaluri'] = (string)$row['principaluri'];
343
+				$row['principaluri'] = (string) $row['principaluri'];
344 344
 				$components = [];
345 345
 				if ($row['components']) {
346 346
 					$components = explode(',', $row['components']);
@@ -350,11 +350,11 @@  discard block
 block discarded – undo
350 350
 					'id' => $row['id'],
351 351
 					'uri' => $row['uri'],
352 352
 					'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
353
-					'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
353
+					'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
354 354
 					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
355
-					'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
356
-					'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
357
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
355
+					'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
356
+					'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
357
+					'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
358 358
 				];
359 359
 
360 360
 				$calendar = $this->rowToCalendar($row, $calendar);
@@ -373,8 +373,8 @@  discard block
 block discarded – undo
373 373
 			$principals[] = $principalUri;
374 374
 
375 375
 			$fields = array_column($this->propertyMap, 0);
376
-			$fields = array_map(function (string $field) {
377
-				return 'a.' . $field;
376
+			$fields = array_map(function(string $field) {
377
+				return 'a.'.$field;
378 378
 			}, $fields);
379 379
 			$fields[] = 'a.id';
380 380
 			$fields[] = 'a.uri';
@@ -401,14 +401,14 @@  discard block
 block discarded – undo
401 401
 
402 402
 			$results = $select->executeQuery();
403 403
 
404
-			$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
404
+			$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
405 405
 			while ($row = $results->fetch()) {
406
-				$row['principaluri'] = (string)$row['principaluri'];
406
+				$row['principaluri'] = (string) $row['principaluri'];
407 407
 				if ($row['principaluri'] === $principalUri) {
408 408
 					continue;
409 409
 				}
410 410
 
411
-				$readOnly = (int)$row['access'] === Backend::ACCESS_READ;
411
+				$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
412 412
 				if (isset($calendars[$row['id']])) {
413 413
 					if ($readOnly) {
414 414
 						// New share can not have more permissions than the old one.
@@ -422,8 +422,8 @@  discard block
 block discarded – undo
422 422
 				}
423 423
 
424 424
 				[, $name] = Uri\split($row['principaluri']);
425
-				$uri = $row['uri'] . '_shared_by_' . $name;
426
-				$row['displayname'] = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? ($name ?? '')) . ')';
425
+				$uri = $row['uri'].'_shared_by_'.$name;
426
+				$row['displayname'] = $row['displayname'].' ('.($this->userManager->getDisplayName($name) ?? ($name ?? '')).')';
427 427
 				$components = [];
428 428
 				if ($row['components']) {
429 429
 					$components = explode(',', $row['components']);
@@ -432,11 +432,11 @@  discard block
 block discarded – undo
432 432
 					'id' => $row['id'],
433 433
 					'uri' => $uri,
434 434
 					'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
435
-					'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
435
+					'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
436 436
 					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
437
-					'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
438
-					'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
439
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
437
+					'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
438
+					'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
439
+					'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
440 440
 					$readOnlyPropertyName => $readOnly,
441 441
 				];
442 442
 
@@ -473,7 +473,7 @@  discard block
 block discarded – undo
473 473
 		$stmt = $query->executeQuery();
474 474
 		$calendars = [];
475 475
 		while ($row = $stmt->fetch()) {
476
-			$row['principaluri'] = (string)$row['principaluri'];
476
+			$row['principaluri'] = (string) $row['principaluri'];
477 477
 			$components = [];
478 478
 			if ($row['components']) {
479 479
 				$components = explode(',', $row['components']);
@@ -482,10 +482,10 @@  discard block
 block discarded – undo
482 482
 				'id' => $row['id'],
483 483
 				'uri' => $row['uri'],
484 484
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
485
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
485
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
486 486
 				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
487
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
488
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
487
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
488
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
489 489
 			];
490 490
 
491 491
 			$calendar = $this->rowToCalendar($row, $calendar);
@@ -523,9 +523,9 @@  discard block
 block discarded – undo
523 523
 			->executeQuery();
524 524
 
525 525
 		while ($row = $result->fetch()) {
526
-			$row['principaluri'] = (string)$row['principaluri'];
526
+			$row['principaluri'] = (string) $row['principaluri'];
527 527
 			[, $name] = Uri\split($row['principaluri']);
528
-			$row['displayname'] = $row['displayname'] . "($name)";
528
+			$row['displayname'] = $row['displayname']."($name)";
529 529
 			$components = [];
530 530
 			if ($row['components']) {
531 531
 				$components = explode(',', $row['components']);
@@ -534,13 +534,13 @@  discard block
 block discarded – undo
534 534
 				'id' => $row['id'],
535 535
 				'uri' => $row['publicuri'],
536 536
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
537
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
537
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
538 538
 				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
539
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
540
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
541
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
542
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => true,
543
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
539
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
540
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
541
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
542
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => true,
543
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
544 544
 			];
545 545
 
546 546
 			$calendar = $this->rowToCalendar($row, $calendar);
@@ -585,12 +585,12 @@  discard block
 block discarded – undo
585 585
 		$result->closeCursor();
586 586
 
587 587
 		if ($row === false) {
588
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
588
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
589 589
 		}
590 590
 
591
-		$row['principaluri'] = (string)$row['principaluri'];
591
+		$row['principaluri'] = (string) $row['principaluri'];
592 592
 		[, $name] = Uri\split($row['principaluri']);
593
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
593
+		$row['displayname'] = $row['displayname'].' '."($name)";
594 594
 		$components = [];
595 595
 		if ($row['components']) {
596 596
 			$components = explode(',', $row['components']);
@@ -599,13 +599,13 @@  discard block
 block discarded – undo
599 599
 			'id' => $row['id'],
600 600
 			'uri' => $row['publicuri'],
601 601
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
602
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
602
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
603 603
 			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
604
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
605
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
606
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
607
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => true,
608
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
604
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
605
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
606
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
607
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => true,
608
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
609 609
 		];
610 610
 
611 611
 		$calendar = $this->rowToCalendar($row, $calendar);
@@ -643,7 +643,7 @@  discard block
 block discarded – undo
643 643
 			return null;
644 644
 		}
645 645
 
646
-		$row['principaluri'] = (string)$row['principaluri'];
646
+		$row['principaluri'] = (string) $row['principaluri'];
647 647
 		$components = [];
648 648
 		if ($row['components']) {
649 649
 			$components = explode(',', $row['components']);
@@ -653,10 +653,10 @@  discard block
 block discarded – undo
653 653
 			'id' => $row['id'],
654 654
 			'uri' => $row['uri'],
655 655
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
656
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
656
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
657 657
 			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
658
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
659
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
658
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
659
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
660 660
 		];
661 661
 
662 662
 		$calendar = $this->rowToCalendar($row, $calendar);
@@ -692,7 +692,7 @@  discard block
 block discarded – undo
692 692
 			return null;
693 693
 		}
694 694
 
695
-		$row['principaluri'] = (string)$row['principaluri'];
695
+		$row['principaluri'] = (string) $row['principaluri'];
696 696
 		$components = [];
697 697
 		if ($row['components']) {
698 698
 			$components = explode(',', $row['components']);
@@ -702,10 +702,10 @@  discard block
 block discarded – undo
702 702
 			'id' => $row['id'],
703 703
 			'uri' => $row['uri'],
704 704
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
705
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
705
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
706 706
 			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?? 0,
707
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
708
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
707
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
708
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
709 709
 		];
710 710
 
711 711
 		$calendar = $this->rowToCalendar($row, $calendar);
@@ -740,14 +740,14 @@  discard block
 block discarded – undo
740 740
 			return null;
741 741
 		}
742 742
 
743
-		$row['principaluri'] = (string)$row['principaluri'];
743
+		$row['principaluri'] = (string) $row['principaluri'];
744 744
 		$subscription = [
745 745
 			'id' => $row['id'],
746 746
 			'uri' => $row['uri'],
747 747
 			'principaluri' => $row['principaluri'],
748 748
 			'source' => $row['source'],
749 749
 			'lastmodified' => $row['lastmodified'],
750
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
750
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
751 751
 			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
752 752
 		];
753 753
 
@@ -777,14 +777,14 @@  discard block
 block discarded – undo
777 777
 			return null;
778 778
 		}
779 779
 
780
-		$row['principaluri'] = (string)$row['principaluri'];
780
+		$row['principaluri'] = (string) $row['principaluri'];
781 781
 		$subscription = [
782 782
 			'id' => $row['id'],
783 783
 			'uri' => $row['uri'],
784 784
 			'principaluri' => $row['principaluri'],
785 785
 			'source' => $row['source'],
786 786
 			'lastmodified' => $row['lastmodified'],
787
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
787
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
788 788
 			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
789 789
 		];
790 790
 
@@ -822,7 +822,7 @@  discard block
 block discarded – undo
822 822
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
823 823
 		if (isset($properties[$sccs])) {
824 824
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
825
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
825
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
826 826
 			}
827 827
 			$values['components'] = implode(',', $properties[$sccs]->getValue());
828 828
 		} elseif (isset($properties['components'])) {
@@ -831,9 +831,9 @@  discard block
 block discarded – undo
831 831
 			$values['components'] = $properties['components'];
832 832
 		}
833 833
 
834
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
834
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
835 835
 		if (isset($properties[$transp])) {
836
-			$values['transparent'] = (int)($properties[$transp]->getValue() === 'transparent');
836
+			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
837 837
 		}
838 838
 
839 839
 		foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
@@ -842,7 +842,7 @@  discard block
 block discarded – undo
842 842
 			}
843 843
 		}
844 844
 
845
-		[$calendarId, $calendarData] = $this->atomic(function () use ($values) {
845
+		[$calendarId, $calendarData] = $this->atomic(function() use ($values) {
846 846
 			$query = $this->db->getQueryBuilder();
847 847
 			$query->insert('calendars');
848 848
 			foreach ($values as $column => $value) {
@@ -855,7 +855,7 @@  discard block
 block discarded – undo
855 855
 			return [$calendarId, $calendarData];
856 856
 		}, $this->db);
857 857
 
858
-		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
858
+		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int) $calendarId, $calendarData));
859 859
 
860 860
 		return $calendarId;
861 861
 	}
@@ -878,15 +878,15 @@  discard block
 block discarded – undo
878 878
 	 */
879 879
 	public function updateCalendar($calendarId, PropPatch $propPatch) {
880 880
 		$supportedProperties = array_keys($this->propertyMap);
881
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
881
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
882 882
 
883
-		$propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
883
+		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
884 884
 			$newValues = [];
885 885
 			foreach ($mutations as $propertyName => $propertyValue) {
886 886
 				switch ($propertyName) {
887
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
887
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp':
888 888
 						$fieldName = 'transparent';
889
-						$newValues[$fieldName] = (int)($propertyValue->getValue() === 'transparent');
889
+						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
890 890
 						break;
891 891
 					default:
892 892
 						$fieldName = $this->propertyMap[$propertyName][0];
@@ -894,7 +894,7 @@  discard block
 block discarded – undo
894 894
 						break;
895 895
 				}
896 896
 			}
897
-			[$calendarData, $shares] = $this->atomic(function () use ($calendarId, $newValues) {
897
+			[$calendarData, $shares] = $this->atomic(function() use ($calendarId, $newValues) {
898 898
 				$query = $this->db->getQueryBuilder();
899 899
 				$query->update('calendars');
900 900
 				foreach ($newValues as $fieldName => $value) {
@@ -923,7 +923,7 @@  discard block
 block discarded – undo
923 923
 	 * @return void
924 924
 	 */
925 925
 	public function deleteCalendar($calendarId, bool $forceDeletePermanently = false) {
926
-		$this->atomic(function () use ($calendarId, $forceDeletePermanently): void {
926
+		$this->atomic(function() use ($calendarId, $forceDeletePermanently): void {
927 927
 			// The calendar is deleted right away if this is either enforced by the caller
928 928
 			// or the special contacts birthday calendar or when the preference of an empty
929 929
 			// retention (0 seconds) is set, which signals a disabled trashbin.
@@ -986,7 +986,7 @@  discard block
 block discarded – undo
986 986
 	}
987 987
 
988 988
 	public function restoreCalendar(int $id): void {
989
-		$this->atomic(function () use ($id): void {
989
+		$this->atomic(function() use ($id): void {
990 990
 			$qb = $this->db->getQueryBuilder();
991 991
 			$update = $qb->update('calendars')
992 992
 				->set('deleted_at', $qb->createNamedParameter(null))
@@ -1060,7 +1060,7 @@  discard block
 block discarded – undo
1060 1060
 	 */
1061 1061
 	public function getLimitedCalendarObjects(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1062 1062
 		$query = $this->db->getQueryBuilder();
1063
-		$query->select(['id','uid', 'etag', 'uri', 'calendardata'])
1063
+		$query->select(['id', 'uid', 'etag', 'uri', 'calendardata'])
1064 1064
 			->from('calendarobjects')
1065 1065
 			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1066 1066
 			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
@@ -1138,11 +1138,11 @@  discard block
 block discarded – undo
1138 1138
 				'id' => $row['id'],
1139 1139
 				'uri' => $row['uri'],
1140 1140
 				'lastmodified' => $row['lastmodified'],
1141
-				'etag' => '"' . $row['etag'] . '"',
1141
+				'etag' => '"'.$row['etag'].'"',
1142 1142
 				'calendarid' => $row['calendarid'],
1143
-				'size' => (int)$row['size'],
1143
+				'size' => (int) $row['size'],
1144 1144
 				'component' => strtolower($row['componenttype']),
1145
-				'classification' => (int)$row['classification']
1145
+				'classification' => (int) $row['classification']
1146 1146
 			];
1147 1147
 		}
1148 1148
 		$stmt->closeCursor();
@@ -1165,13 +1165,13 @@  discard block
 block discarded – undo
1165 1165
 				'id' => $row['id'],
1166 1166
 				'uri' => $row['uri'],
1167 1167
 				'lastmodified' => $row['lastmodified'],
1168
-				'etag' => '"' . $row['etag'] . '"',
1169
-				'calendarid' => (int)$row['calendarid'],
1170
-				'calendartype' => (int)$row['calendartype'],
1171
-				'size' => (int)$row['size'],
1168
+				'etag' => '"'.$row['etag'].'"',
1169
+				'calendarid' => (int) $row['calendarid'],
1170
+				'calendartype' => (int) $row['calendartype'],
1171
+				'size' => (int) $row['size'],
1172 1172
 				'component' => strtolower($row['componenttype']),
1173
-				'classification' => (int)$row['classification'],
1174
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1173
+				'classification' => (int) $row['classification'],
1174
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int) $row['deleted_at'],
1175 1175
 			];
1176 1176
 		}
1177 1177
 		$stmt->closeCursor();
@@ -1204,13 +1204,13 @@  discard block
 block discarded – undo
1204 1204
 				'id' => $row['id'],
1205 1205
 				'uri' => $row['uri'],
1206 1206
 				'lastmodified' => $row['lastmodified'],
1207
-				'etag' => '"' . $row['etag'] . '"',
1207
+				'etag' => '"'.$row['etag'].'"',
1208 1208
 				'calendarid' => $row['calendarid'],
1209 1209
 				'calendaruri' => $row['calendaruri'],
1210
-				'size' => (int)$row['size'],
1210
+				'size' => (int) $row['size'],
1211 1211
 				'component' => strtolower($row['componenttype']),
1212
-				'classification' => (int)$row['classification'],
1213
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1212
+				'classification' => (int) $row['classification'],
1213
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int) $row['deleted_at'],
1214 1214
 			];
1215 1215
 		}
1216 1216
 		$stmt->closeCursor();
@@ -1236,7 +1236,7 @@  discard block
 block discarded – undo
1236 1236
 	 * @return array|null
1237 1237
 	 */
1238 1238
 	public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1239
-		$key = $calendarId . '::' . $objectUri . '::' . $calendarType;
1239
+		$key = $calendarId.'::'.$objectUri.'::'.$calendarType;
1240 1240
 		if (isset($this->cachedObjects[$key])) {
1241 1241
 			return $this->cachedObjects[$key];
1242 1242
 		}
@@ -1265,13 +1265,13 @@  discard block
 block discarded – undo
1265 1265
 			'uri' => $row['uri'],
1266 1266
 			'uid' => $row['uid'],
1267 1267
 			'lastmodified' => $row['lastmodified'],
1268
-			'etag' => '"' . $row['etag'] . '"',
1268
+			'etag' => '"'.$row['etag'].'"',
1269 1269
 			'calendarid' => $row['calendarid'],
1270
-			'size' => (int)$row['size'],
1270
+			'size' => (int) $row['size'],
1271 1271
 			'calendardata' => $this->readBlob($row['calendardata']),
1272 1272
 			'component' => strtolower($row['componenttype']),
1273
-			'classification' => (int)$row['classification'],
1274
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1273
+			'classification' => (int) $row['classification'],
1274
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int) $row['deleted_at'],
1275 1275
 		];
1276 1276
 	}
1277 1277
 
@@ -1313,12 +1313,12 @@  discard block
 block discarded – undo
1313 1313
 					'id' => $row['id'],
1314 1314
 					'uri' => $row['uri'],
1315 1315
 					'lastmodified' => $row['lastmodified'],
1316
-					'etag' => '"' . $row['etag'] . '"',
1316
+					'etag' => '"'.$row['etag'].'"',
1317 1317
 					'calendarid' => $row['calendarid'],
1318
-					'size' => (int)$row['size'],
1318
+					'size' => (int) $row['size'],
1319 1319
 					'calendardata' => $this->readBlob($row['calendardata']),
1320 1320
 					'component' => strtolower($row['componenttype']),
1321
-					'classification' => (int)$row['classification']
1321
+					'classification' => (int) $row['classification']
1322 1322
 				];
1323 1323
 			}
1324 1324
 			$result->closeCursor();
@@ -1350,7 +1350,7 @@  discard block
 block discarded – undo
1350 1350
 		$this->cachedObjects = [];
1351 1351
 		$extraData = $this->getDenormalizedData($calendarData);
1352 1352
 
1353
-		return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1353
+		return $this->atomic(function() use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1354 1354
 			// Try to detect duplicates
1355 1355
 			$qb = $this->db->getQueryBuilder();
1356 1356
 			$qb->select($qb->func()->count('*'))
@@ -1360,7 +1360,7 @@  discard block
 block discarded – undo
1360 1360
 				->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1361 1361
 				->andWhere($qb->expr()->isNull('deleted_at'));
1362 1362
 			$result = $qb->executeQuery();
1363
-			$count = (int)$result->fetchOne();
1363
+			$count = (int) $result->fetchOne();
1364 1364
 			$result->closeCursor();
1365 1365
 
1366 1366
 			if ($count !== 0) {
@@ -1420,7 +1420,7 @@  discard block
 block discarded – undo
1420 1420
 				// TODO: implement custom event for federated calendars
1421 1421
 			}
1422 1422
 
1423
-			return '"' . $extraData['etag'] . '"';
1423
+			return '"'.$extraData['etag'].'"';
1424 1424
 		}, $this->db);
1425 1425
 	}
1426 1426
 
@@ -1447,7 +1447,7 @@  discard block
 block discarded – undo
1447 1447
 		$this->cachedObjects = [];
1448 1448
 		$extraData = $this->getDenormalizedData($calendarData);
1449 1449
 
1450
-		return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1450
+		return $this->atomic(function() use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1451 1451
 			$query = $this->db->getQueryBuilder();
1452 1452
 			$query->update('calendarobjects')
1453 1453
 				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
@@ -1483,7 +1483,7 @@  discard block
 block discarded – undo
1483 1483
 				}
1484 1484
 			}
1485 1485
 
1486
-			return '"' . $extraData['etag'] . '"';
1486
+			return '"'.$extraData['etag'].'"';
1487 1487
 		}, $this->db);
1488 1488
 	}
1489 1489
 
@@ -1501,7 +1501,7 @@  discard block
 block discarded – undo
1501 1501
 	 */
1502 1502
 	public function moveCalendarObject(string $sourcePrincipalUri, int $sourceObjectId, string $targetPrincipalUri, int $targetCalendarId, string $tragetObjectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR): bool {
1503 1503
 		$this->cachedObjects = [];
1504
-		return $this->atomic(function () use ($sourcePrincipalUri, $sourceObjectId, $targetPrincipalUri, $targetCalendarId, $tragetObjectUri, $calendarType) {
1504
+		return $this->atomic(function() use ($sourcePrincipalUri, $sourceObjectId, $targetPrincipalUri, $targetCalendarId, $tragetObjectUri, $calendarType) {
1505 1505
 			$object = $this->getCalendarObjectById($sourcePrincipalUri, $sourceObjectId);
1506 1506
 			if (empty($object)) {
1507 1507
 				return false;
@@ -1558,7 +1558,7 @@  discard block
 block discarded – undo
1558 1558
 	 */
1559 1559
 	public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
1560 1560
 		$this->cachedObjects = [];
1561
-		$this->atomic(function () use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently): void {
1561
+		$this->atomic(function() use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently): void {
1562 1562
 			$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1563 1563
 
1564 1564
 			if ($data === null) {
@@ -1642,8 +1642,8 @@  discard block
 block discarded – undo
1642 1642
 	 */
1643 1643
 	public function restoreCalendarObject(array $objectData): void {
1644 1644
 		$this->cachedObjects = [];
1645
-		$this->atomic(function () use ($objectData): void {
1646
-			$id = (int)$objectData['id'];
1645
+		$this->atomic(function() use ($objectData): void {
1646
+			$id = (int) $objectData['id'];
1647 1647
 			$restoreUri = str_replace('-deleted.ics', '.ics', $objectData['uri']);
1648 1648
 			$targetObject = $this->getCalendarObject(
1649 1649
 				$objectData['calendarid'],
@@ -1673,17 +1673,17 @@  discard block
 block discarded – undo
1673 1673
 				// Welp, this should possibly not have happened, but let's ignore
1674 1674
 				return;
1675 1675
 			}
1676
-			$this->addChanges($row['calendarid'], [$row['uri']], 1, (int)$row['calendartype']);
1676
+			$this->addChanges($row['calendarid'], [$row['uri']], 1, (int) $row['calendartype']);
1677 1677
 
1678
-			$calendarRow = $this->getCalendarById((int)$row['calendarid']);
1678
+			$calendarRow = $this->getCalendarById((int) $row['calendarid']);
1679 1679
 			if ($calendarRow === null) {
1680 1680
 				throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
1681 1681
 			}
1682 1682
 			$this->dispatcher->dispatchTyped(
1683 1683
 				new CalendarObjectRestoredEvent(
1684
-					(int)$objectData['calendarid'],
1684
+					(int) $objectData['calendarid'],
1685 1685
 					$calendarRow,
1686
-					$this->getShares((int)$row['calendarid']),
1686
+					$this->getShares((int) $row['calendarid']),
1687 1687
 					$row
1688 1688
 				)
1689 1689
 			);
@@ -1802,19 +1802,19 @@  discard block
 block discarded – undo
1802 1802
 				try {
1803 1803
 					$matches = $this->validateFilterForObject($row, $filters);
1804 1804
 				} catch (ParseException $ex) {
1805
-					$this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1805
+					$this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri'], [
1806 1806
 						'app' => 'dav',
1807 1807
 						'exception' => $ex,
1808 1808
 					]);
1809 1809
 					continue;
1810 1810
 				} catch (InvalidDataException $ex) {
1811
-					$this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1811
+					$this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri'], [
1812 1812
 						'app' => 'dav',
1813 1813
 						'exception' => $ex,
1814 1814
 					]);
1815 1815
 					continue;
1816 1816
 				} catch (MaxInstancesExceededException $ex) {
1817
-					$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'], [
1817
+					$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'], [
1818 1818
 						'app' => 'dav',
1819 1819
 						'exception' => $ex,
1820 1820
 					]);
@@ -1826,7 +1826,7 @@  discard block
 block discarded – undo
1826 1826
 				}
1827 1827
 			}
1828 1828
 			$result[] = $row['uri'];
1829
-			$key = $calendarId . '::' . $row['uri'] . '::' . $calendarType;
1829
+			$key = $calendarId.'::'.$row['uri'].'::'.$calendarType;
1830 1830
 			$this->cachedObjects[$key] = $this->rowToCalendarObject($row);
1831 1831
 		}
1832 1832
 
@@ -1845,7 +1845,7 @@  discard block
 block discarded – undo
1845 1845
 	 * @return array
1846 1846
 	 */
1847 1847
 	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1848
-		return $this->atomic(function () use ($principalUri, $filters, $limit, $offset) {
1848
+		return $this->atomic(function() use ($principalUri, $filters, $limit, $offset) {
1849 1849
 			$calendars = $this->getCalendarsForUser($principalUri);
1850 1850
 			$ownCalendars = [];
1851 1851
 			$sharedCalendars = [];
@@ -1937,7 +1937,7 @@  discard block
 block discarded – undo
1937 1937
 				->andWhere($compExpr)
1938 1938
 				->andWhere($propParamExpr)
1939 1939
 				->andWhere($query->expr()->iLike('i.value',
1940
-					$query->createNamedParameter('%' . $this->db->escapeLikeParameter($filters['search-term']) . '%')))
1940
+					$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')))
1941 1941
 				->andWhere($query->expr()->isNull('deleted_at'));
1942 1942
 
1943 1943
 			if ($offset) {
@@ -1951,7 +1951,7 @@  discard block
 block discarded – undo
1951 1951
 
1952 1952
 			$result = [];
1953 1953
 			while ($row = $stmt->fetch()) {
1954
-				$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1954
+				$path = $uriMapper[$row['calendarid']].'/'.$row['uri'];
1955 1955
 				if (!in_array($path, $result)) {
1956 1956
 					$result[] = $path;
1957 1957
 				}
@@ -2021,7 +2021,7 @@  discard block
 block discarded – undo
2021 2021
 		if ($pattern !== '') {
2022 2022
 			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
2023 2023
 				$outerQuery->createNamedParameter('%'
2024
-					. $this->db->escapeLikeParameter($pattern) . '%')));
2024
+					. $this->db->escapeLikeParameter($pattern).'%')));
2025 2025
 		}
2026 2026
 
2027 2027
 		$start = null;
@@ -2073,7 +2073,7 @@  discard block
 block discarded – undo
2073 2073
 		// For the pagination with hasLimit and hasTimeRange, a stable ordering is helpful.
2074 2074
 		$outerQuery->addOrderBy('id');
2075 2075
 
2076
-		$offset = (int)$offset;
2076
+		$offset = (int) $offset;
2077 2077
 		$outerQuery->setFirstResult($offset);
2078 2078
 
2079 2079
 		$calendarObjects = [];
@@ -2094,7 +2094,7 @@  discard block
 block discarded – undo
2094 2094
 			 *
2095 2095
 			 * 25 rows and 3 retries is entirely arbitrary.
2096 2096
 			 */
2097
-			$maxResults = (int)max($limit, 25);
2097
+			$maxResults = (int) max($limit, 25);
2098 2098
 			$outerQuery->setMaxResults($maxResults);
2099 2099
 
2100 2100
 			for ($attempt = $objectsCount = 0; $attempt < 3 && $objectsCount < $limit; $attempt++) {
@@ -2108,7 +2108,7 @@  discard block
 block discarded – undo
2108 2108
 			$calendarObjects = $this->searchCalendarObjects($outerQuery, $start, $end);
2109 2109
 		}
2110 2110
 
2111
-		$calendarObjects = array_map(function ($o) use ($options) {
2111
+		$calendarObjects = array_map(function($o) use ($options) {
2112 2112
 			$calendarData = Reader::read($o['calendardata']);
2113 2113
 
2114 2114
 			// Expand recurrences if an explicit time range is requested
@@ -2136,16 +2136,16 @@  discard block
 block discarded – undo
2136 2136
 				'type' => $o['componenttype'],
2137 2137
 				'uid' => $o['uid'],
2138 2138
 				'uri' => $o['uri'],
2139
-				'objects' => array_map(function ($c) {
2139
+				'objects' => array_map(function($c) {
2140 2140
 					return $this->transformSearchData($c);
2141 2141
 				}, $objects),
2142
-				'timezones' => array_map(function ($c) {
2142
+				'timezones' => array_map(function($c) {
2143 2143
 					return $this->transformSearchData($c);
2144 2144
 				}, $timezones),
2145 2145
 			];
2146 2146
 		}, $calendarObjects);
2147 2147
 
2148
-		usort($calendarObjects, function (array $a, array $b) {
2148
+		usort($calendarObjects, function(array $a, array $b) {
2149 2149
 			/** @var DateTimeImmutable $startA */
2150 2150
 			$startA = $a['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2151 2151
 			/** @var DateTimeImmutable $startB */
@@ -2190,7 +2190,7 @@  discard block
 block discarded – undo
2190 2190
 					'time-range' => null,
2191 2191
 				]);
2192 2192
 			} catch (MaxInstancesExceededException $ex) {
2193
-				$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'], [
2193
+				$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'], [
2194 2194
 					'app' => 'dav',
2195 2195
 					'exception' => $ex,
2196 2196
 				]);
@@ -2221,7 +2221,7 @@  discard block
 block discarded – undo
2221 2221
 		/** @var Component[] $subComponents */
2222 2222
 		$subComponents = $comp->getComponents();
2223 2223
 		/** @var Property[] $properties */
2224
-		$properties = array_filter($comp->children(), function ($c) {
2224
+		$properties = array_filter($comp->children(), function($c) {
2225 2225
 			return $c instanceof Property;
2226 2226
 		});
2227 2227
 		$validationRules = $comp->getValidationRules();
@@ -2289,7 +2289,7 @@  discard block
 block discarded – undo
2289 2289
 		array $searchParameters,
2290 2290
 		array $options = [],
2291 2291
 	): array {
2292
-		return $this->atomic(function () use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
2292
+		return $this->atomic(function() use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
2293 2293
 			$escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
2294 2294
 
2295 2295
 			$calendarObjectIdQuery = $this->db->getQueryBuilder();
@@ -2301,7 +2301,7 @@  discard block
 block discarded – undo
2301 2301
 			$subscriptions = $this->getSubscriptionsForUser($principalUri);
2302 2302
 			foreach ($calendars as $calendar) {
2303 2303
 				$calendarAnd = $calendarObjectIdQuery->expr()->andX(
2304
-					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])),
2304
+					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int) $calendar['id'])),
2305 2305
 					$calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)),
2306 2306
 				);
2307 2307
 
@@ -2315,7 +2315,7 @@  discard block
 block discarded – undo
2315 2315
 			}
2316 2316
 			foreach ($subscriptions as $subscription) {
2317 2317
 				$subscriptionAnd = $calendarObjectIdQuery->expr()->andX(
2318
-					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])),
2318
+					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int) $subscription['id'])),
2319 2319
 					$calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)),
2320 2320
 				);
2321 2321
 
@@ -2364,7 +2364,7 @@  discard block
 block discarded – undo
2364 2364
 				if (!$escapePattern) {
2365 2365
 					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
2366 2366
 				} else {
2367
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
2367
+					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%'.$this->db->escapeLikeParameter($pattern).'%')));
2368 2368
 				}
2369 2369
 			}
2370 2370
 
@@ -2392,7 +2392,7 @@  discard block
 block discarded – undo
2392 2392
 			$result = $calendarObjectIdQuery->executeQuery();
2393 2393
 			$matches = [];
2394 2394
 			while (($row = $result->fetch()) !== false) {
2395
-				$matches[] = (int)$row['objectid'];
2395
+				$matches[] = (int) $row['objectid'];
2396 2396
 			}
2397 2397
 			$result->closeCursor();
2398 2398
 
@@ -2404,8 +2404,8 @@  discard block
 block discarded – undo
2404 2404
 			$result = $query->executeQuery();
2405 2405
 			$calendarObjects = [];
2406 2406
 			while (($array = $result->fetch()) !== false) {
2407
-				$array['calendarid'] = (int)$array['calendarid'];
2408
-				$array['calendartype'] = (int)$array['calendartype'];
2407
+				$array['calendarid'] = (int) $array['calendarid'];
2408
+				$array['calendartype'] = (int) $array['calendartype'];
2409 2409
 				$array['calendardata'] = $this->readBlob($array['calendardata']);
2410 2410
 
2411 2411
 				$calendarObjects[] = $array;
@@ -2451,7 +2451,7 @@  discard block
 block discarded – undo
2451 2451
 		$row = $stmt->fetch();
2452 2452
 		$stmt->closeCursor();
2453 2453
 		if ($row) {
2454
-			return $row['calendaruri'] . '/' . $row['objecturi'];
2454
+			return $row['calendaruri'].'/'.$row['objecturi'];
2455 2455
 		}
2456 2456
 
2457 2457
 		return null;
@@ -2477,14 +2477,14 @@  discard block
 block discarded – undo
2477 2477
 			'id' => $row['id'],
2478 2478
 			'uri' => $row['uri'],
2479 2479
 			'lastmodified' => $row['lastmodified'],
2480
-			'etag' => '"' . $row['etag'] . '"',
2480
+			'etag' => '"'.$row['etag'].'"',
2481 2481
 			'calendarid' => $row['calendarid'],
2482 2482
 			'calendaruri' => $row['calendaruri'],
2483
-			'size' => (int)$row['size'],
2483
+			'size' => (int) $row['size'],
2484 2484
 			'calendardata' => $this->readBlob($row['calendardata']),
2485 2485
 			'component' => strtolower($row['componenttype']),
2486
-			'classification' => (int)$row['classification'],
2487
-			'deleted_at' => isset($row['deleted_at']) ? ((int)$row['deleted_at']) : null,
2486
+			'classification' => (int) $row['classification'],
2487
+			'deleted_at' => isset($row['deleted_at']) ? ((int) $row['deleted_at']) : null,
2488 2488
 		];
2489 2489
 	}
2490 2490
 
@@ -2546,9 +2546,9 @@  discard block
 block discarded – undo
2546 2546
 	 * @return ?array
2547 2547
 	 */
2548 2548
 	public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2549
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2549
+		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars' : 'calendarsubscriptions';
2550 2550
 
2551
-		return $this->atomic(function () use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
2551
+		return $this->atomic(function() use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
2552 2552
 			// Current synctoken
2553 2553
 			$qb = $this->db->getQueryBuilder();
2554 2554
 			$qb->select('synctoken')
@@ -2599,7 +2599,7 @@  discard block
 block discarded – undo
2599 2599
 				while ($entry = $stmt->fetch(\PDO::FETCH_NUM)) {
2600 2600
 					// assign uri (column 0) to appropriate mutation based on operation (column 1)
2601 2601
 					// forced (int) is needed as doctrine with OCI returns the operation field as string not integer
2602
-					match ((int)$entry[1]) {
2602
+					match ((int) $entry[1]) {
2603 2603
 						1 => $result['added'][] = $entry[0],
2604 2604
 						2 => $result['modified'][] = $entry[0],
2605 2605
 						3 => $result['deleted'][] = $entry[0],
@@ -2670,7 +2670,7 @@  discard block
 block discarded – undo
2670 2670
 				'source' => $row['source'],
2671 2671
 				'lastmodified' => $row['lastmodified'],
2672 2672
 
2673
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2673
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2674 2674
 				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
2675 2675
 			];
2676 2676
 
@@ -2714,7 +2714,7 @@  discard block
 block discarded – undo
2714 2714
 			}
2715 2715
 		}
2716 2716
 
2717
-		[$subscriptionId, $subscriptionRow] = $this->atomic(function () use ($values) {
2717
+		[$subscriptionId, $subscriptionRow] = $this->atomic(function() use ($values) {
2718 2718
 			$valuesToInsert = [];
2719 2719
 			$query = $this->db->getQueryBuilder();
2720 2720
 			foreach (array_keys($values) as $name) {
@@ -2755,7 +2755,7 @@  discard block
 block discarded – undo
2755 2755
 		$supportedProperties = array_keys($this->subscriptionPropertyMap);
2756 2756
 		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
2757 2757
 
2758
-		$propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2758
+		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
2759 2759
 			$newValues = [];
2760 2760
 
2761 2761
 			foreach ($mutations as $propertyName => $propertyValue) {
@@ -2767,7 +2767,7 @@  discard block
 block discarded – undo
2767 2767
 				}
2768 2768
 			}
2769 2769
 
2770
-			$subscriptionRow = $this->atomic(function () use ($subscriptionId, $newValues) {
2770
+			$subscriptionRow = $this->atomic(function() use ($subscriptionId, $newValues) {
2771 2771
 				$query = $this->db->getQueryBuilder();
2772 2772
 				$query->update('calendarsubscriptions')
2773 2773
 					->set('lastmodified', $query->createNamedParameter(time()));
@@ -2780,7 +2780,7 @@  discard block
 block discarded – undo
2780 2780
 				return $this->getSubscriptionById($subscriptionId);
2781 2781
 			}, $this->db);
2782 2782
 
2783
-			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2783
+			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int) $subscriptionId, $subscriptionRow, [], $mutations));
2784 2784
 
2785 2785
 			return true;
2786 2786
 		});
@@ -2793,7 +2793,7 @@  discard block
 block discarded – undo
2793 2793
 	 * @return void
2794 2794
 	 */
2795 2795
 	public function deleteSubscription($subscriptionId) {
2796
-		$this->atomic(function () use ($subscriptionId): void {
2796
+		$this->atomic(function() use ($subscriptionId): void {
2797 2797
 			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2798 2798
 
2799 2799
 			$query = $this->db->getQueryBuilder();
@@ -2818,7 +2818,7 @@  discard block
 block discarded – undo
2818 2818
 				->executeStatement();
2819 2819
 
2820 2820
 			if ($subscriptionRow) {
2821
-				$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2821
+				$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int) $subscriptionId, $subscriptionRow, []));
2822 2822
 			}
2823 2823
 		}, $this->db);
2824 2824
 	}
@@ -2857,8 +2857,8 @@  discard block
 block discarded – undo
2857 2857
 			'uri' => $row['uri'],
2858 2858
 			'calendardata' => $row['calendardata'],
2859 2859
 			'lastmodified' => $row['lastmodified'],
2860
-			'etag' => '"' . $row['etag'] . '"',
2861
-			'size' => (int)$row['size'],
2860
+			'etag' => '"'.$row['etag'].'"',
2861
+			'size' => (int) $row['size'],
2862 2862
 		];
2863 2863
 	}
2864 2864
 
@@ -2886,8 +2886,8 @@  discard block
 block discarded – undo
2886 2886
 				'calendardata' => $row['calendardata'],
2887 2887
 				'uri' => $row['uri'],
2888 2888
 				'lastmodified' => $row['lastmodified'],
2889
-				'etag' => '"' . $row['etag'] . '"',
2890
-				'size' => (int)$row['size'],
2889
+				'etag' => '"'.$row['etag'].'"',
2890
+				'size' => (int) $row['size'],
2891 2891
 			];
2892 2892
 		}
2893 2893
 		$stmt->closeCursor();
@@ -2929,8 +2929,8 @@  discard block
 block discarded – undo
2929 2929
 		if ($count === 0) {
2930 2930
 			return;
2931 2931
 		}
2932
-		$ids = array_map(static function (array $id) {
2933
-			return (int)$id[0];
2932
+		$ids = array_map(static function(array $id) {
2933
+			return (int) $id[0];
2934 2934
 		}, $result->fetchAll(\PDO::FETCH_NUM));
2935 2935
 		$result->closeCursor();
2936 2936
 
@@ -2983,15 +2983,15 @@  discard block
 block discarded – undo
2983 2983
 	 */
2984 2984
 	protected function addChanges(int $calendarId, array $objectUris, int $operation, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
2985 2985
 		$this->cachedObjects = [];
2986
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2986
+		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars' : 'calendarsubscriptions';
2987 2987
 
2988
-		$this->atomic(function () use ($calendarId, $objectUris, $operation, $calendarType, $table): void {
2988
+		$this->atomic(function() use ($calendarId, $objectUris, $operation, $calendarType, $table): void {
2989 2989
 			$query = $this->db->getQueryBuilder();
2990 2990
 			$query->select('synctoken')
2991 2991
 				->from($table)
2992 2992
 				->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2993 2993
 			$result = $query->executeQuery();
2994
-			$syncToken = (int)$result->fetchOne();
2994
+			$syncToken = (int) $result->fetchOne();
2995 2995
 			$result->closeCursor();
2996 2996
 
2997 2997
 			$query = $this->db->getQueryBuilder();
@@ -3020,7 +3020,7 @@  discard block
 block discarded – undo
3020 3020
 	public function restoreChanges(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
3021 3021
 		$this->cachedObjects = [];
3022 3022
 
3023
-		$this->atomic(function () use ($calendarId, $calendarType): void {
3023
+		$this->atomic(function() use ($calendarId, $calendarType): void {
3024 3024
 			$qbAdded = $this->db->getQueryBuilder();
3025 3025
 			$qbAdded->select('uri')
3026 3026
 				->from('calendarobjects')
@@ -3050,7 +3050,7 @@  discard block
 block discarded – undo
3050 3050
 					)
3051 3051
 				);
3052 3052
 			$resultDeleted = $qbDeleted->executeQuery();
3053
-			$deletedUris = array_map(function (string $uri) {
3053
+			$deletedUris = array_map(function(string $uri) {
3054 3054
 				return str_replace('-deleted.ics', '.ics', $uri);
3055 3055
 			}, $resultDeleted->fetchAll(\PDO::FETCH_COLUMN));
3056 3056
 			$resultDeleted->closeCursor();
@@ -3095,7 +3095,7 @@  discard block
 block discarded – undo
3095 3095
 				// Track first component type and uid
3096 3096
 				if ($uid === null) {
3097 3097
 					$componentType = $component->name;
3098
-					$uid = (string)$component->UID;
3098
+					$uid = (string) $component->UID;
3099 3099
 				}
3100 3100
 			}
3101 3101
 		}
@@ -3186,11 +3186,11 @@  discard block
 block discarded – undo
3186 3186
 	 * @param list<string> $remove
3187 3187
 	 */
3188 3188
 	public function updateShares(IShareable $shareable, array $add, array $remove): void {
3189
-		$this->atomic(function () use ($shareable, $add, $remove): void {
3189
+		$this->atomic(function() use ($shareable, $add, $remove): void {
3190 3190
 			$calendarId = $shareable->getResourceId();
3191 3191
 			$calendarRow = $this->getCalendarById($calendarId);
3192 3192
 			if ($calendarRow === null) {
3193
-				throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $calendarId);
3193
+				throw new \RuntimeException('Trying to update shares for non-existing calendar: '.$calendarId);
3194 3194
 			}
3195 3195
 			$oldShares = $this->getShares($calendarId);
3196 3196
 
@@ -3221,7 +3221,7 @@  discard block
 block discarded – undo
3221 3221
 	 * @return string|null
3222 3222
 	 */
3223 3223
 	public function setPublishStatus($value, $calendar) {
3224
-		return $this->atomic(function () use ($value, $calendar) {
3224
+		return $this->atomic(function() use ($value, $calendar) {
3225 3225
 			$calendarId = $calendar->getResourceId();
3226 3226
 			$calendarData = $this->getCalendarById($calendarId);
3227 3227
 
@@ -3288,7 +3288,7 @@  discard block
 block discarded – undo
3288 3288
 	 */
3289 3289
 	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
3290 3290
 		$this->cachedObjects = [];
3291
-		$this->atomic(function () use ($calendarId, $objectUri, $calendarData, $calendarType): void {
3291
+		$this->atomic(function() use ($calendarId, $objectUri, $calendarData, $calendarType): void {
3292 3292
 			$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
3293 3293
 
3294 3294
 			try {
@@ -3360,7 +3360,7 @@  discard block
 block discarded – undo
3360 3360
 	 * deletes all birthday calendars
3361 3361
 	 */
3362 3362
 	public function deleteAllBirthdayCalendars() {
3363
-		$this->atomic(function (): void {
3363
+		$this->atomic(function(): void {
3364 3364
 			$query = $this->db->getQueryBuilder();
3365 3365
 			$result = $query->select(['id'])->from('calendars')
3366 3366
 				->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
@@ -3380,7 +3380,7 @@  discard block
 block discarded – undo
3380 3380
 	 * @param $subscriptionId
3381 3381
 	 */
3382 3382
 	public function purgeAllCachedEventsForSubscription($subscriptionId) {
3383
-		$this->atomic(function () use ($subscriptionId): void {
3383
+		$this->atomic(function() use ($subscriptionId): void {
3384 3384
 			$query = $this->db->getQueryBuilder();
3385 3385
 			$query->select('uri')
3386 3386
 				->from('calendarobjects')
@@ -3426,7 +3426,7 @@  discard block
 block discarded – undo
3426 3426
 			return;
3427 3427
 		}
3428 3428
 
3429
-		$this->atomic(function () use ($subscriptionId, $calendarObjectIds, $calendarObjectUris): void {
3429
+		$this->atomic(function() use ($subscriptionId, $calendarObjectIds, $calendarObjectUris): void {
3430 3430
 			foreach (array_chunk($calendarObjectIds, 1000) as $chunk) {
3431 3431
 				$query = $this->db->getQueryBuilder();
3432 3432
 				$query->delete($this->dbObjectPropertiesTable)
@@ -3519,10 +3519,10 @@  discard block
 block discarded – undo
3519 3519
 		$result->closeCursor();
3520 3520
 
3521 3521
 		if (!isset($objectIds['id'])) {
3522
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
3522
+			throw new \InvalidArgumentException('Calendarobject does not exists: '.$uri);
3523 3523
 		}
3524 3524
 
3525
-		return (int)$objectIds['id'];
3525
+		return (int) $objectIds['id'];
3526 3526
 	}
3527 3527
 
3528 3528
 	/**
@@ -3538,7 +3538,7 @@  discard block
 block discarded – undo
3538 3538
 			->from('calendarchanges');
3539 3539
 
3540 3540
 		$result = $query->executeQuery();
3541
-		$maxId = (int)$result->fetchOne();
3541
+		$maxId = (int) $result->fetchOne();
3542 3542
 		$result->closeCursor();
3543 3543
 		if (!$maxId || $maxId < $keep) {
3544 3544
 			return 0;
@@ -3576,8 +3576,8 @@  discard block
 block discarded – undo
3576 3576
 	 *
3577 3577
 	 */
3578 3578
 	private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
3579
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
3580
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
3579
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
3580
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
3581 3581
 		if (isset($calendarInfo[$ownerPrincipalKey])) {
3582 3582
 			$uri = $calendarInfo[$ownerPrincipalKey];
3583 3583
 		} else {
@@ -3686,10 +3686,10 @@  discard block
 block discarded – undo
3686 3686
 	}
3687 3687
 
3688 3688
 	public function unshare(IShareable $shareable, string $principal): void {
3689
-		$this->atomic(function () use ($shareable, $principal): void {
3689
+		$this->atomic(function() use ($shareable, $principal): void {
3690 3690
 			$calendarData = $this->getCalendarById($shareable->getResourceId());
3691 3691
 			if ($calendarData === null) {
3692
-				throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $shareable->getResourceId());
3692
+				throw new \RuntimeException('Trying to update shares for non-existing calendar: '.$shareable->getResourceId());
3693 3693
 			}
3694 3694
 
3695 3695
 			$oldShares = $this->getShares($shareable->getResourceId());
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Calendar.php 2 patches
Indentation   +377 added lines, -377 removed lines patch added patch discarded remove patch
@@ -31,381 +31,381 @@
 block discarded – undo
31 31
  * @property CalDavBackend $caldavBackend
32 32
  */
33 33
 class Calendar extends \Sabre\CalDAV\Calendar implements IRestorable, IShareable, IMoveTarget {
34
-	protected IL10N $l10n;
35
-	private bool $useTrashbin = true;
36
-
37
-	public function __construct(
38
-		BackendInterface $caldavBackend,
39
-		array $calendarInfo,
40
-		IL10N $l10n,
41
-		private IConfig $config,
42
-		private LoggerInterface $logger,
43
-	) {
44
-		// Convert deletion date to ISO8601 string
45
-		if (isset($calendarInfo[TrashbinPlugin::PROPERTY_DELETED_AT])) {
46
-			$calendarInfo[TrashbinPlugin::PROPERTY_DELETED_AT] = (new DateTimeImmutable())
47
-				->setTimestamp($calendarInfo[TrashbinPlugin::PROPERTY_DELETED_AT])
48
-				->format(DateTimeInterface::ATOM);
49
-		}
50
-
51
-		parent::__construct($caldavBackend, $calendarInfo);
52
-
53
-		if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI && strcasecmp($this->calendarInfo['{DAV:}displayname'], 'Contact birthdays') === 0) {
54
-			$this->calendarInfo['{DAV:}displayname'] = $l10n->t('Contact birthdays');
55
-		}
56
-		if ($this->getName() === CalDavBackend::PERSONAL_CALENDAR_URI
57
-			&& $this->calendarInfo['{DAV:}displayname'] === CalDavBackend::PERSONAL_CALENDAR_NAME) {
58
-			$this->calendarInfo['{DAV:}displayname'] = $l10n->t('Personal');
59
-		}
60
-		$this->l10n = $l10n;
61
-	}
62
-
63
-	public function getUri(): string {
64
-		return $this->calendarInfo['uri'];
65
-	}
66
-
67
-	protected function getCalendarType(): int {
68
-		return CalDavBackend::CALENDAR_TYPE_CALENDAR;
69
-	}
70
-
71
-	/**
72
-	 * {@inheritdoc}
73
-	 * @throws Forbidden
74
-	 */
75
-	public function updateShares(array $add, array $remove): void {
76
-		if ($this->isShared()) {
77
-			throw new Forbidden();
78
-		}
79
-		$this->caldavBackend->updateShares($this, $add, $remove);
80
-	}
81
-
82
-	/**
83
-	 * Returns the list of people whom this resource is shared with.
84
-	 *
85
-	 * Every element in this array should have the following properties:
86
-	 *   * href - Often a mailto: address
87
-	 *   * commonName - Optional, for example a first + last name
88
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
89
-	 *   * readOnly - boolean
90
-	 *   * summary - Optional, a description for the share
91
-	 *
92
-	 * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
93
-	 */
94
-	public function getShares(): array {
95
-		if ($this->isShared()) {
96
-			return [];
97
-		}
98
-		return $this->caldavBackend->getShares($this->getResourceId());
99
-	}
100
-
101
-	public function getResourceId(): int {
102
-		return $this->calendarInfo['id'];
103
-	}
104
-
105
-	/**
106
-	 * @return string
107
-	 */
108
-	public function getPrincipalURI() {
109
-		return $this->calendarInfo['principaluri'];
110
-	}
111
-
112
-	/**
113
-	 * @param int $resourceId
114
-	 * @param list<array{privilege: string, principal: string, protected: bool}> $acl
115
-	 * @return list<array{privilege: string, principal: ?string, protected: bool}>
116
-	 */
117
-	public function getACL() {
118
-		$acl = [
119
-			[
120
-				'privilege' => '{DAV:}read',
121
-				'principal' => $this->getOwner(),
122
-				'protected' => true,
123
-			],
124
-			[
125
-				'privilege' => '{DAV:}read',
126
-				'principal' => $this->getOwner() . '/calendar-proxy-write',
127
-				'protected' => true,
128
-			],
129
-			[
130
-				'privilege' => '{DAV:}read',
131
-				'principal' => $this->getOwner() . '/calendar-proxy-read',
132
-				'protected' => true,
133
-			],
134
-		];
135
-
136
-		if ($this->getName() !== BirthdayService::BIRTHDAY_CALENDAR_URI) {
137
-			$acl[] = [
138
-				'privilege' => '{DAV:}write',
139
-				'principal' => $this->getOwner(),
140
-				'protected' => true,
141
-			];
142
-			$acl[] = [
143
-				'privilege' => '{DAV:}write',
144
-				'principal' => $this->getOwner() . '/calendar-proxy-write',
145
-				'protected' => true,
146
-			];
147
-		} else {
148
-			$acl[] = [
149
-				'privilege' => '{DAV:}write-properties',
150
-				'principal' => $this->getOwner(),
151
-				'protected' => true,
152
-			];
153
-			$acl[] = [
154
-				'privilege' => '{DAV:}write-properties',
155
-				'principal' => $this->getOwner() . '/calendar-proxy-write',
156
-				'protected' => true,
157
-			];
158
-		}
159
-
160
-		$acl[] = [
161
-			'privilege' => '{DAV:}write-properties',
162
-			'principal' => $this->getOwner() . '/calendar-proxy-read',
163
-			'protected' => true,
164
-		];
165
-
166
-		if (!$this->isShared()) {
167
-			return $acl;
168
-		}
169
-
170
-		if ($this->getOwner() !== parent::getOwner()) {
171
-			$acl[] = [
172
-				'privilege' => '{DAV:}read',
173
-				'principal' => parent::getOwner(),
174
-				'protected' => true,
175
-			];
176
-			if ($this->canWrite()) {
177
-				$acl[] = [
178
-					'privilege' => '{DAV:}write',
179
-					'principal' => parent::getOwner(),
180
-					'protected' => true,
181
-				];
182
-			} else {
183
-				$acl[] = [
184
-					'privilege' => '{DAV:}write-properties',
185
-					'principal' => parent::getOwner(),
186
-					'protected' => true,
187
-				];
188
-			}
189
-		}
190
-		if ($this->isPublic()) {
191
-			$acl[] = [
192
-				'privilege' => '{DAV:}read',
193
-				'principal' => 'principals/system/public',
194
-				'protected' => true,
195
-			];
196
-		}
197
-
198
-		$acl = $this->caldavBackend->applyShareAcl($this->getResourceId(), $acl);
199
-		$allowedPrincipals = [
200
-			$this->getOwner(),
201
-			$this->getOwner() . '/calendar-proxy-read',
202
-			$this->getOwner() . '/calendar-proxy-write',
203
-			parent::getOwner(),
204
-			'principals/system/public',
205
-		];
206
-		/** @var list<array{privilege: string, principal: string, protected: bool}> $acl */
207
-		$acl = array_filter($acl, function (array $rule) use ($allowedPrincipals): bool {
208
-			return \in_array($rule['principal'], $allowedPrincipals, true);
209
-		});
210
-		return $acl;
211
-	}
212
-
213
-	public function getChildACL() {
214
-		return $this->getACL();
215
-	}
216
-
217
-	public function getOwner(): ?string {
218
-		if (isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) {
219
-			return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'];
220
-		}
221
-		return parent::getOwner();
222
-	}
223
-
224
-	public function delete() {
225
-		if ($this->isShared()) {
226
-			$this->caldavBackend->unshare($this, 'principal:' . $this->getPrincipalURI());
227
-			return;
228
-		}
229
-
230
-		// Remember when a user deleted their birthday calendar
231
-		// in order to not regenerate it on the next contacts change
232
-		if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) {
233
-			$principalURI = $this->getPrincipalURI();
234
-			$userId = substr($principalURI, 17);
235
-
236
-			$this->config->setUserValue($userId, 'dav', 'generateBirthdayCalendar', 'no');
237
-		}
238
-
239
-		$this->caldavBackend->deleteCalendar(
240
-			$this->calendarInfo['id'],
241
-			!$this->useTrashbin
242
-		);
243
-	}
244
-
245
-	public function propPatch(PropPatch $propPatch) {
246
-		// parent::propPatch will only update calendars table
247
-		// if calendar is shared, changes have to be made to the properties table
248
-		if (!$this->isShared()) {
249
-			parent::propPatch($propPatch);
250
-		}
251
-	}
252
-
253
-	public function getChild($name) {
254
-		$obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name, $this->getCalendarType());
255
-
256
-		if (!$obj) {
257
-			throw new NotFound('Calendar object not found');
258
-		}
259
-
260
-		if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
261
-			throw new NotFound('Calendar object not found');
262
-		}
263
-
264
-		$obj['acl'] = $this->getChildACL();
265
-
266
-		return new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
267
-	}
268
-
269
-	public function getChildren() {
270
-		$objs = $this->caldavBackend->getCalendarObjects($this->calendarInfo['id'], $this->getCalendarType());
271
-		$children = [];
272
-		foreach ($objs as $obj) {
273
-			if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
274
-				continue;
275
-			}
276
-			$obj['acl'] = $this->getChildACL();
277
-			$children[] = new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
278
-		}
279
-		return $children;
280
-	}
281
-
282
-	public function getMultipleChildren(array $paths) {
283
-		$objs = $this->caldavBackend->getMultipleCalendarObjects($this->calendarInfo['id'], $paths, $this->getCalendarType());
284
-		$children = [];
285
-		foreach ($objs as $obj) {
286
-			if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
287
-				continue;
288
-			}
289
-			$obj['acl'] = $this->getChildACL();
290
-			$children[] = new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
291
-		}
292
-		return $children;
293
-	}
294
-
295
-	public function childExists($name) {
296
-		$obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name, $this->getCalendarType());
297
-		if (!$obj) {
298
-			return false;
299
-		}
300
-		if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
301
-			return false;
302
-		}
303
-
304
-		return true;
305
-	}
306
-
307
-	public function calendarQuery(array $filters) {
308
-		$uris = $this->caldavBackend->calendarQuery($this->calendarInfo['id'], $filters, $this->getCalendarType());
309
-		if ($this->isShared()) {
310
-			return array_filter($uris, function ($uri) {
311
-				return $this->childExists($uri);
312
-			});
313
-		}
314
-
315
-		return $uris;
316
-	}
317
-
318
-	/**
319
-	 * @param boolean $value
320
-	 * @return string|null
321
-	 */
322
-	public function setPublishStatus($value) {
323
-		$publicUri = $this->caldavBackend->setPublishStatus($value, $this);
324
-		$this->calendarInfo['publicuri'] = $publicUri;
325
-		return $publicUri;
326
-	}
327
-
328
-	/**
329
-	 * @return mixed $value
330
-	 */
331
-	public function getPublishStatus() {
332
-		return $this->caldavBackend->getPublishStatus($this);
333
-	}
334
-
335
-	public function canWrite() {
336
-		if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) {
337
-			return false;
338
-		}
339
-
340
-		if (isset($this->calendarInfo['{http://owncloud.org/ns}read-only'])) {
341
-			return !$this->calendarInfo['{http://owncloud.org/ns}read-only'];
342
-		}
343
-		return true;
344
-	}
345
-
346
-	private function isPublic() {
347
-		return isset($this->calendarInfo['{http://owncloud.org/ns}public']);
348
-	}
349
-
350
-	public function isShared() {
351
-		if (!isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) {
352
-			return false;
353
-		}
354
-
355
-		return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'] !== $this->calendarInfo['principaluri'];
356
-	}
357
-
358
-	public function isSubscription() {
359
-		return isset($this->calendarInfo['{http://calendarserver.org/ns/}source']);
360
-	}
361
-
362
-	public function isDeleted(): bool {
363
-		if (!isset($this->calendarInfo[TrashbinPlugin::PROPERTY_DELETED_AT])) {
364
-			return false;
365
-		}
366
-		return $this->calendarInfo[TrashbinPlugin::PROPERTY_DELETED_AT] !== null;
367
-	}
368
-
369
-	/**
370
-	 * @inheritDoc
371
-	 */
372
-	public function getChanges($syncToken, $syncLevel, $limit = null) {
373
-		if (!$syncToken && $limit) {
374
-			throw new UnsupportedLimitOnInitialSyncException();
375
-		}
376
-
377
-		return parent::getChanges($syncToken, $syncLevel, $limit);
378
-	}
379
-
380
-	/**
381
-	 * @inheritDoc
382
-	 */
383
-	public function restore(): void {
384
-		$this->caldavBackend->restoreCalendar((int)$this->calendarInfo['id']);
385
-	}
386
-
387
-	public function disableTrashbin(): void {
388
-		$this->useTrashbin = false;
389
-	}
390
-
391
-	/**
392
-	 * @inheritDoc
393
-	 */
394
-	public function moveInto($targetName, $sourcePath, INode $sourceNode) {
395
-		if (!($sourceNode instanceof CalendarObject)) {
396
-			return false;
397
-		}
398
-		try {
399
-			return $this->caldavBackend->moveCalendarObject(
400
-				$sourceNode->getOwner(),
401
-				$sourceNode->getId(),
402
-				$this->getOwner(),
403
-				$this->getResourceId(),
404
-				$targetName,
405
-			);
406
-		} catch (Exception $e) {
407
-			$this->logger->error('Could not move calendar object: ' . $e->getMessage(), ['exception' => $e]);
408
-			return false;
409
-		}
410
-	}
34
+    protected IL10N $l10n;
35
+    private bool $useTrashbin = true;
36
+
37
+    public function __construct(
38
+        BackendInterface $caldavBackend,
39
+        array $calendarInfo,
40
+        IL10N $l10n,
41
+        private IConfig $config,
42
+        private LoggerInterface $logger,
43
+    ) {
44
+        // Convert deletion date to ISO8601 string
45
+        if (isset($calendarInfo[TrashbinPlugin::PROPERTY_DELETED_AT])) {
46
+            $calendarInfo[TrashbinPlugin::PROPERTY_DELETED_AT] = (new DateTimeImmutable())
47
+                ->setTimestamp($calendarInfo[TrashbinPlugin::PROPERTY_DELETED_AT])
48
+                ->format(DateTimeInterface::ATOM);
49
+        }
50
+
51
+        parent::__construct($caldavBackend, $calendarInfo);
52
+
53
+        if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI && strcasecmp($this->calendarInfo['{DAV:}displayname'], 'Contact birthdays') === 0) {
54
+            $this->calendarInfo['{DAV:}displayname'] = $l10n->t('Contact birthdays');
55
+        }
56
+        if ($this->getName() === CalDavBackend::PERSONAL_CALENDAR_URI
57
+            && $this->calendarInfo['{DAV:}displayname'] === CalDavBackend::PERSONAL_CALENDAR_NAME) {
58
+            $this->calendarInfo['{DAV:}displayname'] = $l10n->t('Personal');
59
+        }
60
+        $this->l10n = $l10n;
61
+    }
62
+
63
+    public function getUri(): string {
64
+        return $this->calendarInfo['uri'];
65
+    }
66
+
67
+    protected function getCalendarType(): int {
68
+        return CalDavBackend::CALENDAR_TYPE_CALENDAR;
69
+    }
70
+
71
+    /**
72
+     * {@inheritdoc}
73
+     * @throws Forbidden
74
+     */
75
+    public function updateShares(array $add, array $remove): void {
76
+        if ($this->isShared()) {
77
+            throw new Forbidden();
78
+        }
79
+        $this->caldavBackend->updateShares($this, $add, $remove);
80
+    }
81
+
82
+    /**
83
+     * Returns the list of people whom this resource is shared with.
84
+     *
85
+     * Every element in this array should have the following properties:
86
+     *   * href - Often a mailto: address
87
+     *   * commonName - Optional, for example a first + last name
88
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
89
+     *   * readOnly - boolean
90
+     *   * summary - Optional, a description for the share
91
+     *
92
+     * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
93
+     */
94
+    public function getShares(): array {
95
+        if ($this->isShared()) {
96
+            return [];
97
+        }
98
+        return $this->caldavBackend->getShares($this->getResourceId());
99
+    }
100
+
101
+    public function getResourceId(): int {
102
+        return $this->calendarInfo['id'];
103
+    }
104
+
105
+    /**
106
+     * @return string
107
+     */
108
+    public function getPrincipalURI() {
109
+        return $this->calendarInfo['principaluri'];
110
+    }
111
+
112
+    /**
113
+     * @param int $resourceId
114
+     * @param list<array{privilege: string, principal: string, protected: bool}> $acl
115
+     * @return list<array{privilege: string, principal: ?string, protected: bool}>
116
+     */
117
+    public function getACL() {
118
+        $acl = [
119
+            [
120
+                'privilege' => '{DAV:}read',
121
+                'principal' => $this->getOwner(),
122
+                'protected' => true,
123
+            ],
124
+            [
125
+                'privilege' => '{DAV:}read',
126
+                'principal' => $this->getOwner() . '/calendar-proxy-write',
127
+                'protected' => true,
128
+            ],
129
+            [
130
+                'privilege' => '{DAV:}read',
131
+                'principal' => $this->getOwner() . '/calendar-proxy-read',
132
+                'protected' => true,
133
+            ],
134
+        ];
135
+
136
+        if ($this->getName() !== BirthdayService::BIRTHDAY_CALENDAR_URI) {
137
+            $acl[] = [
138
+                'privilege' => '{DAV:}write',
139
+                'principal' => $this->getOwner(),
140
+                'protected' => true,
141
+            ];
142
+            $acl[] = [
143
+                'privilege' => '{DAV:}write',
144
+                'principal' => $this->getOwner() . '/calendar-proxy-write',
145
+                'protected' => true,
146
+            ];
147
+        } else {
148
+            $acl[] = [
149
+                'privilege' => '{DAV:}write-properties',
150
+                'principal' => $this->getOwner(),
151
+                'protected' => true,
152
+            ];
153
+            $acl[] = [
154
+                'privilege' => '{DAV:}write-properties',
155
+                'principal' => $this->getOwner() . '/calendar-proxy-write',
156
+                'protected' => true,
157
+            ];
158
+        }
159
+
160
+        $acl[] = [
161
+            'privilege' => '{DAV:}write-properties',
162
+            'principal' => $this->getOwner() . '/calendar-proxy-read',
163
+            'protected' => true,
164
+        ];
165
+
166
+        if (!$this->isShared()) {
167
+            return $acl;
168
+        }
169
+
170
+        if ($this->getOwner() !== parent::getOwner()) {
171
+            $acl[] = [
172
+                'privilege' => '{DAV:}read',
173
+                'principal' => parent::getOwner(),
174
+                'protected' => true,
175
+            ];
176
+            if ($this->canWrite()) {
177
+                $acl[] = [
178
+                    'privilege' => '{DAV:}write',
179
+                    'principal' => parent::getOwner(),
180
+                    'protected' => true,
181
+                ];
182
+            } else {
183
+                $acl[] = [
184
+                    'privilege' => '{DAV:}write-properties',
185
+                    'principal' => parent::getOwner(),
186
+                    'protected' => true,
187
+                ];
188
+            }
189
+        }
190
+        if ($this->isPublic()) {
191
+            $acl[] = [
192
+                'privilege' => '{DAV:}read',
193
+                'principal' => 'principals/system/public',
194
+                'protected' => true,
195
+            ];
196
+        }
197
+
198
+        $acl = $this->caldavBackend->applyShareAcl($this->getResourceId(), $acl);
199
+        $allowedPrincipals = [
200
+            $this->getOwner(),
201
+            $this->getOwner() . '/calendar-proxy-read',
202
+            $this->getOwner() . '/calendar-proxy-write',
203
+            parent::getOwner(),
204
+            'principals/system/public',
205
+        ];
206
+        /** @var list<array{privilege: string, principal: string, protected: bool}> $acl */
207
+        $acl = array_filter($acl, function (array $rule) use ($allowedPrincipals): bool {
208
+            return \in_array($rule['principal'], $allowedPrincipals, true);
209
+        });
210
+        return $acl;
211
+    }
212
+
213
+    public function getChildACL() {
214
+        return $this->getACL();
215
+    }
216
+
217
+    public function getOwner(): ?string {
218
+        if (isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) {
219
+            return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'];
220
+        }
221
+        return parent::getOwner();
222
+    }
223
+
224
+    public function delete() {
225
+        if ($this->isShared()) {
226
+            $this->caldavBackend->unshare($this, 'principal:' . $this->getPrincipalURI());
227
+            return;
228
+        }
229
+
230
+        // Remember when a user deleted their birthday calendar
231
+        // in order to not regenerate it on the next contacts change
232
+        if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) {
233
+            $principalURI = $this->getPrincipalURI();
234
+            $userId = substr($principalURI, 17);
235
+
236
+            $this->config->setUserValue($userId, 'dav', 'generateBirthdayCalendar', 'no');
237
+        }
238
+
239
+        $this->caldavBackend->deleteCalendar(
240
+            $this->calendarInfo['id'],
241
+            !$this->useTrashbin
242
+        );
243
+    }
244
+
245
+    public function propPatch(PropPatch $propPatch) {
246
+        // parent::propPatch will only update calendars table
247
+        // if calendar is shared, changes have to be made to the properties table
248
+        if (!$this->isShared()) {
249
+            parent::propPatch($propPatch);
250
+        }
251
+    }
252
+
253
+    public function getChild($name) {
254
+        $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name, $this->getCalendarType());
255
+
256
+        if (!$obj) {
257
+            throw new NotFound('Calendar object not found');
258
+        }
259
+
260
+        if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
261
+            throw new NotFound('Calendar object not found');
262
+        }
263
+
264
+        $obj['acl'] = $this->getChildACL();
265
+
266
+        return new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
267
+    }
268
+
269
+    public function getChildren() {
270
+        $objs = $this->caldavBackend->getCalendarObjects($this->calendarInfo['id'], $this->getCalendarType());
271
+        $children = [];
272
+        foreach ($objs as $obj) {
273
+            if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
274
+                continue;
275
+            }
276
+            $obj['acl'] = $this->getChildACL();
277
+            $children[] = new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
278
+        }
279
+        return $children;
280
+    }
281
+
282
+    public function getMultipleChildren(array $paths) {
283
+        $objs = $this->caldavBackend->getMultipleCalendarObjects($this->calendarInfo['id'], $paths, $this->getCalendarType());
284
+        $children = [];
285
+        foreach ($objs as $obj) {
286
+            if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
287
+                continue;
288
+            }
289
+            $obj['acl'] = $this->getChildACL();
290
+            $children[] = new CalendarObject($this->caldavBackend, $this->l10n, $this->calendarInfo, $obj);
291
+        }
292
+        return $children;
293
+    }
294
+
295
+    public function childExists($name) {
296
+        $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name, $this->getCalendarType());
297
+        if (!$obj) {
298
+            return false;
299
+        }
300
+        if ($obj['classification'] === CalDavBackend::CLASSIFICATION_PRIVATE && $this->isShared()) {
301
+            return false;
302
+        }
303
+
304
+        return true;
305
+    }
306
+
307
+    public function calendarQuery(array $filters) {
308
+        $uris = $this->caldavBackend->calendarQuery($this->calendarInfo['id'], $filters, $this->getCalendarType());
309
+        if ($this->isShared()) {
310
+            return array_filter($uris, function ($uri) {
311
+                return $this->childExists($uri);
312
+            });
313
+        }
314
+
315
+        return $uris;
316
+    }
317
+
318
+    /**
319
+     * @param boolean $value
320
+     * @return string|null
321
+     */
322
+    public function setPublishStatus($value) {
323
+        $publicUri = $this->caldavBackend->setPublishStatus($value, $this);
324
+        $this->calendarInfo['publicuri'] = $publicUri;
325
+        return $publicUri;
326
+    }
327
+
328
+    /**
329
+     * @return mixed $value
330
+     */
331
+    public function getPublishStatus() {
332
+        return $this->caldavBackend->getPublishStatus($this);
333
+    }
334
+
335
+    public function canWrite() {
336
+        if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) {
337
+            return false;
338
+        }
339
+
340
+        if (isset($this->calendarInfo['{http://owncloud.org/ns}read-only'])) {
341
+            return !$this->calendarInfo['{http://owncloud.org/ns}read-only'];
342
+        }
343
+        return true;
344
+    }
345
+
346
+    private function isPublic() {
347
+        return isset($this->calendarInfo['{http://owncloud.org/ns}public']);
348
+    }
349
+
350
+    public function isShared() {
351
+        if (!isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) {
352
+            return false;
353
+        }
354
+
355
+        return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'] !== $this->calendarInfo['principaluri'];
356
+    }
357
+
358
+    public function isSubscription() {
359
+        return isset($this->calendarInfo['{http://calendarserver.org/ns/}source']);
360
+    }
361
+
362
+    public function isDeleted(): bool {
363
+        if (!isset($this->calendarInfo[TrashbinPlugin::PROPERTY_DELETED_AT])) {
364
+            return false;
365
+        }
366
+        return $this->calendarInfo[TrashbinPlugin::PROPERTY_DELETED_AT] !== null;
367
+    }
368
+
369
+    /**
370
+     * @inheritDoc
371
+     */
372
+    public function getChanges($syncToken, $syncLevel, $limit = null) {
373
+        if (!$syncToken && $limit) {
374
+            throw new UnsupportedLimitOnInitialSyncException();
375
+        }
376
+
377
+        return parent::getChanges($syncToken, $syncLevel, $limit);
378
+    }
379
+
380
+    /**
381
+     * @inheritDoc
382
+     */
383
+    public function restore(): void {
384
+        $this->caldavBackend->restoreCalendar((int)$this->calendarInfo['id']);
385
+    }
386
+
387
+    public function disableTrashbin(): void {
388
+        $this->useTrashbin = false;
389
+    }
390
+
391
+    /**
392
+     * @inheritDoc
393
+     */
394
+    public function moveInto($targetName, $sourcePath, INode $sourceNode) {
395
+        if (!($sourceNode instanceof CalendarObject)) {
396
+            return false;
397
+        }
398
+        try {
399
+            return $this->caldavBackend->moveCalendarObject(
400
+                $sourceNode->getOwner(),
401
+                $sourceNode->getId(),
402
+                $this->getOwner(),
403
+                $this->getResourceId(),
404
+                $targetName,
405
+            );
406
+        } catch (Exception $e) {
407
+            $this->logger->error('Could not move calendar object: ' . $e->getMessage(), ['exception' => $e]);
408
+            return false;
409
+        }
410
+    }
411 411
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -123,12 +123,12 @@  discard block
 block discarded – undo
123 123
 			],
124 124
 			[
125 125
 				'privilege' => '{DAV:}read',
126
-				'principal' => $this->getOwner() . '/calendar-proxy-write',
126
+				'principal' => $this->getOwner().'/calendar-proxy-write',
127 127
 				'protected' => true,
128 128
 			],
129 129
 			[
130 130
 				'privilege' => '{DAV:}read',
131
-				'principal' => $this->getOwner() . '/calendar-proxy-read',
131
+				'principal' => $this->getOwner().'/calendar-proxy-read',
132 132
 				'protected' => true,
133 133
 			],
134 134
 		];
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 			];
142 142
 			$acl[] = [
143 143
 				'privilege' => '{DAV:}write',
144
-				'principal' => $this->getOwner() . '/calendar-proxy-write',
144
+				'principal' => $this->getOwner().'/calendar-proxy-write',
145 145
 				'protected' => true,
146 146
 			];
147 147
 		} else {
@@ -152,14 +152,14 @@  discard block
 block discarded – undo
152 152
 			];
153 153
 			$acl[] = [
154 154
 				'privilege' => '{DAV:}write-properties',
155
-				'principal' => $this->getOwner() . '/calendar-proxy-write',
155
+				'principal' => $this->getOwner().'/calendar-proxy-write',
156 156
 				'protected' => true,
157 157
 			];
158 158
 		}
159 159
 
160 160
 		$acl[] = [
161 161
 			'privilege' => '{DAV:}write-properties',
162
-			'principal' => $this->getOwner() . '/calendar-proxy-read',
162
+			'principal' => $this->getOwner().'/calendar-proxy-read',
163 163
 			'protected' => true,
164 164
 		];
165 165
 
@@ -198,13 +198,13 @@  discard block
 block discarded – undo
198 198
 		$acl = $this->caldavBackend->applyShareAcl($this->getResourceId(), $acl);
199 199
 		$allowedPrincipals = [
200 200
 			$this->getOwner(),
201
-			$this->getOwner() . '/calendar-proxy-read',
202
-			$this->getOwner() . '/calendar-proxy-write',
201
+			$this->getOwner().'/calendar-proxy-read',
202
+			$this->getOwner().'/calendar-proxy-write',
203 203
 			parent::getOwner(),
204 204
 			'principals/system/public',
205 205
 		];
206 206
 		/** @var list<array{privilege: string, principal: string, protected: bool}> $acl */
207
-		$acl = array_filter($acl, function (array $rule) use ($allowedPrincipals): bool {
207
+		$acl = array_filter($acl, function(array $rule) use ($allowedPrincipals): bool {
208 208
 			return \in_array($rule['principal'], $allowedPrincipals, true);
209 209
 		});
210 210
 		return $acl;
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
 
224 224
 	public function delete() {
225 225
 		if ($this->isShared()) {
226
-			$this->caldavBackend->unshare($this, 'principal:' . $this->getPrincipalURI());
226
+			$this->caldavBackend->unshare($this, 'principal:'.$this->getPrincipalURI());
227 227
 			return;
228 228
 		}
229 229
 
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
 	public function calendarQuery(array $filters) {
308 308
 		$uris = $this->caldavBackend->calendarQuery($this->calendarInfo['id'], $filters, $this->getCalendarType());
309 309
 		if ($this->isShared()) {
310
-			return array_filter($uris, function ($uri) {
310
+			return array_filter($uris, function($uri) {
311 311
 				return $this->childExists($uri);
312 312
 			});
313 313
 		}
@@ -381,7 +381,7 @@  discard block
 block discarded – undo
381 381
 	 * @inheritDoc
382 382
 	 */
383 383
 	public function restore(): void {
384
-		$this->caldavBackend->restoreCalendar((int)$this->calendarInfo['id']);
384
+		$this->caldavBackend->restoreCalendar((int) $this->calendarInfo['id']);
385 385
 	}
386 386
 
387 387
 	public function disableTrashbin(): void {
@@ -404,7 +404,7 @@  discard block
 block discarded – undo
404 404
 				$targetName,
405 405
 			);
406 406
 		} catch (Exception $e) {
407
-			$this->logger->error('Could not move calendar object: ' . $e->getMessage(), ['exception' => $e]);
407
+			$this->logger->error('Could not move calendar object: '.$e->getMessage(), ['exception' => $e]);
408 408
 			return false;
409 409
 		}
410 410
 	}
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalendarHome.php 1 patch
Indentation   +193 added lines, -193 removed lines patch added patch discarded remove patch
@@ -30,197 +30,197 @@
 block discarded – undo
30 30
 
31 31
 class CalendarHome extends \Sabre\CalDAV\CalendarHome {
32 32
 
33
-	/** @var IL10N */
34
-	private $l10n;
35
-
36
-	/** @var IConfig */
37
-	private $config;
38
-
39
-	/** @var PluginManager */
40
-	private $pluginManager;
41
-
42
-	private ?array $cachedChildren = null;
43
-
44
-	public function __construct(
45
-		BackendInterface $caldavBackend,
46
-		array $principalInfo,
47
-		private LoggerInterface $logger,
48
-		private FederatedCalendarFactory $federatedCalendarFactory,
49
-		private bool $returnCachedSubscriptions,
50
-	) {
51
-		parent::__construct($caldavBackend, $principalInfo);
52
-		$this->l10n = \OC::$server->getL10N('dav');
53
-		$this->config = Server::get(IConfig::class);
54
-		$this->pluginManager = new PluginManager(
55
-			\OC::$server,
56
-			Server::get(IAppManager::class)
57
-		);
58
-	}
59
-
60
-	/**
61
-	 * @return BackendInterface
62
-	 */
63
-	public function getCalDAVBackend() {
64
-		return $this->caldavBackend;
65
-	}
66
-
67
-	/**
68
-	 * @inheritdoc
69
-	 */
70
-	public function createExtendedCollection($name, MkCol $mkCol): void {
71
-		$reservedNames = [
72
-			BirthdayService::BIRTHDAY_CALENDAR_URI,
73
-			TrashbinHome::NAME,
74
-		];
75
-
76
-		if (\in_array($name, $reservedNames, true) || ExternalCalendar::doesViolateReservedName($name)) {
77
-			throw new MethodNotAllowed('The resource you tried to create has a reserved name');
78
-		}
79
-
80
-		parent::createExtendedCollection($name, $mkCol);
81
-	}
82
-
83
-	/**
84
-	 * @inheritdoc
85
-	 */
86
-	public function getChildren() {
87
-		if ($this->cachedChildren) {
88
-			return $this->cachedChildren;
89
-		}
90
-		$calendars = $this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']);
91
-		$objects = [];
92
-		foreach ($calendars as $calendar) {
93
-			$objects[] = new Calendar($this->caldavBackend, $calendar, $this->l10n, $this->config, $this->logger);
94
-		}
95
-
96
-		if ($this->caldavBackend instanceof SchedulingSupport) {
97
-			$objects[] = new Inbox($this->caldavBackend, $this->principalInfo['uri']);
98
-			$objects[] = new Outbox($this->config, $this->principalInfo['uri']);
99
-		}
100
-
101
-		// We're adding a notifications node, if it's supported by the backend.
102
-		if ($this->caldavBackend instanceof NotificationSupport) {
103
-			$objects[] = new \Sabre\CalDAV\Notifications\Collection($this->caldavBackend, $this->principalInfo['uri']);
104
-		}
105
-
106
-		if ($this->caldavBackend instanceof CalDavBackend) {
107
-			$objects[] = new TrashbinHome($this->caldavBackend, $this->principalInfo);
108
-
109
-			$federatedCalendars = $this->caldavBackend->getFederatedCalendarsForUser(
110
-				$this->principalInfo['uri'],
111
-			);
112
-			foreach ($federatedCalendars as $federatedCalendarInfo) {
113
-				$objects[] = $this->federatedCalendarFactory->createFederatedCalendar(
114
-					$federatedCalendarInfo,
115
-				);
116
-			}
117
-		}
118
-
119
-		// If the backend supports subscriptions, we'll add those as well,
120
-		if ($this->caldavBackend instanceof SubscriptionSupport) {
121
-			foreach ($this->caldavBackend->getSubscriptionsForUser($this->principalInfo['uri']) as $subscription) {
122
-				if ($this->returnCachedSubscriptions) {
123
-					$objects[] = new CachedSubscription($this->caldavBackend, $subscription);
124
-				} else {
125
-					$objects[] = new Subscription($this->caldavBackend, $subscription);
126
-				}
127
-			}
128
-		}
129
-
130
-		foreach ($this->pluginManager->getCalendarPlugins() as $calendarPlugin) {
131
-			/** @var ICalendarProvider $calendarPlugin */
132
-			$calendars = $calendarPlugin->fetchAllForCalendarHome($this->principalInfo['uri']);
133
-			foreach ($calendars as $calendar) {
134
-				$objects[] = $calendar;
135
-			}
136
-		}
137
-
138
-		$this->cachedChildren = $objects;
139
-		return $objects;
140
-	}
141
-
142
-	/**
143
-	 * @param string $name
144
-	 *
145
-	 * @return INode
146
-	 */
147
-	public function getChild($name) {
148
-		// Special nodes
149
-		if ($name === 'inbox' && $this->caldavBackend instanceof SchedulingSupport) {
150
-			return new Inbox($this->caldavBackend, $this->principalInfo['uri']);
151
-		}
152
-		if ($name === 'outbox' && $this->caldavBackend instanceof SchedulingSupport) {
153
-			return new Outbox($this->config, $this->principalInfo['uri']);
154
-		}
155
-		if ($name === 'notifications' && $this->caldavBackend instanceof NotificationSupport) {
156
-			return new \Sabre\CalDAV\Notifications\Collection($this->caldavBackend, $this->principalInfo['uri']);
157
-		}
158
-		if ($name === TrashbinHome::NAME && $this->caldavBackend instanceof CalDavBackend) {
159
-			return new TrashbinHome($this->caldavBackend, $this->principalInfo);
160
-		}
161
-
162
-		// Only check if the methods are available
163
-		if ($this->caldavBackend instanceof CalDavBackend) {
164
-			// Calendar - this covers all "regular" calendars, but not shared
165
-			$calendar = $this->caldavBackend->getCalendarByUri($this->principalInfo['uri'], $name);
166
-			if (!empty($calendar)) {
167
-				return new Calendar($this->caldavBackend, $calendar, $this->l10n, $this->config, $this->logger);
168
-			}
169
-
170
-			// Federated calendar
171
-			$federatedCalendar = $this->caldavBackend->getFederatedCalendarByUri(
172
-				$this->principalInfo['uri'],
173
-				$name,
174
-			);
175
-			if ($federatedCalendar !== null) {
176
-				return $this->federatedCalendarFactory->createFederatedCalendar($federatedCalendar);
177
-			}
178
-		}
179
-
180
-		// Fallback to cover shared calendars
181
-		foreach ($this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']) as $calendar) {
182
-			if ($calendar['uri'] === $name) {
183
-				return new Calendar($this->caldavBackend, $calendar, $this->l10n, $this->config, $this->logger);
184
-			}
185
-		}
186
-
187
-		if ($this->caldavBackend instanceof SubscriptionSupport) {
188
-			foreach ($this->caldavBackend->getSubscriptionsForUser($this->principalInfo['uri']) as $subscription) {
189
-				if ($subscription['uri'] === $name) {
190
-					if ($this->returnCachedSubscriptions) {
191
-						return new CachedSubscription($this->caldavBackend, $subscription);
192
-					}
193
-
194
-					return new Subscription($this->caldavBackend, $subscription);
195
-				}
196
-			}
197
-		}
198
-
199
-		if (ExternalCalendar::isAppGeneratedCalendar($name)) {
200
-			[$appId, $calendarUri] = ExternalCalendar::splitAppGeneratedCalendarUri($name);
201
-
202
-			foreach ($this->pluginManager->getCalendarPlugins() as $calendarPlugin) {
203
-				/** @var ICalendarProvider $calendarPlugin */
204
-				if ($calendarPlugin->getAppId() !== $appId) {
205
-					continue;
206
-				}
207
-
208
-				if ($calendarPlugin->hasCalendarInCalendarHome($this->principalInfo['uri'], $calendarUri)) {
209
-					return $calendarPlugin->getCalendarInCalendarHome($this->principalInfo['uri'], $calendarUri);
210
-				}
211
-			}
212
-		}
213
-
214
-		throw new NotFound('Node with name \'' . $name . '\' could not be found');
215
-	}
216
-
217
-	/**
218
-	 * @param array $filters
219
-	 * @param integer|null $limit
220
-	 * @param integer|null $offset
221
-	 */
222
-	public function calendarSearch(array $filters, $limit = null, $offset = null) {
223
-		$principalUri = $this->principalInfo['uri'];
224
-		return $this->caldavBackend->calendarSearch($principalUri, $filters, $limit, $offset);
225
-	}
33
+    /** @var IL10N */
34
+    private $l10n;
35
+
36
+    /** @var IConfig */
37
+    private $config;
38
+
39
+    /** @var PluginManager */
40
+    private $pluginManager;
41
+
42
+    private ?array $cachedChildren = null;
43
+
44
+    public function __construct(
45
+        BackendInterface $caldavBackend,
46
+        array $principalInfo,
47
+        private LoggerInterface $logger,
48
+        private FederatedCalendarFactory $federatedCalendarFactory,
49
+        private bool $returnCachedSubscriptions,
50
+    ) {
51
+        parent::__construct($caldavBackend, $principalInfo);
52
+        $this->l10n = \OC::$server->getL10N('dav');
53
+        $this->config = Server::get(IConfig::class);
54
+        $this->pluginManager = new PluginManager(
55
+            \OC::$server,
56
+            Server::get(IAppManager::class)
57
+        );
58
+    }
59
+
60
+    /**
61
+     * @return BackendInterface
62
+     */
63
+    public function getCalDAVBackend() {
64
+        return $this->caldavBackend;
65
+    }
66
+
67
+    /**
68
+     * @inheritdoc
69
+     */
70
+    public function createExtendedCollection($name, MkCol $mkCol): void {
71
+        $reservedNames = [
72
+            BirthdayService::BIRTHDAY_CALENDAR_URI,
73
+            TrashbinHome::NAME,
74
+        ];
75
+
76
+        if (\in_array($name, $reservedNames, true) || ExternalCalendar::doesViolateReservedName($name)) {
77
+            throw new MethodNotAllowed('The resource you tried to create has a reserved name');
78
+        }
79
+
80
+        parent::createExtendedCollection($name, $mkCol);
81
+    }
82
+
83
+    /**
84
+     * @inheritdoc
85
+     */
86
+    public function getChildren() {
87
+        if ($this->cachedChildren) {
88
+            return $this->cachedChildren;
89
+        }
90
+        $calendars = $this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']);
91
+        $objects = [];
92
+        foreach ($calendars as $calendar) {
93
+            $objects[] = new Calendar($this->caldavBackend, $calendar, $this->l10n, $this->config, $this->logger);
94
+        }
95
+
96
+        if ($this->caldavBackend instanceof SchedulingSupport) {
97
+            $objects[] = new Inbox($this->caldavBackend, $this->principalInfo['uri']);
98
+            $objects[] = new Outbox($this->config, $this->principalInfo['uri']);
99
+        }
100
+
101
+        // We're adding a notifications node, if it's supported by the backend.
102
+        if ($this->caldavBackend instanceof NotificationSupport) {
103
+            $objects[] = new \Sabre\CalDAV\Notifications\Collection($this->caldavBackend, $this->principalInfo['uri']);
104
+        }
105
+
106
+        if ($this->caldavBackend instanceof CalDavBackend) {
107
+            $objects[] = new TrashbinHome($this->caldavBackend, $this->principalInfo);
108
+
109
+            $federatedCalendars = $this->caldavBackend->getFederatedCalendarsForUser(
110
+                $this->principalInfo['uri'],
111
+            );
112
+            foreach ($federatedCalendars as $federatedCalendarInfo) {
113
+                $objects[] = $this->federatedCalendarFactory->createFederatedCalendar(
114
+                    $federatedCalendarInfo,
115
+                );
116
+            }
117
+        }
118
+
119
+        // If the backend supports subscriptions, we'll add those as well,
120
+        if ($this->caldavBackend instanceof SubscriptionSupport) {
121
+            foreach ($this->caldavBackend->getSubscriptionsForUser($this->principalInfo['uri']) as $subscription) {
122
+                if ($this->returnCachedSubscriptions) {
123
+                    $objects[] = new CachedSubscription($this->caldavBackend, $subscription);
124
+                } else {
125
+                    $objects[] = new Subscription($this->caldavBackend, $subscription);
126
+                }
127
+            }
128
+        }
129
+
130
+        foreach ($this->pluginManager->getCalendarPlugins() as $calendarPlugin) {
131
+            /** @var ICalendarProvider $calendarPlugin */
132
+            $calendars = $calendarPlugin->fetchAllForCalendarHome($this->principalInfo['uri']);
133
+            foreach ($calendars as $calendar) {
134
+                $objects[] = $calendar;
135
+            }
136
+        }
137
+
138
+        $this->cachedChildren = $objects;
139
+        return $objects;
140
+    }
141
+
142
+    /**
143
+     * @param string $name
144
+     *
145
+     * @return INode
146
+     */
147
+    public function getChild($name) {
148
+        // Special nodes
149
+        if ($name === 'inbox' && $this->caldavBackend instanceof SchedulingSupport) {
150
+            return new Inbox($this->caldavBackend, $this->principalInfo['uri']);
151
+        }
152
+        if ($name === 'outbox' && $this->caldavBackend instanceof SchedulingSupport) {
153
+            return new Outbox($this->config, $this->principalInfo['uri']);
154
+        }
155
+        if ($name === 'notifications' && $this->caldavBackend instanceof NotificationSupport) {
156
+            return new \Sabre\CalDAV\Notifications\Collection($this->caldavBackend, $this->principalInfo['uri']);
157
+        }
158
+        if ($name === TrashbinHome::NAME && $this->caldavBackend instanceof CalDavBackend) {
159
+            return new TrashbinHome($this->caldavBackend, $this->principalInfo);
160
+        }
161
+
162
+        // Only check if the methods are available
163
+        if ($this->caldavBackend instanceof CalDavBackend) {
164
+            // Calendar - this covers all "regular" calendars, but not shared
165
+            $calendar = $this->caldavBackend->getCalendarByUri($this->principalInfo['uri'], $name);
166
+            if (!empty($calendar)) {
167
+                return new Calendar($this->caldavBackend, $calendar, $this->l10n, $this->config, $this->logger);
168
+            }
169
+
170
+            // Federated calendar
171
+            $federatedCalendar = $this->caldavBackend->getFederatedCalendarByUri(
172
+                $this->principalInfo['uri'],
173
+                $name,
174
+            );
175
+            if ($federatedCalendar !== null) {
176
+                return $this->federatedCalendarFactory->createFederatedCalendar($federatedCalendar);
177
+            }
178
+        }
179
+
180
+        // Fallback to cover shared calendars
181
+        foreach ($this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']) as $calendar) {
182
+            if ($calendar['uri'] === $name) {
183
+                return new Calendar($this->caldavBackend, $calendar, $this->l10n, $this->config, $this->logger);
184
+            }
185
+        }
186
+
187
+        if ($this->caldavBackend instanceof SubscriptionSupport) {
188
+            foreach ($this->caldavBackend->getSubscriptionsForUser($this->principalInfo['uri']) as $subscription) {
189
+                if ($subscription['uri'] === $name) {
190
+                    if ($this->returnCachedSubscriptions) {
191
+                        return new CachedSubscription($this->caldavBackend, $subscription);
192
+                    }
193
+
194
+                    return new Subscription($this->caldavBackend, $subscription);
195
+                }
196
+            }
197
+        }
198
+
199
+        if (ExternalCalendar::isAppGeneratedCalendar($name)) {
200
+            [$appId, $calendarUri] = ExternalCalendar::splitAppGeneratedCalendarUri($name);
201
+
202
+            foreach ($this->pluginManager->getCalendarPlugins() as $calendarPlugin) {
203
+                /** @var ICalendarProvider $calendarPlugin */
204
+                if ($calendarPlugin->getAppId() !== $appId) {
205
+                    continue;
206
+                }
207
+
208
+                if ($calendarPlugin->hasCalendarInCalendarHome($this->principalInfo['uri'], $calendarUri)) {
209
+                    return $calendarPlugin->getCalendarInCalendarHome($this->principalInfo['uri'], $calendarUri);
210
+                }
211
+            }
212
+        }
213
+
214
+        throw new NotFound('Node with name \'' . $name . '\' could not be found');
215
+    }
216
+
217
+    /**
218
+     * @param array $filters
219
+     * @param integer|null $limit
220
+     * @param integer|null $offset
221
+     */
222
+    public function calendarSearch(array $filters, $limit = null, $offset = null) {
223
+        $principalUri = $this->principalInfo['uri'];
224
+        return $this->caldavBackend->calendarSearch($principalUri, $filters, $limit, $offset);
225
+    }
226 226
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalendarRoot.php 1 patch
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -17,57 +17,57 @@
 block discarded – undo
17 17
 use Sabre\DAVACL\PrincipalBackend;
18 18
 
19 19
 class CalendarRoot extends \Sabre\CalDAV\CalendarRoot {
20
-	private array $returnCachedSubscriptions = [];
20
+    private array $returnCachedSubscriptions = [];
21 21
 
22
-	public function __construct(
23
-		PrincipalBackend\BackendInterface $principalBackend,
24
-		Backend\BackendInterface $caldavBackend,
25
-		$principalPrefix,
26
-		private LoggerInterface $logger,
27
-		private IL10N $l10n,
28
-		private IConfig $config,
29
-		private FederatedCalendarFactory $federatedCalendarFactory,
30
-	) {
31
-		parent::__construct($principalBackend, $caldavBackend, $principalPrefix);
32
-	}
22
+    public function __construct(
23
+        PrincipalBackend\BackendInterface $principalBackend,
24
+        Backend\BackendInterface $caldavBackend,
25
+        $principalPrefix,
26
+        private LoggerInterface $logger,
27
+        private IL10N $l10n,
28
+        private IConfig $config,
29
+        private FederatedCalendarFactory $federatedCalendarFactory,
30
+    ) {
31
+        parent::__construct($principalBackend, $caldavBackend, $principalPrefix);
32
+    }
33 33
 
34
-	public function getChildForPrincipal(array $principal) {
35
-		[$prefix] = \Sabre\Uri\split($principal['uri']);
36
-		if ($prefix === RemoteUserPrincipalBackend::PRINCIPAL_PREFIX) {
37
-			return new RemoteUserCalendarHome(
38
-				$this->caldavBackend,
39
-				$principal,
40
-				$this->l10n,
41
-				$this->config,
42
-				$this->logger,
43
-			);
44
-		}
34
+    public function getChildForPrincipal(array $principal) {
35
+        [$prefix] = \Sabre\Uri\split($principal['uri']);
36
+        if ($prefix === RemoteUserPrincipalBackend::PRINCIPAL_PREFIX) {
37
+            return new RemoteUserCalendarHome(
38
+                $this->caldavBackend,
39
+                $principal,
40
+                $this->l10n,
41
+                $this->config,
42
+                $this->logger,
43
+            );
44
+        }
45 45
 
46
-		return new CalendarHome(
47
-			$this->caldavBackend,
48
-			$principal,
49
-			$this->logger,
50
-			$this->federatedCalendarFactory,
51
-			array_key_exists($principal['uri'], $this->returnCachedSubscriptions)
52
-		);
53
-	}
46
+        return new CalendarHome(
47
+            $this->caldavBackend,
48
+            $principal,
49
+            $this->logger,
50
+            $this->federatedCalendarFactory,
51
+            array_key_exists($principal['uri'], $this->returnCachedSubscriptions)
52
+        );
53
+    }
54 54
 
55
-	public function getName() {
56
-		if ($this->principalPrefix === 'principals/calendar-resources'
57
-			|| $this->principalPrefix === 'principals/calendar-rooms') {
58
-			$parts = explode('/', $this->principalPrefix);
55
+    public function getName() {
56
+        if ($this->principalPrefix === 'principals/calendar-resources'
57
+            || $this->principalPrefix === 'principals/calendar-rooms') {
58
+            $parts = explode('/', $this->principalPrefix);
59 59
 
60
-			return $parts[1];
61
-		}
60
+            return $parts[1];
61
+        }
62 62
 
63
-		if ($this->principalPrefix === RemoteUserPrincipalBackend::PRINCIPAL_PREFIX) {
64
-			return 'remote-calendars';
65
-		}
63
+        if ($this->principalPrefix === RemoteUserPrincipalBackend::PRINCIPAL_PREFIX) {
64
+            return 'remote-calendars';
65
+        }
66 66
 
67
-		return parent::getName();
68
-	}
67
+        return parent::getName();
68
+    }
69 69
 
70
-	public function enableReturnCachedSubscriptions(string $principalUri): void {
71
-		$this->returnCachedSubscriptions['principals/users/' . $principalUri] = true;
72
-	}
70
+    public function enableReturnCachedSubscriptions(string $principalUri): void {
71
+        $this->returnCachedSubscriptions['principals/users/' . $principalUri] = true;
72
+    }
73 73
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/SyncService.php 2 patches
Indentation   +64 added lines, -64 removed lines patch added patch discarded remove patch
@@ -21,72 +21,72 @@
 block discarded – undo
21 21
 use Psr\Log\LoggerInterface;
22 22
 
23 23
 class SyncService extends ASyncService {
24
-	use TTransactional;
24
+    use TTransactional;
25 25
 
26
-	public function __construct(
27
-		IClientService $clientService,
28
-		IConfig $config,
29
-		private readonly CalDavBackend $backend,
30
-		private readonly FederatedCalendarMapper $federatedCalendarMapper,
31
-		private readonly IDBConnection $dbConnection,
32
-		private readonly LoggerInterface $logger,
33
-	) {
34
-		parent::__construct($clientService, $config);
35
-	}
26
+    public function __construct(
27
+        IClientService $clientService,
28
+        IConfig $config,
29
+        private readonly CalDavBackend $backend,
30
+        private readonly FederatedCalendarMapper $federatedCalendarMapper,
31
+        private readonly IDBConnection $dbConnection,
32
+        private readonly LoggerInterface $logger,
33
+    ) {
34
+        parent::__construct($clientService, $config);
35
+    }
36 36
 
37
-	/**
38
-	 * @param string $url
39
-	 * @param string $username
40
-	 * @param string $sharedSecret
41
-	 * @param string|null $syncToken
42
-	 * @param FederatedCalendarEntity $calendar
43
-	 */
44
-	public function syncRemoteCalendar(
45
-		string $url,
46
-		string $username,
47
-		string $sharedSecret,
48
-		?string $syncToken,
49
-		FederatedCalendarEntity $calendar,
50
-	): SyncServiceResult {
51
-		try {
52
-			$response = $this->requestSyncReport($url, $username, $sharedSecret, $syncToken);
53
-		} catch (ClientExceptionInterface $ex) {
54
-			if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
55
-				// Remote server revoked access to the calendar => remove it
56
-				$this->federatedCalendarMapper->delete($calendar);
57
-				$this->logger->error("Authorization failed, remove federated calendar: $url", [
58
-					'app' => 'dav',
59
-				]);
60
-				throw $ex;
61
-			}
62
-			$this->logger->error('Client exception:', ['app' => 'dav', 'exception' => $ex]);
63
-			throw $ex;
64
-		}
37
+    /**
38
+     * @param string $url
39
+     * @param string $username
40
+     * @param string $sharedSecret
41
+     * @param string|null $syncToken
42
+     * @param FederatedCalendarEntity $calendar
43
+     */
44
+    public function syncRemoteCalendar(
45
+        string $url,
46
+        string $username,
47
+        string $sharedSecret,
48
+        ?string $syncToken,
49
+        FederatedCalendarEntity $calendar,
50
+    ): SyncServiceResult {
51
+        try {
52
+            $response = $this->requestSyncReport($url, $username, $sharedSecret, $syncToken);
53
+        } catch (ClientExceptionInterface $ex) {
54
+            if ($ex->getCode() === Http::STATUS_UNAUTHORIZED) {
55
+                // Remote server revoked access to the calendar => remove it
56
+                $this->federatedCalendarMapper->delete($calendar);
57
+                $this->logger->error("Authorization failed, remove federated calendar: $url", [
58
+                    'app' => 'dav',
59
+                ]);
60
+                throw $ex;
61
+            }
62
+            $this->logger->error('Client exception:', ['app' => 'dav', 'exception' => $ex]);
63
+            throw $ex;
64
+        }
65 65
 
66
-		// TODO: use multi-get for download
67
-		$downloadedEvents = 0;
68
-		foreach ($response['response'] as $resource => $status) {
69
-			$objectUri = basename($resource);
70
-			if (isset($status[200])) {
71
-				$absoluteUrl = $this->prepareUri($url, $resource);
72
-				$vCard = $this->download($absoluteUrl, $username, $sharedSecret);
73
-				$this->atomic(function () use ($calendar, $objectUri, $vCard): void {
74
-					$existingObject = $this->backend->getCalendarObject($calendar->getId(), $objectUri, CalDavBackend::CALENDAR_TYPE_FEDERATED);
75
-					if (!$existingObject) {
76
-						$this->backend->createCalendarObject($calendar->getId(), $objectUri, $vCard, CalDavBackend::CALENDAR_TYPE_FEDERATED);
77
-					} else {
78
-						$this->backend->updateCalendarObject($calendar->getId(), $objectUri, $vCard, CalDavBackend::CALENDAR_TYPE_FEDERATED);
79
-					}
80
-				}, $this->dbConnection);
81
-				$downloadedEvents++;
82
-			} else {
83
-				$this->backend->deleteCalendarObject($calendar->getId(), $objectUri, CalDavBackend::CALENDAR_TYPE_FEDERATED, true);
84
-			}
85
-		}
66
+        // TODO: use multi-get for download
67
+        $downloadedEvents = 0;
68
+        foreach ($response['response'] as $resource => $status) {
69
+            $objectUri = basename($resource);
70
+            if (isset($status[200])) {
71
+                $absoluteUrl = $this->prepareUri($url, $resource);
72
+                $vCard = $this->download($absoluteUrl, $username, $sharedSecret);
73
+                $this->atomic(function () use ($calendar, $objectUri, $vCard): void {
74
+                    $existingObject = $this->backend->getCalendarObject($calendar->getId(), $objectUri, CalDavBackend::CALENDAR_TYPE_FEDERATED);
75
+                    if (!$existingObject) {
76
+                        $this->backend->createCalendarObject($calendar->getId(), $objectUri, $vCard, CalDavBackend::CALENDAR_TYPE_FEDERATED);
77
+                    } else {
78
+                        $this->backend->updateCalendarObject($calendar->getId(), $objectUri, $vCard, CalDavBackend::CALENDAR_TYPE_FEDERATED);
79
+                    }
80
+                }, $this->dbConnection);
81
+                $downloadedEvents++;
82
+            } else {
83
+                $this->backend->deleteCalendarObject($calendar->getId(), $objectUri, CalDavBackend::CALENDAR_TYPE_FEDERATED, true);
84
+            }
85
+        }
86 86
 
87
-		return new SyncServiceResult(
88
-			$response['token'],
89
-			$downloadedEvents,
90
-		);
91
-	}
87
+        return new SyncServiceResult(
88
+            $response['token'],
89
+            $downloadedEvents,
90
+        );
91
+    }
92 92
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -70,7 +70,7 @@
 block discarded – undo
70 70
 			if (isset($status[200])) {
71 71
 				$absoluteUrl = $this->prepareUri($url, $resource);
72 72
 				$vCard = $this->download($absoluteUrl, $username, $sharedSecret);
73
-				$this->atomic(function () use ($calendar, $objectUri, $vCard): void {
73
+				$this->atomic(function() use ($calendar, $objectUri, $vCard): void {
74 74
 					$existingObject = $this->backend->getCalendarObject($calendar->getId(), $objectUri, CalDavBackend::CALENDAR_TYPE_FEDERATED);
75 75
 					if (!$existingObject) {
76 76
 						$this->backend->createCalendarObject($calendar->getId(), $objectUri, $vCard, CalDavBackend::CALENDAR_TYPE_FEDERATED);
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Federation/RemoteUserCalendarHome.php 1 patch
Indentation   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -18,50 +18,50 @@
 block discarded – undo
18 18
 use Sabre\DAV\Exception\NotFound;
19 19
 
20 20
 class RemoteUserCalendarHome extends CalendarHome {
21
-	public function __construct(
22
-		Backend\BackendInterface $caldavBackend,
23
-		$principalInfo,
24
-		private readonly IL10N $l10n,
25
-		private readonly IConfig $config,
26
-		private readonly LoggerInterface $logger,
27
-	) {
28
-		parent::__construct($caldavBackend, $principalInfo);
29
-	}
21
+    public function __construct(
22
+        Backend\BackendInterface $caldavBackend,
23
+        $principalInfo,
24
+        private readonly IL10N $l10n,
25
+        private readonly IConfig $config,
26
+        private readonly LoggerInterface $logger,
27
+    ) {
28
+        parent::__construct($caldavBackend, $principalInfo);
29
+    }
30 30
 
31
-	public function getChild($name) {
32
-		// Remote users can only have incoming shared calendars so we can skip the rest of a regular
33
-		// calendar home
34
-		foreach ($this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']) as $calendar) {
35
-			if ($calendar['uri'] === $name) {
36
-				return new Calendar(
37
-					$this->caldavBackend,
38
-					$calendar,
39
-					$this->l10n,
40
-					$this->config,
41
-					$this->logger,
42
-				);
43
-			}
44
-		}
31
+    public function getChild($name) {
32
+        // Remote users can only have incoming shared calendars so we can skip the rest of a regular
33
+        // calendar home
34
+        foreach ($this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']) as $calendar) {
35
+            if ($calendar['uri'] === $name) {
36
+                return new Calendar(
37
+                    $this->caldavBackend,
38
+                    $calendar,
39
+                    $this->l10n,
40
+                    $this->config,
41
+                    $this->logger,
42
+                );
43
+            }
44
+        }
45 45
 
46
-		throw new NotFound("Node with name $name could not be found");
47
-	}
46
+        throw new NotFound("Node with name $name could not be found");
47
+    }
48 48
 
49
-	public function getChildren(): array {
50
-		$objects = [];
49
+    public function getChildren(): array {
50
+        $objects = [];
51 51
 
52
-		// Remote users can only have incoming shared calendars so we can skip the rest of a regular
53
-		// calendar home
54
-		$calendars = $this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']);
55
-		foreach ($calendars as $calendar) {
56
-			$objects[] = new Calendar(
57
-				$this->caldavBackend,
58
-				$calendar,
59
-				$this->l10n,
60
-				$this->config,
61
-				$this->logger,
62
-			);
63
-		}
52
+        // Remote users can only have incoming shared calendars so we can skip the rest of a regular
53
+        // calendar home
54
+        $calendars = $this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']);
55
+        foreach ($calendars as $calendar) {
56
+            $objects[] = new Calendar(
57
+                $this->caldavBackend,
58
+                $calendar,
59
+                $this->l10n,
60
+                $this->config,
61
+                $this->logger,
62
+            );
63
+        }
64 64
 
65
-		return $objects;
66
-	}
65
+        return $objects;
66
+    }
67 67
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Federation/FederatedCalendarEntity.php 2 patches
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -41,61 +41,61 @@
 block discarded – undo
41 41
  * @method void setComponents(string $components)
42 42
  */
43 43
 class FederatedCalendarEntity extends Entity {
44
-	protected string $principaluri = '';
45
-	protected string $uri = '';
46
-	protected string $displayName = '';
47
-	protected ?string $color = null;
48
-	protected int $permissions = 0;
49
-	protected int $syncToken = 0;
50
-	protected string $remoteUrl = '';
51
-	protected string $token = '';
52
-	protected ?int $lastSync = null;
53
-	protected string $sharedBy = '';
54
-	protected string $sharedByDisplayName = '';
55
-	protected string $components = '';
44
+    protected string $principaluri = '';
45
+    protected string $uri = '';
46
+    protected string $displayName = '';
47
+    protected ?string $color = null;
48
+    protected int $permissions = 0;
49
+    protected int $syncToken = 0;
50
+    protected string $remoteUrl = '';
51
+    protected string $token = '';
52
+    protected ?int $lastSync = null;
53
+    protected string $sharedBy = '';
54
+    protected string $sharedByDisplayName = '';
55
+    protected string $components = '';
56 56
 
57
-	public function __construct() {
58
-		$this->addType('principaluri', Types::STRING);
59
-		$this->addType('uri', Types::STRING);
60
-		$this->addType('color', Types::STRING);
61
-		$this->addType('displayName', Types::STRING);
62
-		$this->addType('permissions', Types::INTEGER);
63
-		$this->addType('syncToken', Types::INTEGER);
64
-		$this->addType('remoteUrl', Types::STRING);
65
-		$this->addType('token', Types::STRING);
66
-		$this->addType('lastSync', Types::INTEGER);
67
-		$this->addType('sharedBy', Types::STRING);
68
-		$this->addType('sharedByDisplayName', Types::STRING);
69
-		$this->addType('components', Types::STRING);
70
-	}
57
+    public function __construct() {
58
+        $this->addType('principaluri', Types::STRING);
59
+        $this->addType('uri', Types::STRING);
60
+        $this->addType('color', Types::STRING);
61
+        $this->addType('displayName', Types::STRING);
62
+        $this->addType('permissions', Types::INTEGER);
63
+        $this->addType('syncToken', Types::INTEGER);
64
+        $this->addType('remoteUrl', Types::STRING);
65
+        $this->addType('token', Types::STRING);
66
+        $this->addType('lastSync', Types::INTEGER);
67
+        $this->addType('sharedBy', Types::STRING);
68
+        $this->addType('sharedByDisplayName', Types::STRING);
69
+        $this->addType('components', Types::STRING);
70
+    }
71 71
 
72
-	public function getSyncTokenForSabre(): string {
73
-		return 'http://sabre.io/ns/sync/' . $this->getSyncToken();
74
-	}
72
+    public function getSyncTokenForSabre(): string {
73
+        return 'http://sabre.io/ns/sync/' . $this->getSyncToken();
74
+    }
75 75
 
76
-	public function getSharedByPrincipal(): string {
77
-		return RemoteUserPrincipalBackend::PRINCIPAL_PREFIX . '/' . base64_encode($this->getSharedBy());
78
-	}
76
+    public function getSharedByPrincipal(): string {
77
+        return RemoteUserPrincipalBackend::PRINCIPAL_PREFIX . '/' . base64_encode($this->getSharedBy());
78
+    }
79 79
 
80
-	public function getSupportedCalendarComponentSet(): SupportedCalendarComponentSet {
81
-		$components = explode(',', $this->getComponents());
82
-		return new SupportedCalendarComponentSet($components);
83
-	}
80
+    public function getSupportedCalendarComponentSet(): SupportedCalendarComponentSet {
81
+        $components = explode(',', $this->getComponents());
82
+        return new SupportedCalendarComponentSet($components);
83
+    }
84 84
 
85
-	public function toCalendarInfo(): array {
86
-		return [
87
-			'id' => $this->getId(),
88
-			'uri' => $this->getUri(),
89
-			'principaluri' => $this->getPrincipaluri(),
90
-			'federated' => 1,
85
+    public function toCalendarInfo(): array {
86
+        return [
87
+            'id' => $this->getId(),
88
+            'uri' => $this->getUri(),
89
+            'principaluri' => $this->getPrincipaluri(),
90
+            'federated' => 1,
91 91
 
92
-			'{DAV:}displayname' => $this->getDisplayName(),
93
-			'{http://sabredav.org/ns}sync-token' => $this->getSyncToken(),
94
-			'{' . \Sabre\CalDAV\Plugin::NS_CALENDARSERVER . '}getctag' => $this->getSyncTokenForSabre(),
95
-			'{' . \Sabre\CalDAV\Plugin::NS_CALDAV . '}supported-calendar-component-set' => $this->getSupportedCalendarComponentSet(),
96
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->getSharedByPrincipal(),
97
-			// TODO: implement read-write sharing
98
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => 1
99
-		];
100
-	}
92
+            '{DAV:}displayname' => $this->getDisplayName(),
93
+            '{http://sabredav.org/ns}sync-token' => $this->getSyncToken(),
94
+            '{' . \Sabre\CalDAV\Plugin::NS_CALENDARSERVER . '}getctag' => $this->getSyncTokenForSabre(),
95
+            '{' . \Sabre\CalDAV\Plugin::NS_CALDAV . '}supported-calendar-component-set' => $this->getSupportedCalendarComponentSet(),
96
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->getSharedByPrincipal(),
97
+            // TODO: implement read-write sharing
98
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => 1
99
+        ];
100
+    }
101 101
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -70,11 +70,11 @@  discard block
 block discarded – undo
70 70
 	}
71 71
 
72 72
 	public function getSyncTokenForSabre(): string {
73
-		return 'http://sabre.io/ns/sync/' . $this->getSyncToken();
73
+		return 'http://sabre.io/ns/sync/'.$this->getSyncToken();
74 74
 	}
75 75
 
76 76
 	public function getSharedByPrincipal(): string {
77
-		return RemoteUserPrincipalBackend::PRINCIPAL_PREFIX . '/' . base64_encode($this->getSharedBy());
77
+		return RemoteUserPrincipalBackend::PRINCIPAL_PREFIX.'/'.base64_encode($this->getSharedBy());
78 78
 	}
79 79
 
80 80
 	public function getSupportedCalendarComponentSet(): SupportedCalendarComponentSet {
@@ -91,11 +91,11 @@  discard block
 block discarded – undo
91 91
 
92 92
 			'{DAV:}displayname' => $this->getDisplayName(),
93 93
 			'{http://sabredav.org/ns}sync-token' => $this->getSyncToken(),
94
-			'{' . \Sabre\CalDAV\Plugin::NS_CALENDARSERVER . '}getctag' => $this->getSyncTokenForSabre(),
95
-			'{' . \Sabre\CalDAV\Plugin::NS_CALDAV . '}supported-calendar-component-set' => $this->getSupportedCalendarComponentSet(),
96
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->getSharedByPrincipal(),
94
+			'{'.\Sabre\CalDAV\Plugin::NS_CALENDARSERVER.'}getctag' => $this->getSyncTokenForSabre(),
95
+			'{'.\Sabre\CalDAV\Plugin::NS_CALDAV.'}supported-calendar-component-set' => $this->getSupportedCalendarComponentSet(),
96
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->getSharedByPrincipal(),
97 97
 			// TODO: implement read-write sharing
98
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => 1
98
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => 1
99 99
 		];
100 100
 	}
101 101
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Federation/FederationSharingService.php 2 patches
Indentation   +151 added lines, -151 removed lines patch added patch discarded remove patch
@@ -26,155 +26,155 @@
 block discarded – undo
26 26
 // TODO: Convert this to an abstract service like the addressbook/calendar sharing services once we
27 27
 //       support addressbook federation as well.
28 28
 class FederationSharingService {
29
-	public function __construct(
30
-		private readonly ICloudFederationProviderManager $federationManager,
31
-		private readonly ICloudFederationFactory $federationFactory,
32
-		private readonly IUserManager $userManager,
33
-		private readonly IURLGenerator $url,
34
-		private readonly LoggerInterface $logger,
35
-		private readonly ISecureRandom $random,
36
-		private readonly SharingMapper $sharingMapper,
37
-	) {
38
-	}
39
-
40
-	/**
41
-	 * Decode a (base64) encoded remote user principal and return the remote user's cloud id. Will
42
-	 * return null if the given principal is not belonging to a remote user (or has an invalid
43
-	 * format).
44
-	 *
45
-	 * The remote user/cloud id needs to be encoded as it might contain slashes.
46
-	 */
47
-	private function decodeRemoteUserPrincipal(string $principal): ?string {
48
-		// Expected format: principals/remote-users/abcdef123
49
-		[$prefix, $collection, $encodedId] = explode('/', $principal);
50
-		if ($prefix !== 'principals' || $collection !== 'remote-users') {
51
-			return null;
52
-		}
53
-
54
-		$decodedId = base64_decode($encodedId);
55
-		if (!is_string($decodedId)) {
56
-			return null;
57
-		}
58
-
59
-		return $decodedId;
60
-	}
61
-
62
-	/**
63
-	 * Send a calendar share to a remote instance and create a federated share locally if it is
64
-	 * accepted.
65
-	 *
66
-	 * @param IShareable $shareable The calendar to be shared.
67
-	 * @param string $principal The principal to share with (should be a remote user principal).
68
-	 * @param int $access The access level. The remote serve might reject it.
69
-	 */
70
-	public function shareWith(IShareable $shareable, string $principal, int $access): void {
71
-		$baseError = 'Failed to create federated calendar share: ';
72
-
73
-		// 1. Validate share data
74
-		$shareWith = $this->decodeRemoteUserPrincipal($principal);
75
-		if ($shareWith === null) {
76
-			$this->logger->error($baseError . 'Principal of sharee is not belonging to a remote user', [
77
-				'shareable' => $shareable->getName(),
78
-				'encodedShareWith' => $principal,
79
-			]);
80
-			return;
81
-		}
82
-
83
-		[,, $ownerUid] = explode('/', $shareable->getOwner());
84
-		$owner = $this->userManager->get($ownerUid);
85
-		if ($owner === null) {
86
-			$this->logger->error($baseError . 'Shareable is not owned by a user on this server', [
87
-				'shareable' => $shareable->getName(),
88
-				'shareWith' => $shareWith,
89
-			]);
90
-			return;
91
-		}
92
-
93
-		// Need a calendar instance to extract properties for the protocol
94
-		$calendar = $shareable;
95
-		if (!($calendar instanceof Calendar)) {
96
-			$this->logger->error($baseError . 'Shareable is not a calendar', [
97
-				'shareable' => $shareable->getName(),
98
-				'owner' => $owner,
99
-				'shareWith' => $shareWith,
100
-			]);
101
-			return;
102
-		}
103
-
104
-		$getProp = static fn (string $prop) => $calendar->getProperties([$prop])[$prop] ?? null;
105
-
106
-		$displayName = $getProp('{DAV:}displayname') ?? '';
107
-
108
-		$token = $this->random->generate(32);
109
-		$share = $this->federationFactory->getCloudFederationShare(
110
-			$shareWith,
111
-			$shareable->getName(),
112
-			$displayName,
113
-			CalendarFederationProvider::PROVIDER_ID,
114
-			// Resharing is not possible so the owner is always the sharer
115
-			$owner->getCloudId(),
116
-			$owner->getDisplayName(),
117
-			$owner->getCloudId(),
118
-			$owner->getDisplayName(),
119
-			$token,
120
-			CalendarFederationProvider::USER_SHARE_TYPE,
121
-			CalendarFederationProvider::CALENDAR_RESOURCE,
122
-		);
123
-
124
-		// 2. Send share to federated instance
125
-		$shareWithEncoded = base64_encode($shareWith);
126
-		$relativeCalendarUrl = "remote-calendars/$shareWithEncoded/" . $calendar->getName() . '_shared_by_' . $ownerUid;
127
-		$calendarUrl = $this->url->linkTo('', 'remote.php') . "/dav/$relativeCalendarUrl";
128
-		$calendarUrl = $this->url->getAbsoluteURL($calendarUrl);
129
-		$protocol = new CalendarFederationProtocolV1();
130
-		$protocol->setUrl($calendarUrl);
131
-		$protocol->setDisplayName($displayName);
132
-		$protocol->setColor($getProp('{http://apple.com/ns/ical/}calendar-color'));
133
-		$protocol->setAccess($access);
134
-		$protocol->setComponents(implode(',', $getProp(
135
-			'{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set')?->getValue() ?? [],
136
-		));
137
-		$share->setProtocol([
138
-			// Preserve original protocol contents
139
-			...$share->getProtocol(),
140
-			...$protocol->toProtocol(),
141
-		]);
142
-
143
-		try {
144
-			$response = $this->federationManager->sendCloudShare($share);
145
-		} catch (OCMProviderException $e) {
146
-			$this->logger->error($baseError . $e->getMessage(), [
147
-				'exception' => $e,
148
-				'owner' => $owner->getUID(),
149
-				'calendar' => $shareable->getName(),
150
-				'shareWith' => $shareWith,
151
-			]);
152
-			return;
153
-		}
154
-
155
-		if ($response->getStatusCode() !== Http::STATUS_CREATED) {
156
-			$this->logger->error($baseError . 'Server replied with code ' . $response->getStatusCode(), [
157
-				'responseBody' => $response->getBody(),
158
-				'owner' => $owner->getUID(),
159
-				'calendar' => $shareable->getName(),
160
-				'shareWith' => $shareWith,
161
-			]);
162
-			return;
163
-		}
164
-
165
-		// 3. Create a local DAV share to track the token for authentication
166
-		$shareWithPrincipalUri = RemoteUserPrincipalBackend::PRINCIPAL_PREFIX . '/' . $shareWithEncoded;
167
-		$this->sharingMapper->deleteShare(
168
-			$shareable->getResourceId(),
169
-			'calendar',
170
-			$shareWithPrincipalUri,
171
-		);
172
-		$this->sharingMapper->shareWithToken(
173
-			$shareable->getResourceId(),
174
-			'calendar',
175
-			$access,
176
-			$shareWithPrincipalUri,
177
-			$token,
178
-		);
179
-	}
29
+    public function __construct(
30
+        private readonly ICloudFederationProviderManager $federationManager,
31
+        private readonly ICloudFederationFactory $federationFactory,
32
+        private readonly IUserManager $userManager,
33
+        private readonly IURLGenerator $url,
34
+        private readonly LoggerInterface $logger,
35
+        private readonly ISecureRandom $random,
36
+        private readonly SharingMapper $sharingMapper,
37
+    ) {
38
+    }
39
+
40
+    /**
41
+     * Decode a (base64) encoded remote user principal and return the remote user's cloud id. Will
42
+     * return null if the given principal is not belonging to a remote user (or has an invalid
43
+     * format).
44
+     *
45
+     * The remote user/cloud id needs to be encoded as it might contain slashes.
46
+     */
47
+    private function decodeRemoteUserPrincipal(string $principal): ?string {
48
+        // Expected format: principals/remote-users/abcdef123
49
+        [$prefix, $collection, $encodedId] = explode('/', $principal);
50
+        if ($prefix !== 'principals' || $collection !== 'remote-users') {
51
+            return null;
52
+        }
53
+
54
+        $decodedId = base64_decode($encodedId);
55
+        if (!is_string($decodedId)) {
56
+            return null;
57
+        }
58
+
59
+        return $decodedId;
60
+    }
61
+
62
+    /**
63
+     * Send a calendar share to a remote instance and create a federated share locally if it is
64
+     * accepted.
65
+     *
66
+     * @param IShareable $shareable The calendar to be shared.
67
+     * @param string $principal The principal to share with (should be a remote user principal).
68
+     * @param int $access The access level. The remote serve might reject it.
69
+     */
70
+    public function shareWith(IShareable $shareable, string $principal, int $access): void {
71
+        $baseError = 'Failed to create federated calendar share: ';
72
+
73
+        // 1. Validate share data
74
+        $shareWith = $this->decodeRemoteUserPrincipal($principal);
75
+        if ($shareWith === null) {
76
+            $this->logger->error($baseError . 'Principal of sharee is not belonging to a remote user', [
77
+                'shareable' => $shareable->getName(),
78
+                'encodedShareWith' => $principal,
79
+            ]);
80
+            return;
81
+        }
82
+
83
+        [,, $ownerUid] = explode('/', $shareable->getOwner());
84
+        $owner = $this->userManager->get($ownerUid);
85
+        if ($owner === null) {
86
+            $this->logger->error($baseError . 'Shareable is not owned by a user on this server', [
87
+                'shareable' => $shareable->getName(),
88
+                'shareWith' => $shareWith,
89
+            ]);
90
+            return;
91
+        }
92
+
93
+        // Need a calendar instance to extract properties for the protocol
94
+        $calendar = $shareable;
95
+        if (!($calendar instanceof Calendar)) {
96
+            $this->logger->error($baseError . 'Shareable is not a calendar', [
97
+                'shareable' => $shareable->getName(),
98
+                'owner' => $owner,
99
+                'shareWith' => $shareWith,
100
+            ]);
101
+            return;
102
+        }
103
+
104
+        $getProp = static fn (string $prop) => $calendar->getProperties([$prop])[$prop] ?? null;
105
+
106
+        $displayName = $getProp('{DAV:}displayname') ?? '';
107
+
108
+        $token = $this->random->generate(32);
109
+        $share = $this->federationFactory->getCloudFederationShare(
110
+            $shareWith,
111
+            $shareable->getName(),
112
+            $displayName,
113
+            CalendarFederationProvider::PROVIDER_ID,
114
+            // Resharing is not possible so the owner is always the sharer
115
+            $owner->getCloudId(),
116
+            $owner->getDisplayName(),
117
+            $owner->getCloudId(),
118
+            $owner->getDisplayName(),
119
+            $token,
120
+            CalendarFederationProvider::USER_SHARE_TYPE,
121
+            CalendarFederationProvider::CALENDAR_RESOURCE,
122
+        );
123
+
124
+        // 2. Send share to federated instance
125
+        $shareWithEncoded = base64_encode($shareWith);
126
+        $relativeCalendarUrl = "remote-calendars/$shareWithEncoded/" . $calendar->getName() . '_shared_by_' . $ownerUid;
127
+        $calendarUrl = $this->url->linkTo('', 'remote.php') . "/dav/$relativeCalendarUrl";
128
+        $calendarUrl = $this->url->getAbsoluteURL($calendarUrl);
129
+        $protocol = new CalendarFederationProtocolV1();
130
+        $protocol->setUrl($calendarUrl);
131
+        $protocol->setDisplayName($displayName);
132
+        $protocol->setColor($getProp('{http://apple.com/ns/ical/}calendar-color'));
133
+        $protocol->setAccess($access);
134
+        $protocol->setComponents(implode(',', $getProp(
135
+            '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set')?->getValue() ?? [],
136
+        ));
137
+        $share->setProtocol([
138
+            // Preserve original protocol contents
139
+            ...$share->getProtocol(),
140
+            ...$protocol->toProtocol(),
141
+        ]);
142
+
143
+        try {
144
+            $response = $this->federationManager->sendCloudShare($share);
145
+        } catch (OCMProviderException $e) {
146
+            $this->logger->error($baseError . $e->getMessage(), [
147
+                'exception' => $e,
148
+                'owner' => $owner->getUID(),
149
+                'calendar' => $shareable->getName(),
150
+                'shareWith' => $shareWith,
151
+            ]);
152
+            return;
153
+        }
154
+
155
+        if ($response->getStatusCode() !== Http::STATUS_CREATED) {
156
+            $this->logger->error($baseError . 'Server replied with code ' . $response->getStatusCode(), [
157
+                'responseBody' => $response->getBody(),
158
+                'owner' => $owner->getUID(),
159
+                'calendar' => $shareable->getName(),
160
+                'shareWith' => $shareWith,
161
+            ]);
162
+            return;
163
+        }
164
+
165
+        // 3. Create a local DAV share to track the token for authentication
166
+        $shareWithPrincipalUri = RemoteUserPrincipalBackend::PRINCIPAL_PREFIX . '/' . $shareWithEncoded;
167
+        $this->sharingMapper->deleteShare(
168
+            $shareable->getResourceId(),
169
+            'calendar',
170
+            $shareWithPrincipalUri,
171
+        );
172
+        $this->sharingMapper->shareWithToken(
173
+            $shareable->getResourceId(),
174
+            'calendar',
175
+            $access,
176
+            $shareWithPrincipalUri,
177
+            $token,
178
+        );
179
+    }
180 180
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
 		// 1. Validate share data
74 74
 		$shareWith = $this->decodeRemoteUserPrincipal($principal);
75 75
 		if ($shareWith === null) {
76
-			$this->logger->error($baseError . 'Principal of sharee is not belonging to a remote user', [
76
+			$this->logger->error($baseError.'Principal of sharee is not belonging to a remote user', [
77 77
 				'shareable' => $shareable->getName(),
78 78
 				'encodedShareWith' => $principal,
79 79
 			]);
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
 		[,, $ownerUid] = explode('/', $shareable->getOwner());
84 84
 		$owner = $this->userManager->get($ownerUid);
85 85
 		if ($owner === null) {
86
-			$this->logger->error($baseError . 'Shareable is not owned by a user on this server', [
86
+			$this->logger->error($baseError.'Shareable is not owned by a user on this server', [
87 87
 				'shareable' => $shareable->getName(),
88 88
 				'shareWith' => $shareWith,
89 89
 			]);
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
 		// Need a calendar instance to extract properties for the protocol
94 94
 		$calendar = $shareable;
95 95
 		if (!($calendar instanceof Calendar)) {
96
-			$this->logger->error($baseError . 'Shareable is not a calendar', [
96
+			$this->logger->error($baseError.'Shareable is not a calendar', [
97 97
 				'shareable' => $shareable->getName(),
98 98
 				'owner' => $owner,
99 99
 				'shareWith' => $shareWith,
@@ -123,8 +123,8 @@  discard block
 block discarded – undo
123 123
 
124 124
 		// 2. Send share to federated instance
125 125
 		$shareWithEncoded = base64_encode($shareWith);
126
-		$relativeCalendarUrl = "remote-calendars/$shareWithEncoded/" . $calendar->getName() . '_shared_by_' . $ownerUid;
127
-		$calendarUrl = $this->url->linkTo('', 'remote.php') . "/dav/$relativeCalendarUrl";
126
+		$relativeCalendarUrl = "remote-calendars/$shareWithEncoded/".$calendar->getName().'_shared_by_'.$ownerUid;
127
+		$calendarUrl = $this->url->linkTo('', 'remote.php')."/dav/$relativeCalendarUrl";
128 128
 		$calendarUrl = $this->url->getAbsoluteURL($calendarUrl);
129 129
 		$protocol = new CalendarFederationProtocolV1();
130 130
 		$protocol->setUrl($calendarUrl);
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 		try {
144 144
 			$response = $this->federationManager->sendCloudShare($share);
145 145
 		} catch (OCMProviderException $e) {
146
-			$this->logger->error($baseError . $e->getMessage(), [
146
+			$this->logger->error($baseError.$e->getMessage(), [
147 147
 				'exception' => $e,
148 148
 				'owner' => $owner->getUID(),
149 149
 				'calendar' => $shareable->getName(),
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
 		}
154 154
 
155 155
 		if ($response->getStatusCode() !== Http::STATUS_CREATED) {
156
-			$this->logger->error($baseError . 'Server replied with code ' . $response->getStatusCode(), [
156
+			$this->logger->error($baseError.'Server replied with code '.$response->getStatusCode(), [
157 157
 				'responseBody' => $response->getBody(),
158 158
 				'owner' => $owner->getUID(),
159 159
 				'calendar' => $shareable->getName(),
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 		}
164 164
 
165 165
 		// 3. Create a local DAV share to track the token for authentication
166
-		$shareWithPrincipalUri = RemoteUserPrincipalBackend::PRINCIPAL_PREFIX . '/' . $shareWithEncoded;
166
+		$shareWithPrincipalUri = RemoteUserPrincipalBackend::PRINCIPAL_PREFIX.'/'.$shareWithEncoded;
167 167
 		$this->sharingMapper->deleteShare(
168 168
 			$shareable->getResourceId(),
169 169
 			'calendar',
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Federation/CalendarFederationProvider.php 2 patches
Indentation   +175 added lines, -175 removed lines patch added patch discarded remove patch
@@ -25,179 +25,179 @@
 block discarded – undo
25 25
 use Psr\Log\LoggerInterface;
26 26
 
27 27
 class CalendarFederationProvider implements ICloudFederationProvider {
28
-	public const PROVIDER_ID = 'calendar';
29
-	public const CALENDAR_RESOURCE = 'calendar';
30
-	public const USER_SHARE_TYPE = 'user';
31
-
32
-	public function __construct(
33
-		private readonly LoggerInterface $logger,
34
-		private readonly FederatedCalendarMapper $federatedCalendarMapper,
35
-		private readonly CalendarFederationConfig $calendarFederationConfig,
36
-		private readonly IJobList $jobList,
37
-		private readonly ICloudIdManager $cloudIdManager,
38
-	) {
39
-	}
40
-
41
-	public function getShareType(): string {
42
-		return self::PROVIDER_ID;
43
-	}
44
-
45
-	public function shareReceived(ICloudFederationShare $share): string {
46
-		if (!$this->calendarFederationConfig->isFederationEnabled()) {
47
-			$this->logger->debug('Received a federation invite but federation is disabled');
48
-			throw new ProviderCouldNotAddShareException(
49
-				'Server does not support calendar federation',
50
-				'',
51
-				Http::STATUS_SERVICE_UNAVAILABLE,
52
-			);
53
-		}
54
-
55
-		if (!in_array($share->getShareType(), $this->getSupportedShareTypes(), true)) {
56
-			$this->logger->debug('Received a federation invite for invalid share type');
57
-			throw new ProviderCouldNotAddShareException(
58
-				'Support for sharing with non-users not implemented yet',
59
-				'',
60
-				Http::STATUS_NOT_IMPLEMENTED,
61
-			);
62
-			// TODO: Implement group shares
63
-		}
64
-
65
-		$rawProtocol = $share->getProtocol();
66
-		switch ($rawProtocol[ICalendarFederationProtocol::PROP_VERSION]) {
67
-			case CalendarFederationProtocolV1::VERSION:
68
-				try {
69
-					$protocol = CalendarFederationProtocolV1::parse($rawProtocol);
70
-				} catch (Protocol\CalendarProtocolParseException $e) {
71
-					throw new ProviderCouldNotAddShareException(
72
-						'Invalid protocol data (v1)',
73
-						'',
74
-						Http::STATUS_BAD_REQUEST,
75
-					);
76
-				}
77
-				$calendarUrl = $protocol->getUrl();
78
-				$displayName = $protocol->getDisplayName();
79
-				$color = $protocol->getColor();
80
-				$access = $protocol->getAccess();
81
-				$components = $protocol->getComponents();
82
-				break;
83
-			default:
84
-				throw new ProviderCouldNotAddShareException(
85
-					'Unknown protocol version',
86
-					'',
87
-					Http::STATUS_BAD_REQUEST,
88
-				);
89
-		}
90
-
91
-		if (!$calendarUrl || !$displayName) {
92
-			throw new ProviderCouldNotAddShareException(
93
-				'Incomplete protocol data',
94
-				'',
95
-				Http::STATUS_BAD_REQUEST,
96
-			);
97
-		}
98
-
99
-		// TODO: implement read-write sharing
100
-		$permissions = match ($access) {
101
-			DavSharingBackend::ACCESS_READ => Constants::PERMISSION_READ,
102
-			default => throw new ProviderCouldNotAddShareException(
103
-				"Unsupported access value: $access",
104
-				'',
105
-				Http::STATUS_BAD_REQUEST,
106
-			),
107
-		};
108
-
109
-		// The calendar uri is the local name of the calendar. As such it must not contain slashes.
110
-		// Just use the hashed url for simplicity here.
111
-		// Example: calendars/foo-bar-user/<calendar-uri>
112
-		$calendarUri = hash('md5', $calendarUrl);
113
-
114
-		$sharedWithPrincipal = 'principals/users/' . $share->getShareWith();
115
-
116
-		// Delete existing incoming federated share first
117
-		$this->federatedCalendarMapper->deleteByUri($sharedWithPrincipal, $calendarUri);
118
-
119
-		$calendar = new FederatedCalendarEntity();
120
-		$calendar->setPrincipaluri($sharedWithPrincipal);
121
-		$calendar->setUri($calendarUri);
122
-		$calendar->setRemoteUrl($calendarUrl);
123
-		$calendar->setDisplayName($displayName);
124
-		$calendar->setColor($color);
125
-		$calendar->setToken($share->getShareSecret());
126
-		$calendar->setSharedBy($share->getSharedBy());
127
-		$calendar->setSharedByDisplayName($share->getSharedByDisplayName());
128
-		$calendar->setPermissions($permissions);
129
-		$calendar->setComponents($components);
130
-		$calendar = $this->federatedCalendarMapper->insert($calendar);
131
-
132
-		$this->jobList->add(FederatedCalendarSyncJob::class, [
133
-			FederatedCalendarSyncJob::ARGUMENT_ID => $calendar->getId(),
134
-		]);
135
-
136
-		return (string)$calendar->getId();
137
-	}
138
-
139
-	public function notificationReceived(
140
-		$notificationType,
141
-		$providerId,
142
-		array $notification,
143
-	): array {
144
-		if ($providerId !== self::PROVIDER_ID) {
145
-			throw new BadRequestException(['providerId']);
146
-		}
147
-
148
-		switch ($notificationType) {
149
-			case CalendarFederationNotifier::NOTIFICATION_SYNC_CALENDAR:
150
-				return $this->handleSyncCalendarNotification($notification);
151
-			default:
152
-				return [];
153
-		}
154
-	}
155
-
156
-	/**
157
-	 * @return string[]
158
-	 */
159
-	public function getSupportedShareTypes(): array {
160
-		return [self::USER_SHARE_TYPE];
161
-	}
162
-
163
-	/**
164
-	 * @throws BadRequestException If notification props are missing.
165
-	 * @throws ShareNotFound If the notification is not related to a known share.
166
-	 */
167
-	private function handleSyncCalendarNotification(array $notification): array {
168
-		$sharedSecret = $notification['sharedSecret'];
169
-		$shareWithRaw = $notification[CalendarFederationNotifier::PROP_SYNC_CALENDAR_SHARE_WITH] ?? null;
170
-		$calendarUrl = $notification[CalendarFederationNotifier::PROP_SYNC_CALENDAR_CALENDAR_URL] ?? null;
171
-
172
-		if ($shareWithRaw === null || $shareWithRaw === '') {
173
-			throw new BadRequestException([CalendarFederationNotifier::PROP_SYNC_CALENDAR_SHARE_WITH]);
174
-		}
175
-
176
-		if ($calendarUrl === null || $calendarUrl === '') {
177
-			throw new BadRequestException([CalendarFederationNotifier::PROP_SYNC_CALENDAR_CALENDAR_URL]);
178
-		}
179
-
180
-		try {
181
-			$shareWith = $this->cloudIdManager->resolveCloudId($shareWithRaw);
182
-		} catch (\InvalidArgumentException $e) {
183
-			throw new ShareNotFound('Invalid sharee cloud id');
184
-		}
185
-
186
-		$calendars = $this->federatedCalendarMapper->findByRemoteUrl(
187
-			$calendarUrl,
188
-			'principals/users/' . $shareWith->getUser(),
189
-			$sharedSecret,
190
-		);
191
-		if (empty($calendars)) {
192
-			throw new ShareNotFound('Calendar is not shared with the sharee');
193
-		}
194
-
195
-		foreach ($calendars as $calendar) {
196
-			$this->jobList->add(FederatedCalendarSyncJob::class, [
197
-				FederatedCalendarSyncJob::ARGUMENT_ID => $calendar->getId(),
198
-			]);
199
-		}
200
-
201
-		return [];
202
-	}
28
+    public const PROVIDER_ID = 'calendar';
29
+    public const CALENDAR_RESOURCE = 'calendar';
30
+    public const USER_SHARE_TYPE = 'user';
31
+
32
+    public function __construct(
33
+        private readonly LoggerInterface $logger,
34
+        private readonly FederatedCalendarMapper $federatedCalendarMapper,
35
+        private readonly CalendarFederationConfig $calendarFederationConfig,
36
+        private readonly IJobList $jobList,
37
+        private readonly ICloudIdManager $cloudIdManager,
38
+    ) {
39
+    }
40
+
41
+    public function getShareType(): string {
42
+        return self::PROVIDER_ID;
43
+    }
44
+
45
+    public function shareReceived(ICloudFederationShare $share): string {
46
+        if (!$this->calendarFederationConfig->isFederationEnabled()) {
47
+            $this->logger->debug('Received a federation invite but federation is disabled');
48
+            throw new ProviderCouldNotAddShareException(
49
+                'Server does not support calendar federation',
50
+                '',
51
+                Http::STATUS_SERVICE_UNAVAILABLE,
52
+            );
53
+        }
54
+
55
+        if (!in_array($share->getShareType(), $this->getSupportedShareTypes(), true)) {
56
+            $this->logger->debug('Received a federation invite for invalid share type');
57
+            throw new ProviderCouldNotAddShareException(
58
+                'Support for sharing with non-users not implemented yet',
59
+                '',
60
+                Http::STATUS_NOT_IMPLEMENTED,
61
+            );
62
+            // TODO: Implement group shares
63
+        }
64
+
65
+        $rawProtocol = $share->getProtocol();
66
+        switch ($rawProtocol[ICalendarFederationProtocol::PROP_VERSION]) {
67
+            case CalendarFederationProtocolV1::VERSION:
68
+                try {
69
+                    $protocol = CalendarFederationProtocolV1::parse($rawProtocol);
70
+                } catch (Protocol\CalendarProtocolParseException $e) {
71
+                    throw new ProviderCouldNotAddShareException(
72
+                        'Invalid protocol data (v1)',
73
+                        '',
74
+                        Http::STATUS_BAD_REQUEST,
75
+                    );
76
+                }
77
+                $calendarUrl = $protocol->getUrl();
78
+                $displayName = $protocol->getDisplayName();
79
+                $color = $protocol->getColor();
80
+                $access = $protocol->getAccess();
81
+                $components = $protocol->getComponents();
82
+                break;
83
+            default:
84
+                throw new ProviderCouldNotAddShareException(
85
+                    'Unknown protocol version',
86
+                    '',
87
+                    Http::STATUS_BAD_REQUEST,
88
+                );
89
+        }
90
+
91
+        if (!$calendarUrl || !$displayName) {
92
+            throw new ProviderCouldNotAddShareException(
93
+                'Incomplete protocol data',
94
+                '',
95
+                Http::STATUS_BAD_REQUEST,
96
+            );
97
+        }
98
+
99
+        // TODO: implement read-write sharing
100
+        $permissions = match ($access) {
101
+            DavSharingBackend::ACCESS_READ => Constants::PERMISSION_READ,
102
+            default => throw new ProviderCouldNotAddShareException(
103
+                "Unsupported access value: $access",
104
+                '',
105
+                Http::STATUS_BAD_REQUEST,
106
+            ),
107
+        };
108
+
109
+        // The calendar uri is the local name of the calendar. As such it must not contain slashes.
110
+        // Just use the hashed url for simplicity here.
111
+        // Example: calendars/foo-bar-user/<calendar-uri>
112
+        $calendarUri = hash('md5', $calendarUrl);
113
+
114
+        $sharedWithPrincipal = 'principals/users/' . $share->getShareWith();
115
+
116
+        // Delete existing incoming federated share first
117
+        $this->federatedCalendarMapper->deleteByUri($sharedWithPrincipal, $calendarUri);
118
+
119
+        $calendar = new FederatedCalendarEntity();
120
+        $calendar->setPrincipaluri($sharedWithPrincipal);
121
+        $calendar->setUri($calendarUri);
122
+        $calendar->setRemoteUrl($calendarUrl);
123
+        $calendar->setDisplayName($displayName);
124
+        $calendar->setColor($color);
125
+        $calendar->setToken($share->getShareSecret());
126
+        $calendar->setSharedBy($share->getSharedBy());
127
+        $calendar->setSharedByDisplayName($share->getSharedByDisplayName());
128
+        $calendar->setPermissions($permissions);
129
+        $calendar->setComponents($components);
130
+        $calendar = $this->federatedCalendarMapper->insert($calendar);
131
+
132
+        $this->jobList->add(FederatedCalendarSyncJob::class, [
133
+            FederatedCalendarSyncJob::ARGUMENT_ID => $calendar->getId(),
134
+        ]);
135
+
136
+        return (string)$calendar->getId();
137
+    }
138
+
139
+    public function notificationReceived(
140
+        $notificationType,
141
+        $providerId,
142
+        array $notification,
143
+    ): array {
144
+        if ($providerId !== self::PROVIDER_ID) {
145
+            throw new BadRequestException(['providerId']);
146
+        }
147
+
148
+        switch ($notificationType) {
149
+            case CalendarFederationNotifier::NOTIFICATION_SYNC_CALENDAR:
150
+                return $this->handleSyncCalendarNotification($notification);
151
+            default:
152
+                return [];
153
+        }
154
+    }
155
+
156
+    /**
157
+     * @return string[]
158
+     */
159
+    public function getSupportedShareTypes(): array {
160
+        return [self::USER_SHARE_TYPE];
161
+    }
162
+
163
+    /**
164
+     * @throws BadRequestException If notification props are missing.
165
+     * @throws ShareNotFound If the notification is not related to a known share.
166
+     */
167
+    private function handleSyncCalendarNotification(array $notification): array {
168
+        $sharedSecret = $notification['sharedSecret'];
169
+        $shareWithRaw = $notification[CalendarFederationNotifier::PROP_SYNC_CALENDAR_SHARE_WITH] ?? null;
170
+        $calendarUrl = $notification[CalendarFederationNotifier::PROP_SYNC_CALENDAR_CALENDAR_URL] ?? null;
171
+
172
+        if ($shareWithRaw === null || $shareWithRaw === '') {
173
+            throw new BadRequestException([CalendarFederationNotifier::PROP_SYNC_CALENDAR_SHARE_WITH]);
174
+        }
175
+
176
+        if ($calendarUrl === null || $calendarUrl === '') {
177
+            throw new BadRequestException([CalendarFederationNotifier::PROP_SYNC_CALENDAR_CALENDAR_URL]);
178
+        }
179
+
180
+        try {
181
+            $shareWith = $this->cloudIdManager->resolveCloudId($shareWithRaw);
182
+        } catch (\InvalidArgumentException $e) {
183
+            throw new ShareNotFound('Invalid sharee cloud id');
184
+        }
185
+
186
+        $calendars = $this->federatedCalendarMapper->findByRemoteUrl(
187
+            $calendarUrl,
188
+            'principals/users/' . $shareWith->getUser(),
189
+            $sharedSecret,
190
+        );
191
+        if (empty($calendars)) {
192
+            throw new ShareNotFound('Calendar is not shared with the sharee');
193
+        }
194
+
195
+        foreach ($calendars as $calendar) {
196
+            $this->jobList->add(FederatedCalendarSyncJob::class, [
197
+                FederatedCalendarSyncJob::ARGUMENT_ID => $calendar->getId(),
198
+            ]);
199
+        }
200
+
201
+        return [];
202
+    }
203 203
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
 		// Example: calendars/foo-bar-user/<calendar-uri>
112 112
 		$calendarUri = hash('md5', $calendarUrl);
113 113
 
114
-		$sharedWithPrincipal = 'principals/users/' . $share->getShareWith();
114
+		$sharedWithPrincipal = 'principals/users/'.$share->getShareWith();
115 115
 
116 116
 		// Delete existing incoming federated share first
117 117
 		$this->federatedCalendarMapper->deleteByUri($sharedWithPrincipal, $calendarUri);
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 			FederatedCalendarSyncJob::ARGUMENT_ID => $calendar->getId(),
134 134
 		]);
135 135
 
136
-		return (string)$calendar->getId();
136
+		return (string) $calendar->getId();
137 137
 	}
138 138
 
139 139
 	public function notificationReceived(
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
 
186 186
 		$calendars = $this->federatedCalendarMapper->findByRemoteUrl(
187 187
 			$calendarUrl,
188
-			'principals/users/' . $shareWith->getUser(),
188
+			'principals/users/'.$shareWith->getUser(),
189 189
 			$sharedSecret,
190 190
 		);
191 191
 		if (empty($calendars)) {
Please login to merge, or discard this patch.