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