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