Passed
Push — master ( 943eef...4dc8a4 )
by Daniel
27:23 queued 13:37
created
apps/dav/lib/CalDAV/CalDavBackend.php 2 patches
Indentation   +3036 added lines, -3036 removed lines patch added patch discarded remove patch
@@ -113,3040 +113,3040 @@
 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
-	public function getDeletedCalendarObjectsByPrincipal(string $principalUri): array {
1102
-		$query = $this->db->getQueryBuilder();
1103
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1104
-			->selectAlias('c.uri', 'calendaruri')
1105
-			->from('calendarobjects', 'co')
1106
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1107
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1108
-			->andWhere($query->expr()->isNotNull('co.deleted_at'));
1109
-		$stmt = $query->executeQuery();
1110
-
1111
-		$result = [];
1112
-		while ($row = $stmt->fetch()) {
1113
-			$result[] = [
1114
-				'id' => $row['id'],
1115
-				'uri' => $row['uri'],
1116
-				'lastmodified' => $row['lastmodified'],
1117
-				'etag' => '"' . $row['etag'] . '"',
1118
-				'calendarid' => $row['calendarid'],
1119
-				'calendaruri' => $row['calendaruri'],
1120
-				'size' => (int)$row['size'],
1121
-				'component' => strtolower($row['componenttype']),
1122
-				'classification' => (int)$row['classification'],
1123
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'],
1124
-			];
1125
-		}
1126
-		$stmt->closeCursor();
1127
-
1128
-		return $result;
1129
-	}
1130
-
1131
-	/**
1132
-	 * Returns information from a single calendar object, based on it's object
1133
-	 * uri.
1134
-	 *
1135
-	 * The object uri is only the basename, or filename and not a full path.
1136
-	 *
1137
-	 * The returned array must have the same keys as getCalendarObjects. The
1138
-	 * 'calendardata' object is required here though, while it's not required
1139
-	 * for getCalendarObjects.
1140
-	 *
1141
-	 * This method must return null if the object did not exist.
1142
-	 *
1143
-	 * @param mixed $calendarId
1144
-	 * @param string $objectUri
1145
-	 * @param int $calendarType
1146
-	 * @return array|null
1147
-	 */
1148
-	public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1149
-		$query = $this->db->getQueryBuilder();
1150
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1151
-			->from('calendarobjects')
1152
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1153
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1154
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1155
-		$stmt = $query->executeQuery();
1156
-		$row = $stmt->fetch();
1157
-		$stmt->closeCursor();
1158
-
1159
-		if (!$row) {
1160
-			return null;
1161
-		}
1162
-
1163
-		return [
1164
-			'id' => $row['id'],
1165
-			'uri' => $row['uri'],
1166
-			'lastmodified' => $row['lastmodified'],
1167
-			'etag' => '"' . $row['etag'] . '"',
1168
-			'calendarid' => $row['calendarid'],
1169
-			'size' => (int)$row['size'],
1170
-			'calendardata' => $this->readBlob($row['calendardata']),
1171
-			'component' => strtolower($row['componenttype']),
1172
-			'classification' => (int)$row['classification']
1173
-		];
1174
-	}
1175
-
1176
-	/**
1177
-	 * Returns a list of calendar objects.
1178
-	 *
1179
-	 * This method should work identical to getCalendarObject, but instead
1180
-	 * return all the calendar objects in the list as an array.
1181
-	 *
1182
-	 * If the backend supports this, it may allow for some speed-ups.
1183
-	 *
1184
-	 * @param mixed $calendarId
1185
-	 * @param string[] $uris
1186
-	 * @param int $calendarType
1187
-	 * @return array
1188
-	 */
1189
-	public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1190
-		if (empty($uris)) {
1191
-			return [];
1192
-		}
1193
-
1194
-		$chunks = array_chunk($uris, 100);
1195
-		$objects = [];
1196
-
1197
-		$query = $this->db->getQueryBuilder();
1198
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1199
-			->from('calendarobjects')
1200
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1201
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1202
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1203
-			->andWhere($query->expr()->isNull('deleted_at'));
1204
-
1205
-		foreach ($chunks as $uris) {
1206
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1207
-			$result = $query->executeQuery();
1208
-
1209
-			while ($row = $result->fetch()) {
1210
-				$objects[] = [
1211
-					'id' => $row['id'],
1212
-					'uri' => $row['uri'],
1213
-					'lastmodified' => $row['lastmodified'],
1214
-					'etag' => '"' . $row['etag'] . '"',
1215
-					'calendarid' => $row['calendarid'],
1216
-					'size' => (int)$row['size'],
1217
-					'calendardata' => $this->readBlob($row['calendardata']),
1218
-					'component' => strtolower($row['componenttype']),
1219
-					'classification' => (int)$row['classification']
1220
-				];
1221
-			}
1222
-			$result->closeCursor();
1223
-		}
1224
-
1225
-		return $objects;
1226
-	}
1227
-
1228
-	/**
1229
-	 * Creates a new calendar object.
1230
-	 *
1231
-	 * The object uri is only the basename, or filename and not a full path.
1232
-	 *
1233
-	 * It is possible return an etag from this function, which will be used in
1234
-	 * the response to this PUT request. Note that the ETag must be surrounded
1235
-	 * by double-quotes.
1236
-	 *
1237
-	 * However, you should only really return this ETag if you don't mangle the
1238
-	 * calendar-data. If the result of a subsequent GET to this object is not
1239
-	 * the exact same as this request body, you should omit the ETag.
1240
-	 *
1241
-	 * @param mixed $calendarId
1242
-	 * @param string $objectUri
1243
-	 * @param string $calendarData
1244
-	 * @param int $calendarType
1245
-	 * @return string
1246
-	 */
1247
-	public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1248
-		$extraData = $this->getDenormalizedData($calendarData);
1249
-
1250
-		// Try to detect duplicates
1251
-		$qb = $this->db->getQueryBuilder();
1252
-		$qb->select($qb->func()->count('*'))
1253
-			->from('calendarobjects')
1254
-			->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1255
-			->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($extraData['uid'])))
1256
-			->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1257
-			->andWhere($qb->expr()->isNull('deleted_at'));
1258
-		$result = $qb->executeQuery();
1259
-		$count = (int) $result->fetchOne();
1260
-		$result->closeCursor();
1261
-
1262
-		if ($count !== 0) {
1263
-			throw new BadRequest('Calendar object with uid already exists in this calendar collection.');
1264
-		}
1265
-		// For a more specific error message we also try to explicitly look up the UID but as a deleted entry
1266
-		$qbDel = $this->db->getQueryBuilder();
1267
-		$qbDel->select($qb->func()->count('*'))
1268
-			->from('calendarobjects')
1269
-			->where($qbDel->expr()->eq('calendarid', $qbDel->createNamedParameter($calendarId)))
1270
-			->andWhere($qbDel->expr()->eq('uid', $qbDel->createNamedParameter($extraData['uid'])))
1271
-			->andWhere($qbDel->expr()->eq('calendartype', $qbDel->createNamedParameter($calendarType)))
1272
-			->andWhere($qbDel->expr()->isNotNull('deleted_at'));
1273
-		$result = $qbDel->executeQuery();
1274
-		$count = (int) $result->fetchOne();
1275
-		$result->closeCursor();
1276
-		if ($count !== 0) {
1277
-			throw new BadRequest('Deleted calendar object with uid already exists in this calendar collection.');
1278
-		}
1279
-
1280
-		$query = $this->db->getQueryBuilder();
1281
-		$query->insert('calendarobjects')
1282
-			->values([
1283
-				'calendarid' => $query->createNamedParameter($calendarId),
1284
-				'uri' => $query->createNamedParameter($objectUri),
1285
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1286
-				'lastmodified' => $query->createNamedParameter(time()),
1287
-				'etag' => $query->createNamedParameter($extraData['etag']),
1288
-				'size' => $query->createNamedParameter($extraData['size']),
1289
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
1290
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1291
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1292
-				'classification' => $query->createNamedParameter($extraData['classification']),
1293
-				'uid' => $query->createNamedParameter($extraData['uid']),
1294
-				'calendartype' => $query->createNamedParameter($calendarType),
1295
-			])
1296
-			->executeStatement();
1297
-
1298
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1299
-		$this->addChange($calendarId, $objectUri, 1, $calendarType);
1300
-
1301
-		$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1302
-		if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1303
-			$calendarRow = $this->getCalendarById($calendarId);
1304
-			$shares = $this->getShares($calendarId);
1305
-
1306
-			$this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent((int)$calendarId, $calendarRow, $shares, $objectRow));
1307
-		} else {
1308
-			$subscriptionRow = $this->getSubscriptionById($calendarId);
1309
-
1310
-			$this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow));
1311
-			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1312
-				'\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1313
-				[
1314
-					'subscriptionId' => $calendarId,
1315
-					'calendarData' => $subscriptionRow,
1316
-					'shares' => [],
1317
-					'objectData' => $objectRow,
1318
-				]
1319
-			));
1320
-		}
1321
-
1322
-		return '"' . $extraData['etag'] . '"';
1323
-	}
1324
-
1325
-	/**
1326
-	 * Updates an existing calendarobject, based on it's uri.
1327
-	 *
1328
-	 * The object uri is only the basename, or filename and not a full path.
1329
-	 *
1330
-	 * It is possible return an etag from this function, which will be used in
1331
-	 * the response to this PUT request. Note that the ETag must be surrounded
1332
-	 * by double-quotes.
1333
-	 *
1334
-	 * However, you should only really return this ETag if you don't mangle the
1335
-	 * calendar-data. If the result of a subsequent GET to this object is not
1336
-	 * the exact same as this request body, you should omit the ETag.
1337
-	 *
1338
-	 * @param mixed $calendarId
1339
-	 * @param string $objectUri
1340
-	 * @param string $calendarData
1341
-	 * @param int $calendarType
1342
-	 * @return string
1343
-	 */
1344
-	public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1345
-		$extraData = $this->getDenormalizedData($calendarData);
1346
-		$query = $this->db->getQueryBuilder();
1347
-		$query->update('calendarobjects')
1348
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1349
-				->set('lastmodified', $query->createNamedParameter(time()))
1350
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1351
-				->set('size', $query->createNamedParameter($extraData['size']))
1352
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1353
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1354
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1355
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1356
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1357
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1358
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1359
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1360
-			->executeStatement();
1361
-
1362
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1363
-		$this->addChange($calendarId, $objectUri, 2, $calendarType);
1364
-
1365
-		$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1366
-		if (is_array($objectRow)) {
1367
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1368
-				$calendarRow = $this->getCalendarById($calendarId);
1369
-				$shares = $this->getShares($calendarId);
1370
-
1371
-				$this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent((int)$calendarId, $calendarRow, $shares, $objectRow));
1372
-			} else {
1373
-				$subscriptionRow = $this->getSubscriptionById($calendarId);
1374
-
1375
-				$this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow));
1376
-				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1377
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1378
-					[
1379
-						'subscriptionId' => $calendarId,
1380
-						'calendarData' => $subscriptionRow,
1381
-						'shares' => [],
1382
-						'objectData' => $objectRow,
1383
-					]
1384
-				));
1385
-			}
1386
-		}
1387
-
1388
-		return '"' . $extraData['etag'] . '"';
1389
-	}
1390
-
1391
-	/**
1392
-	 * @param int $calendarObjectId
1393
-	 * @param int $classification
1394
-	 */
1395
-	public function setClassification($calendarObjectId, $classification) {
1396
-		if (!in_array($classification, [
1397
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1398
-		])) {
1399
-			throw new \InvalidArgumentException();
1400
-		}
1401
-		$query = $this->db->getQueryBuilder();
1402
-		$query->update('calendarobjects')
1403
-			->set('classification', $query->createNamedParameter($classification))
1404
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1405
-			->executeStatement();
1406
-	}
1407
-
1408
-	/**
1409
-	 * Deletes an existing calendar object.
1410
-	 *
1411
-	 * The object uri is only the basename, or filename and not a full path.
1412
-	 *
1413
-	 * @param mixed $calendarId
1414
-	 * @param string $objectUri
1415
-	 * @param int $calendarType
1416
-	 * @param bool $forceDeletePermanently
1417
-	 * @return void
1418
-	 */
1419
-	public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
1420
-		$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1421
-
1422
-		if ($data === null) {
1423
-			// Nothing to delete
1424
-			return;
1425
-		}
1426
-
1427
-		if ($forceDeletePermanently || $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0') {
1428
-			$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1429
-			$stmt->execute([$calendarId, $objectUri, $calendarType]);
1430
-
1431
-			$this->purgeProperties($calendarId, $data['id']);
1432
-
1433
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1434
-				$calendarRow = $this->getCalendarById($calendarId);
1435
-				$shares = $this->getShares($calendarId);
1436
-
1437
-				$this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent((int)$calendarId, $calendarRow, $shares, $data));
1438
-			} else {
1439
-				$subscriptionRow = $this->getSubscriptionById($calendarId);
1440
-
1441
-				$this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent((int)$calendarId, $subscriptionRow, [], $data));
1442
-				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1443
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1444
-					[
1445
-						'subscriptionId' => $calendarId,
1446
-						'calendarData' => $subscriptionRow,
1447
-						'shares' => [],
1448
-						'objectData' => $data,
1449
-					]
1450
-				));
1451
-			}
1452
-		} else {
1453
-			$pathInfo = pathinfo($data['uri']);
1454
-			if (!empty($pathInfo['extension'])) {
1455
-				// Append a suffix to "free" the old URI for recreation
1456
-				$newUri = sprintf(
1457
-					"%s-deleted.%s",
1458
-					$pathInfo['filename'],
1459
-					$pathInfo['extension']
1460
-				);
1461
-			} else {
1462
-				$newUri = sprintf(
1463
-					"%s-deleted",
1464
-					$pathInfo['filename']
1465
-				);
1466
-			}
1467
-
1468
-			// Try to detect conflicts before the DB does
1469
-			// As unlikely as it seems, this can happen when the user imports, then deletes, imports and deletes again
1470
-			$newObject = $this->getCalendarObject($calendarId, $newUri, $calendarType);
1471
-			if ($newObject !== null) {
1472
-				throw new Forbidden("A calendar object with URI $newUri already exists in calendar $calendarId, therefore this object can't be moved into the trashbin");
1473
-			}
1474
-
1475
-			$qb = $this->db->getQueryBuilder();
1476
-			$markObjectDeletedQuery = $qb->update('calendarobjects')
1477
-				->set('deleted_at', $qb->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
1478
-				->set('uri', $qb->createNamedParameter($newUri))
1479
-				->where(
1480
-					$qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
1481
-					$qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
1482
-					$qb->expr()->eq('uri', $qb->createNamedParameter($objectUri))
1483
-				);
1484
-			$markObjectDeletedQuery->executeStatement();
1485
-
1486
-			$calendarData = $this->getCalendarById($calendarId);
1487
-			if ($calendarData !== null) {
1488
-				$this->dispatcher->dispatchTyped(
1489
-					new CalendarObjectMovedToTrashEvent(
1490
-						(int)$calendarId,
1491
-						$calendarData,
1492
-						$this->getShares($calendarId),
1493
-						$data
1494
-					)
1495
-				);
1496
-			}
1497
-		}
1498
-
1499
-		$this->addChange($calendarId, $objectUri, 3, $calendarType);
1500
-	}
1501
-
1502
-	/**
1503
-	 * @param mixed $objectData
1504
-	 *
1505
-	 * @throws Forbidden
1506
-	 */
1507
-	public function restoreCalendarObject(array $objectData): void {
1508
-		$id = (int) $objectData['id'];
1509
-		$restoreUri = str_replace("-deleted.ics", ".ics", $objectData['uri']);
1510
-		$targetObject = $this->getCalendarObject(
1511
-			$objectData['calendarid'],
1512
-			$restoreUri
1513
-		);
1514
-		if ($targetObject !== null) {
1515
-			throw new Forbidden("Can not restore calendar $id because a calendar object with the URI $restoreUri already exists");
1516
-		}
1517
-
1518
-		$qb = $this->db->getQueryBuilder();
1519
-		$update = $qb->update('calendarobjects')
1520
-			->set('uri', $qb->createNamedParameter($restoreUri))
1521
-			->set('deleted_at', $qb->createNamedParameter(null))
1522
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1523
-		$update->executeStatement();
1524
-
1525
-		// Make sure this change is tracked in the changes table
1526
-		$qb2 = $this->db->getQueryBuilder();
1527
-		$selectObject = $qb2->select('calendardata', 'uri', 'calendarid', 'calendartype')
1528
-			->selectAlias('componenttype', 'component')
1529
-			->from('calendarobjects')
1530
-			->where($qb2->expr()->eq('id', $qb2->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1531
-		$result = $selectObject->executeQuery();
1532
-		$row = $result->fetch();
1533
-		$result->closeCursor();
1534
-		if ($row === false) {
1535
-			// Welp, this should possibly not have happened, but let's ignore
1536
-			return;
1537
-		}
1538
-		$this->addChange($row['calendarid'], $row['uri'], 1, (int) $row['calendartype']);
1539
-
1540
-		$calendarRow = $this->getCalendarById((int) $row['calendarid']);
1541
-		if ($calendarRow === null) {
1542
-			throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
1543
-		}
1544
-		$this->dispatcher->dispatchTyped(
1545
-			new CalendarObjectRestoredEvent(
1546
-				(int) $objectData['calendarid'],
1547
-				$calendarRow,
1548
-				$this->getShares((int) $row['calendarid']),
1549
-				$row
1550
-			)
1551
-		);
1552
-	}
1553
-
1554
-	/**
1555
-	 * Performs a calendar-query on the contents of this calendar.
1556
-	 *
1557
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1558
-	 * calendar-query it is possible for a client to request a specific set of
1559
-	 * object, based on contents of iCalendar properties, date-ranges and
1560
-	 * iCalendar component types (VTODO, VEVENT).
1561
-	 *
1562
-	 * This method should just return a list of (relative) urls that match this
1563
-	 * query.
1564
-	 *
1565
-	 * The list of filters are specified as an array. The exact array is
1566
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1567
-	 *
1568
-	 * Note that it is extremely likely that getCalendarObject for every path
1569
-	 * returned from this method will be called almost immediately after. You
1570
-	 * may want to anticipate this to speed up these requests.
1571
-	 *
1572
-	 * This method provides a default implementation, which parses *all* the
1573
-	 * iCalendar objects in the specified calendar.
1574
-	 *
1575
-	 * This default may well be good enough for personal use, and calendars
1576
-	 * that aren't very large. But if you anticipate high usage, big calendars
1577
-	 * or high loads, you are strongly advised to optimize certain paths.
1578
-	 *
1579
-	 * The best way to do so is override this method and to optimize
1580
-	 * specifically for 'common filters'.
1581
-	 *
1582
-	 * Requests that are extremely common are:
1583
-	 *   * requests for just VEVENTS
1584
-	 *   * requests for just VTODO
1585
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1586
-	 *
1587
-	 * ..and combinations of these requests. It may not be worth it to try to
1588
-	 * handle every possible situation and just rely on the (relatively
1589
-	 * easy to use) CalendarQueryValidator to handle the rest.
1590
-	 *
1591
-	 * Note that especially time-range-filters may be difficult to parse. A
1592
-	 * time-range filter specified on a VEVENT must for instance also handle
1593
-	 * recurrence rules correctly.
1594
-	 * A good example of how to interprete all these filters can also simply
1595
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1596
-	 * as possible, so it gives you a good idea on what type of stuff you need
1597
-	 * to think of.
1598
-	 *
1599
-	 * @param mixed $calendarId
1600
-	 * @param array $filters
1601
-	 * @param int $calendarType
1602
-	 * @return array
1603
-	 */
1604
-	public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1605
-		$componentType = null;
1606
-		$requirePostFilter = true;
1607
-		$timeRange = null;
1608
-
1609
-		// if no filters were specified, we don't need to filter after a query
1610
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1611
-			$requirePostFilter = false;
1612
-		}
1613
-
1614
-		// Figuring out if there's a component filter
1615
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1616
-			$componentType = $filters['comp-filters'][0]['name'];
1617
-
1618
-			// Checking if we need post-filters
1619
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1620
-				$requirePostFilter = false;
1621
-			}
1622
-			// There was a time-range filter
1623
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
1624
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1625
-
1626
-				// If start time OR the end time is not specified, we can do a
1627
-				// 100% accurate mysql query.
1628
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1629
-					$requirePostFilter = false;
1630
-				}
1631
-			}
1632
-		}
1633
-		$columns = ['uri'];
1634
-		if ($requirePostFilter) {
1635
-			$columns = ['uri', 'calendardata'];
1636
-		}
1637
-		$query = $this->db->getQueryBuilder();
1638
-		$query->select($columns)
1639
-			->from('calendarobjects')
1640
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1641
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1642
-			->andWhere($query->expr()->isNull('deleted_at'));
1643
-
1644
-		if ($componentType) {
1645
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1646
-		}
1647
-
1648
-		if ($timeRange && $timeRange['start']) {
1649
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1650
-		}
1651
-		if ($timeRange && $timeRange['end']) {
1652
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1653
-		}
1654
-
1655
-		$stmt = $query->executeQuery();
1656
-
1657
-		$result = [];
1658
-		while ($row = $stmt->fetch()) {
1659
-			if ($requirePostFilter) {
1660
-				// validateFilterForObject will parse the calendar data
1661
-				// catch parsing errors
1662
-				try {
1663
-					$matches = $this->validateFilterForObject($row, $filters);
1664
-				} catch (ParseException $ex) {
1665
-					$this->logger->logException($ex, [
1666
-						'app' => 'dav',
1667
-						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1668
-					]);
1669
-					continue;
1670
-				} catch (InvalidDataException $ex) {
1671
-					$this->logger->logException($ex, [
1672
-						'app' => 'dav',
1673
-						'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1674
-					]);
1675
-					continue;
1676
-				}
1677
-
1678
-				if (!$matches) {
1679
-					continue;
1680
-				}
1681
-			}
1682
-			$result[] = $row['uri'];
1683
-		}
1684
-
1685
-		return $result;
1686
-	}
1687
-
1688
-	/**
1689
-	 * custom Nextcloud search extension for CalDAV
1690
-	 *
1691
-	 * TODO - this should optionally cover cached calendar objects as well
1692
-	 *
1693
-	 * @param string $principalUri
1694
-	 * @param array $filters
1695
-	 * @param integer|null $limit
1696
-	 * @param integer|null $offset
1697
-	 * @return array
1698
-	 */
1699
-	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1700
-		$calendars = $this->getCalendarsForUser($principalUri);
1701
-		$ownCalendars = [];
1702
-		$sharedCalendars = [];
1703
-
1704
-		$uriMapper = [];
1705
-
1706
-		foreach ($calendars as $calendar) {
1707
-			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1708
-				$ownCalendars[] = $calendar['id'];
1709
-			} else {
1710
-				$sharedCalendars[] = $calendar['id'];
1711
-			}
1712
-			$uriMapper[$calendar['id']] = $calendar['uri'];
1713
-		}
1714
-		if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1715
-			return [];
1716
-		}
1717
-
1718
-		$query = $this->db->getQueryBuilder();
1719
-		// Calendar id expressions
1720
-		$calendarExpressions = [];
1721
-		foreach ($ownCalendars as $id) {
1722
-			$calendarExpressions[] = $query->expr()->andX(
1723
-				$query->expr()->eq('c.calendarid',
1724
-					$query->createNamedParameter($id)),
1725
-				$query->expr()->eq('c.calendartype',
1726
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1727
-		}
1728
-		foreach ($sharedCalendars as $id) {
1729
-			$calendarExpressions[] = $query->expr()->andX(
1730
-				$query->expr()->eq('c.calendarid',
1731
-					$query->createNamedParameter($id)),
1732
-				$query->expr()->eq('c.classification',
1733
-					$query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1734
-				$query->expr()->eq('c.calendartype',
1735
-					$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1736
-		}
1737
-
1738
-		if (count($calendarExpressions) === 1) {
1739
-			$calExpr = $calendarExpressions[0];
1740
-		} else {
1741
-			$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1742
-		}
1743
-
1744
-		// Component expressions
1745
-		$compExpressions = [];
1746
-		foreach ($filters['comps'] as $comp) {
1747
-			$compExpressions[] = $query->expr()
1748
-				->eq('c.componenttype', $query->createNamedParameter($comp));
1749
-		}
1750
-
1751
-		if (count($compExpressions) === 1) {
1752
-			$compExpr = $compExpressions[0];
1753
-		} else {
1754
-			$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1755
-		}
1756
-
1757
-		if (!isset($filters['props'])) {
1758
-			$filters['props'] = [];
1759
-		}
1760
-		if (!isset($filters['params'])) {
1761
-			$filters['params'] = [];
1762
-		}
1763
-
1764
-		$propParamExpressions = [];
1765
-		foreach ($filters['props'] as $prop) {
1766
-			$propParamExpressions[] = $query->expr()->andX(
1767
-				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1768
-				$query->expr()->isNull('i.parameter')
1769
-			);
1770
-		}
1771
-		foreach ($filters['params'] as $param) {
1772
-			$propParamExpressions[] = $query->expr()->andX(
1773
-				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1774
-				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1775
-			);
1776
-		}
1777
-
1778
-		if (count($propParamExpressions) === 1) {
1779
-			$propParamExpr = $propParamExpressions[0];
1780
-		} else {
1781
-			$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1782
-		}
1783
-
1784
-		$query->select(['c.calendarid', 'c.uri'])
1785
-			->from($this->dbObjectPropertiesTable, 'i')
1786
-			->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1787
-			->where($calExpr)
1788
-			->andWhere($compExpr)
1789
-			->andWhere($propParamExpr)
1790
-			->andWhere($query->expr()->iLike('i.value',
1791
-				$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')))
1792
-			->andWhere($query->expr()->isNull('deleted_at'));
1793
-
1794
-		if ($offset) {
1795
-			$query->setFirstResult($offset);
1796
-		}
1797
-		if ($limit) {
1798
-			$query->setMaxResults($limit);
1799
-		}
1800
-
1801
-		$stmt = $query->executeQuery();
1802
-
1803
-		$result = [];
1804
-		while ($row = $stmt->fetch()) {
1805
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1806
-			if (!in_array($path, $result)) {
1807
-				$result[] = $path;
1808
-			}
1809
-		}
1810
-
1811
-		return $result;
1812
-	}
1813
-
1814
-	/**
1815
-	 * used for Nextcloud's calendar API
1816
-	 *
1817
-	 * @param array $calendarInfo
1818
-	 * @param string $pattern
1819
-	 * @param array $searchProperties
1820
-	 * @param array $options
1821
-	 * @param integer|null $limit
1822
-	 * @param integer|null $offset
1823
-	 *
1824
-	 * @return array
1825
-	 */
1826
-	public function search(array $calendarInfo, $pattern, array $searchProperties,
1827
-						   array $options, $limit, $offset) {
1828
-		$outerQuery = $this->db->getQueryBuilder();
1829
-		$innerQuery = $this->db->getQueryBuilder();
1830
-
1831
-		$innerQuery->selectDistinct('op.objectid')
1832
-			->from($this->dbObjectPropertiesTable, 'op')
1833
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
1834
-				$outerQuery->createNamedParameter($calendarInfo['id'])))
1835
-			->andWhere($innerQuery->expr()->eq('op.calendartype',
1836
-				$outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1837
-
1838
-		// only return public items for shared calendars for now
1839
-		if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1840
-			$innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1841
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1842
-		}
1843
-
1844
-		$or = $innerQuery->expr()->orX();
1845
-		foreach ($searchProperties as $searchProperty) {
1846
-			$or->add($innerQuery->expr()->eq('op.name',
1847
-				$outerQuery->createNamedParameter($searchProperty)));
1848
-		}
1849
-		$innerQuery->andWhere($or);
1850
-
1851
-		if ($pattern !== '') {
1852
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1853
-				$outerQuery->createNamedParameter('%' .
1854
-					$this->db->escapeLikeParameter($pattern) . '%')));
1855
-		}
1856
-
1857
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1858
-			->from('calendarobjects', 'c')
1859
-			->where($outerQuery->expr()->isNull('deleted_at'));
1860
-
1861
-		if (isset($options['timerange'])) {
1862
-			if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTime) {
1863
-				$outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1864
-					$outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp())));
1865
-			}
1866
-			if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTime) {
1867
-				$outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1868
-					$outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp())));
1869
-			}
1870
-		}
1871
-
1872
-		if (isset($options['types'])) {
1873
-			$or = $outerQuery->expr()->orX();
1874
-			foreach ($options['types'] as $type) {
1875
-				$or->add($outerQuery->expr()->eq('componenttype',
1876
-					$outerQuery->createNamedParameter($type)));
1877
-			}
1878
-			$outerQuery->andWhere($or);
1879
-		}
1880
-
1881
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id',
1882
-			$outerQuery->createFunction($innerQuery->getSQL())));
1883
-
1884
-		if ($offset) {
1885
-			$outerQuery->setFirstResult($offset);
1886
-		}
1887
-		if ($limit) {
1888
-			$outerQuery->setMaxResults($limit);
1889
-		}
1890
-
1891
-		$result = $outerQuery->executeQuery();
1892
-		$calendarObjects = $result->fetchAll();
1893
-
1894
-		return array_map(function ($o) {
1895
-			$calendarData = Reader::read($o['calendardata']);
1896
-			$comps = $calendarData->getComponents();
1897
-			$objects = [];
1898
-			$timezones = [];
1899
-			foreach ($comps as $comp) {
1900
-				if ($comp instanceof VTimeZone) {
1901
-					$timezones[] = $comp;
1902
-				} else {
1903
-					$objects[] = $comp;
1904
-				}
1905
-			}
1906
-
1907
-			return [
1908
-				'id' => $o['id'],
1909
-				'type' => $o['componenttype'],
1910
-				'uid' => $o['uid'],
1911
-				'uri' => $o['uri'],
1912
-				'objects' => array_map(function ($c) {
1913
-					return $this->transformSearchData($c);
1914
-				}, $objects),
1915
-				'timezones' => array_map(function ($c) {
1916
-					return $this->transformSearchData($c);
1917
-				}, $timezones),
1918
-			];
1919
-		}, $calendarObjects);
1920
-	}
1921
-
1922
-	/**
1923
-	 * @param Component $comp
1924
-	 * @return array
1925
-	 */
1926
-	private function transformSearchData(Component $comp) {
1927
-		$data = [];
1928
-		/** @var Component[] $subComponents */
1929
-		$subComponents = $comp->getComponents();
1930
-		/** @var Property[] $properties */
1931
-		$properties = array_filter($comp->children(), function ($c) {
1932
-			return $c instanceof Property;
1933
-		});
1934
-		$validationRules = $comp->getValidationRules();
1935
-
1936
-		foreach ($subComponents as $subComponent) {
1937
-			$name = $subComponent->name;
1938
-			if (!isset($data[$name])) {
1939
-				$data[$name] = [];
1940
-			}
1941
-			$data[$name][] = $this->transformSearchData($subComponent);
1942
-		}
1943
-
1944
-		foreach ($properties as $property) {
1945
-			$name = $property->name;
1946
-			if (!isset($validationRules[$name])) {
1947
-				$validationRules[$name] = '*';
1948
-			}
1949
-
1950
-			$rule = $validationRules[$property->name];
1951
-			if ($rule === '+' || $rule === '*') { // multiple
1952
-				if (!isset($data[$name])) {
1953
-					$data[$name] = [];
1954
-				}
1955
-
1956
-				$data[$name][] = $this->transformSearchProperty($property);
1957
-			} else { // once
1958
-				$data[$name] = $this->transformSearchProperty($property);
1959
-			}
1960
-		}
1961
-
1962
-		return $data;
1963
-	}
1964
-
1965
-	/**
1966
-	 * @param Property $prop
1967
-	 * @return array
1968
-	 */
1969
-	private function transformSearchProperty(Property $prop) {
1970
-		// No need to check Date, as it extends DateTime
1971
-		if ($prop instanceof Property\ICalendar\DateTime) {
1972
-			$value = $prop->getDateTime();
1973
-		} else {
1974
-			$value = $prop->getValue();
1975
-		}
1976
-
1977
-		return [
1978
-			$value,
1979
-			$prop->parameters()
1980
-		];
1981
-	}
1982
-
1983
-	/**
1984
-	 * @param string $principalUri
1985
-	 * @param string $pattern
1986
-	 * @param array $componentTypes
1987
-	 * @param array $searchProperties
1988
-	 * @param array $searchParameters
1989
-	 * @param array $options
1990
-	 * @return array
1991
-	 */
1992
-	public function searchPrincipalUri(string $principalUri,
1993
-									   string $pattern,
1994
-									   array $componentTypes,
1995
-									   array $searchProperties,
1996
-									   array $searchParameters,
1997
-									   array $options = []): array {
1998
-		$escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
1999
-
2000
-		$calendarObjectIdQuery = $this->db->getQueryBuilder();
2001
-		$calendarOr = $calendarObjectIdQuery->expr()->orX();
2002
-		$searchOr = $calendarObjectIdQuery->expr()->orX();
2003
-
2004
-		// Fetch calendars and subscription
2005
-		$calendars = $this->getCalendarsForUser($principalUri);
2006
-		$subscriptions = $this->getSubscriptionsForUser($principalUri);
2007
-		foreach ($calendars as $calendar) {
2008
-			$calendarAnd = $calendarObjectIdQuery->expr()->andX();
2009
-			$calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])));
2010
-			$calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
2011
-
2012
-			// If it's shared, limit search to public events
2013
-			if (isset($calendar['{http://owncloud.org/ns}owner-principal'])
2014
-				&& $calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
2015
-				$calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2016
-			}
2017
-
2018
-			$calendarOr->add($calendarAnd);
2019
-		}
2020
-		foreach ($subscriptions as $subscription) {
2021
-			$subscriptionAnd = $calendarObjectIdQuery->expr()->andX();
2022
-			$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])));
2023
-			$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2024
-
2025
-			// If it's shared, limit search to public events
2026
-			if (isset($subscription['{http://owncloud.org/ns}owner-principal'])
2027
-				&& $subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
2028
-				$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2029
-			}
2030
-
2031
-			$calendarOr->add($subscriptionAnd);
2032
-		}
2033
-
2034
-		foreach ($searchProperties as $property) {
2035
-			$propertyAnd = $calendarObjectIdQuery->expr()->andX();
2036
-			$propertyAnd->add($calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)));
2037
-			$propertyAnd->add($calendarObjectIdQuery->expr()->isNull('cob.parameter'));
2038
-
2039
-			$searchOr->add($propertyAnd);
2040
-		}
2041
-		foreach ($searchParameters as $property => $parameter) {
2042
-			$parameterAnd = $calendarObjectIdQuery->expr()->andX();
2043
-			$parameterAnd->add($calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)));
2044
-			$parameterAnd->add($calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)));
2045
-
2046
-			$searchOr->add($parameterAnd);
2047
-		}
2048
-
2049
-		if ($calendarOr->count() === 0) {
2050
-			return [];
2051
-		}
2052
-		if ($searchOr->count() === 0) {
2053
-			return [];
2054
-		}
2055
-
2056
-		$calendarObjectIdQuery->selectDistinct('cob.objectid')
2057
-			->from($this->dbObjectPropertiesTable, 'cob')
2058
-			->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
2059
-			->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
2060
-			->andWhere($calendarOr)
2061
-			->andWhere($searchOr)
2062
-			->andWhere($calendarObjectIdQuery->expr()->isNull('deleted_at'));
2063
-
2064
-		if ('' !== $pattern) {
2065
-			if (!$escapePattern) {
2066
-				$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
2067
-			} else {
2068
-				$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
2069
-			}
2070
-		}
2071
-
2072
-		if (isset($options['limit'])) {
2073
-			$calendarObjectIdQuery->setMaxResults($options['limit']);
2074
-		}
2075
-		if (isset($options['offset'])) {
2076
-			$calendarObjectIdQuery->setFirstResult($options['offset']);
2077
-		}
2078
-
2079
-		$result = $calendarObjectIdQuery->executeQuery();
2080
-		$matches = $result->fetchAll();
2081
-		$result->closeCursor();
2082
-		$matches = array_map(static function (array $match):int {
2083
-			return (int) $match['objectid'];
2084
-		}, $matches);
2085
-
2086
-		$query = $this->db->getQueryBuilder();
2087
-		$query->select('calendardata', 'uri', 'calendarid', 'calendartype')
2088
-			->from('calendarobjects')
2089
-			->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
2090
-
2091
-		$result = $query->executeQuery();
2092
-		$calendarObjects = $result->fetchAll();
2093
-		$result->closeCursor();
2094
-
2095
-		return array_map(function (array $array): array {
2096
-			$array['calendarid'] = (int)$array['calendarid'];
2097
-			$array['calendartype'] = (int)$array['calendartype'];
2098
-			$array['calendardata'] = $this->readBlob($array['calendardata']);
2099
-
2100
-			return $array;
2101
-		}, $calendarObjects);
2102
-	}
2103
-
2104
-	/**
2105
-	 * Searches through all of a users calendars and calendar objects to find
2106
-	 * an object with a specific UID.
2107
-	 *
2108
-	 * This method should return the path to this object, relative to the
2109
-	 * calendar home, so this path usually only contains two parts:
2110
-	 *
2111
-	 * calendarpath/objectpath.ics
2112
-	 *
2113
-	 * If the uid is not found, return null.
2114
-	 *
2115
-	 * This method should only consider * objects that the principal owns, so
2116
-	 * any calendars owned by other principals that also appear in this
2117
-	 * collection should be ignored.
2118
-	 *
2119
-	 * @param string $principalUri
2120
-	 * @param string $uid
2121
-	 * @return string|null
2122
-	 */
2123
-	public function getCalendarObjectByUID($principalUri, $uid) {
2124
-		$query = $this->db->getQueryBuilder();
2125
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
2126
-			->from('calendarobjects', 'co')
2127
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
2128
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2129
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
2130
-			->andWhere($query->expr()->isNull('co.deleted_at'));
2131
-		$stmt = $query->executeQuery();
2132
-		$row = $stmt->fetch();
2133
-		$stmt->closeCursor();
2134
-		if ($row) {
2135
-			return $row['calendaruri'] . '/' . $row['objecturi'];
2136
-		}
2137
-
2138
-		return null;
2139
-	}
2140
-
2141
-	public function getCalendarObjectById(string $principalUri, int $id): ?array {
2142
-		$query = $this->db->getQueryBuilder();
2143
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.calendardata', 'co.componenttype', 'co.classification', 'co.deleted_at'])
2144
-			->selectAlias('c.uri', 'calendaruri')
2145
-			->from('calendarobjects', 'co')
2146
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
2147
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2148
-			->andWhere($query->expr()->eq('co.id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
2149
-		$stmt = $query->executeQuery();
2150
-		$row = $stmt->fetch();
2151
-		$stmt->closeCursor();
2152
-
2153
-		if (!$row) {
2154
-			return null;
2155
-		}
2156
-
2157
-		return [
2158
-			'id' => $row['id'],
2159
-			'uri' => $row['uri'],
2160
-			'lastmodified' => $row['lastmodified'],
2161
-			'etag' => '"' . $row['etag'] . '"',
2162
-			'calendarid' => $row['calendarid'],
2163
-			'calendaruri' => $row['calendaruri'],
2164
-			'size' => (int)$row['size'],
2165
-			'calendardata' => $this->readBlob($row['calendardata']),
2166
-			'component' => strtolower($row['componenttype']),
2167
-			'classification' => (int)$row['classification'],
2168
-			'deleted_at' => isset($row['deleted_at']) ? ((int) $row['deleted_at']) : null,
2169
-		];
2170
-	}
2171
-
2172
-	/**
2173
-	 * The getChanges method returns all the changes that have happened, since
2174
-	 * the specified syncToken in the specified calendar.
2175
-	 *
2176
-	 * This function should return an array, such as the following:
2177
-	 *
2178
-	 * [
2179
-	 *   'syncToken' => 'The current synctoken',
2180
-	 *   'added'   => [
2181
-	 *      'new.txt',
2182
-	 *   ],
2183
-	 *   'modified'   => [
2184
-	 *      'modified.txt',
2185
-	 *   ],
2186
-	 *   'deleted' => [
2187
-	 *      'foo.php.bak',
2188
-	 *      'old.txt'
2189
-	 *   ]
2190
-	 * );
2191
-	 *
2192
-	 * The returned syncToken property should reflect the *current* syncToken
2193
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
2194
-	 * property This is * needed here too, to ensure the operation is atomic.
2195
-	 *
2196
-	 * If the $syncToken argument is specified as null, this is an initial
2197
-	 * sync, and all members should be reported.
2198
-	 *
2199
-	 * The modified property is an array of nodenames that have changed since
2200
-	 * the last token.
2201
-	 *
2202
-	 * The deleted property is an array with nodenames, that have been deleted
2203
-	 * from collection.
2204
-	 *
2205
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
2206
-	 * 1, you only have to report changes that happened only directly in
2207
-	 * immediate descendants. If it's 2, it should also include changes from
2208
-	 * the nodes below the child collections. (grandchildren)
2209
-	 *
2210
-	 * The $limit argument allows a client to specify how many results should
2211
-	 * be returned at most. If the limit is not specified, it should be treated
2212
-	 * as infinite.
2213
-	 *
2214
-	 * If the limit (infinite or not) is higher than you're willing to return,
2215
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
2216
-	 *
2217
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
2218
-	 * return null.
2219
-	 *
2220
-	 * The limit is 'suggestive'. You are free to ignore it.
2221
-	 *
2222
-	 * @param string $calendarId
2223
-	 * @param string $syncToken
2224
-	 * @param int $syncLevel
2225
-	 * @param int|null $limit
2226
-	 * @param int $calendarType
2227
-	 * @return array
2228
-	 */
2229
-	public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2230
-		// Current synctoken
2231
-		$qb = $this->db->getQueryBuilder();
2232
-		$qb->select('synctoken')
2233
-			->from('calendars')
2234
-			->where(
2235
-				$qb->expr()->eq('id', $qb->createNamedParameter($calendarId))
2236
-			);
2237
-		$stmt = $qb->executeQuery();
2238
-		$currentToken = $stmt->fetchOne();
2239
-
2240
-		if ($currentToken === false) {
2241
-			return null;
2242
-		}
2243
-
2244
-		$result = [
2245
-			'syncToken' => $currentToken,
2246
-			'added' => [],
2247
-			'modified' => [],
2248
-			'deleted' => [],
2249
-		];
2250
-
2251
-		if ($syncToken) {
2252
-			$qb = $this->db->getQueryBuilder();
2253
-
2254
-			$qb->select('uri', 'operation')
2255
-				->from('calendarchanges')
2256
-				->where(
2257
-					$qb->expr()->andX(
2258
-						$qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)),
2259
-						$qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)),
2260
-						$qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
2261
-						$qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType))
2262
-					)
2263
-				)->orderBy('synctoken');
2264
-			if (is_int($limit) && $limit > 0) {
2265
-				$qb->setMaxResults($limit);
2266
-			}
2267
-
2268
-			// Fetching all changes
2269
-			$stmt = $qb->executeQuery();
2270
-			$changes = [];
2271
-
2272
-			// This loop ensures that any duplicates are overwritten, only the
2273
-			// last change on a node is relevant.
2274
-			while ($row = $stmt->fetch()) {
2275
-				$changes[$row['uri']] = $row['operation'];
2276
-			}
2277
-			$stmt->closeCursor();
2278
-
2279
-			foreach ($changes as $uri => $operation) {
2280
-				switch ($operation) {
2281
-					case 1:
2282
-						$result['added'][] = $uri;
2283
-						break;
2284
-					case 2:
2285
-						$result['modified'][] = $uri;
2286
-						break;
2287
-					case 3:
2288
-						$result['deleted'][] = $uri;
2289
-						break;
2290
-				}
2291
-			}
2292
-		} else {
2293
-			// No synctoken supplied, this is the initial sync.
2294
-			$qb = $this->db->getQueryBuilder();
2295
-			$qb->select('uri')
2296
-				->from('calendarobjects')
2297
-				->where(
2298
-					$qb->expr()->andX(
2299
-						$qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
2300
-						$qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType))
2301
-					)
2302
-				);
2303
-			$stmt = $qb->executeQuery();
2304
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
2305
-			$stmt->closeCursor();
2306
-		}
2307
-		return $result;
2308
-	}
2309
-
2310
-	/**
2311
-	 * Returns a list of subscriptions for a principal.
2312
-	 *
2313
-	 * Every subscription is an array with the following keys:
2314
-	 *  * id, a unique id that will be used by other functions to modify the
2315
-	 *    subscription. This can be the same as the uri or a database key.
2316
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
2317
-	 *  * principaluri. The owner of the subscription. Almost always the same as
2318
-	 *    principalUri passed to this method.
2319
-	 *
2320
-	 * Furthermore, all the subscription info must be returned too:
2321
-	 *
2322
-	 * 1. {DAV:}displayname
2323
-	 * 2. {http://apple.com/ns/ical/}refreshrate
2324
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
2325
-	 *    should not be stripped).
2326
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
2327
-	 *    should not be stripped).
2328
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
2329
-	 *    attachments should not be stripped).
2330
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
2331
-	 *     Sabre\DAV\Property\Href).
2332
-	 * 7. {http://apple.com/ns/ical/}calendar-color
2333
-	 * 8. {http://apple.com/ns/ical/}calendar-order
2334
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
2335
-	 *    (should just be an instance of
2336
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
2337
-	 *    default components).
2338
-	 *
2339
-	 * @param string $principalUri
2340
-	 * @return array
2341
-	 */
2342
-	public function getSubscriptionsForUser($principalUri) {
2343
-		$fields = array_values($this->subscriptionPropertyMap);
2344
-		$fields[] = 'id';
2345
-		$fields[] = 'uri';
2346
-		$fields[] = 'source';
2347
-		$fields[] = 'principaluri';
2348
-		$fields[] = 'lastmodified';
2349
-		$fields[] = 'synctoken';
2350
-
2351
-		$query = $this->db->getQueryBuilder();
2352
-		$query->select($fields)
2353
-			->from('calendarsubscriptions')
2354
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2355
-			->orderBy('calendarorder', 'asc');
2356
-		$stmt = $query->executeQuery();
2357
-
2358
-		$subscriptions = [];
2359
-		while ($row = $stmt->fetch()) {
2360
-			$subscription = [
2361
-				'id' => $row['id'],
2362
-				'uri' => $row['uri'],
2363
-				'principaluri' => $row['principaluri'],
2364
-				'source' => $row['source'],
2365
-				'lastmodified' => $row['lastmodified'],
2366
-
2367
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2368
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
2369
-			];
2370
-
2371
-			foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
2372
-				if (!is_null($row[$dbName])) {
2373
-					$subscription[$xmlName] = $row[$dbName];
2374
-				}
2375
-			}
2376
-
2377
-			$subscriptions[] = $subscription;
2378
-		}
2379
-
2380
-		return $subscriptions;
2381
-	}
2382
-
2383
-	/**
2384
-	 * Creates a new subscription for a principal.
2385
-	 *
2386
-	 * If the creation was a success, an id must be returned that can be used to reference
2387
-	 * this subscription in other methods, such as updateSubscription.
2388
-	 *
2389
-	 * @param string $principalUri
2390
-	 * @param string $uri
2391
-	 * @param array $properties
2392
-	 * @return mixed
2393
-	 */
2394
-	public function createSubscription($principalUri, $uri, array $properties) {
2395
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2396
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2397
-		}
2398
-
2399
-		$values = [
2400
-			'principaluri' => $principalUri,
2401
-			'uri' => $uri,
2402
-			'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2403
-			'lastmodified' => time(),
2404
-		];
2405
-
2406
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2407
-
2408
-		foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
2409
-			if (array_key_exists($xmlName, $properties)) {
2410
-				$values[$dbName] = $properties[$xmlName];
2411
-				if (in_array($dbName, $propertiesBoolean)) {
2412
-					$values[$dbName] = true;
2413
-				}
2414
-			}
2415
-		}
2416
-
2417
-		$valuesToInsert = [];
2418
-
2419
-		$query = $this->db->getQueryBuilder();
2420
-
2421
-		foreach (array_keys($values) as $name) {
2422
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2423
-		}
2424
-
2425
-		$query->insert('calendarsubscriptions')
2426
-			->values($valuesToInsert)
2427
-			->executeStatement();
2428
-
2429
-		$subscriptionId = $query->getLastInsertId();
2430
-
2431
-		$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2432
-		$this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow));
2433
-		$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
2434
-			'\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
2435
-			[
2436
-				'subscriptionId' => $subscriptionId,
2437
-				'subscriptionData' => $subscriptionRow,
2438
-			]));
2439
-
2440
-		return $subscriptionId;
2441
-	}
2442
-
2443
-	/**
2444
-	 * Updates a subscription
2445
-	 *
2446
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2447
-	 * To do the actual updates, you must tell this object which properties
2448
-	 * you're going to process with the handle() method.
2449
-	 *
2450
-	 * Calling the handle method is like telling the PropPatch object "I
2451
-	 * promise I can handle updating this property".
2452
-	 *
2453
-	 * Read the PropPatch documentation for more info and examples.
2454
-	 *
2455
-	 * @param mixed $subscriptionId
2456
-	 * @param PropPatch $propPatch
2457
-	 * @return void
2458
-	 */
2459
-	public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2460
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
2461
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
2462
-
2463
-		$propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2464
-			$newValues = [];
2465
-
2466
-			foreach ($mutations as $propertyName => $propertyValue) {
2467
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
2468
-					$newValues['source'] = $propertyValue->getHref();
2469
-				} else {
2470
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
2471
-					$newValues[$fieldName] = $propertyValue;
2472
-				}
2473
-			}
2474
-
2475
-			$query = $this->db->getQueryBuilder();
2476
-			$query->update('calendarsubscriptions')
2477
-				->set('lastmodified', $query->createNamedParameter(time()));
2478
-			foreach ($newValues as $fieldName => $value) {
2479
-				$query->set($fieldName, $query->createNamedParameter($value));
2480
-			}
2481
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2482
-				->executeStatement();
2483
-
2484
-			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2485
-			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2486
-			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2487
-				'\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2488
-				[
2489
-					'subscriptionId' => $subscriptionId,
2490
-					'subscriptionData' => $subscriptionRow,
2491
-					'propertyMutations' => $mutations,
2492
-				]));
2493
-
2494
-			return true;
2495
-		});
2496
-	}
2497
-
2498
-	/**
2499
-	 * Deletes a subscription.
2500
-	 *
2501
-	 * @param mixed $subscriptionId
2502
-	 * @return void
2503
-	 */
2504
-	public function deleteSubscription($subscriptionId) {
2505
-		$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2506
-
2507
-		$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2508
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2509
-			[
2510
-				'subscriptionId' => $subscriptionId,
2511
-				'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2512
-			]));
2513
-
2514
-		$query = $this->db->getQueryBuilder();
2515
-		$query->delete('calendarsubscriptions')
2516
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2517
-			->executeStatement();
2518
-
2519
-		$query = $this->db->getQueryBuilder();
2520
-		$query->delete('calendarobjects')
2521
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2522
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2523
-			->executeStatement();
2524
-
2525
-		$query->delete('calendarchanges')
2526
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2527
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2528
-			->executeStatement();
2529
-
2530
-		$query->delete($this->dbObjectPropertiesTable)
2531
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2532
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2533
-			->executeStatement();
2534
-
2535
-		if ($subscriptionRow) {
2536
-			$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2537
-		}
2538
-	}
2539
-
2540
-	/**
2541
-	 * Returns a single scheduling object for the inbox collection.
2542
-	 *
2543
-	 * The returned array should contain the following elements:
2544
-	 *   * uri - A unique basename for the object. This will be used to
2545
-	 *           construct a full uri.
2546
-	 *   * calendardata - The iCalendar object
2547
-	 *   * lastmodified - The last modification date. Can be an int for a unix
2548
-	 *                    timestamp, or a PHP DateTime object.
2549
-	 *   * etag - A unique token that must change if the object changed.
2550
-	 *   * size - The size of the object, in bytes.
2551
-	 *
2552
-	 * @param string $principalUri
2553
-	 * @param string $objectUri
2554
-	 * @return array
2555
-	 */
2556
-	public function getSchedulingObject($principalUri, $objectUri) {
2557
-		$query = $this->db->getQueryBuilder();
2558
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2559
-			->from('schedulingobjects')
2560
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2561
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2562
-			->executeQuery();
2563
-
2564
-		$row = $stmt->fetch();
2565
-
2566
-		if (!$row) {
2567
-			return null;
2568
-		}
2569
-
2570
-		return [
2571
-			'uri' => $row['uri'],
2572
-			'calendardata' => $row['calendardata'],
2573
-			'lastmodified' => $row['lastmodified'],
2574
-			'etag' => '"' . $row['etag'] . '"',
2575
-			'size' => (int)$row['size'],
2576
-		];
2577
-	}
2578
-
2579
-	/**
2580
-	 * Returns all scheduling objects for the inbox collection.
2581
-	 *
2582
-	 * These objects should be returned as an array. Every item in the array
2583
-	 * should follow the same structure as returned from getSchedulingObject.
2584
-	 *
2585
-	 * The main difference is that 'calendardata' is optional.
2586
-	 *
2587
-	 * @param string $principalUri
2588
-	 * @return array
2589
-	 */
2590
-	public function getSchedulingObjects($principalUri) {
2591
-		$query = $this->db->getQueryBuilder();
2592
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2593
-				->from('schedulingobjects')
2594
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2595
-				->executeQuery();
2596
-
2597
-		$result = [];
2598
-		foreach ($stmt->fetchAll() as $row) {
2599
-			$result[] = [
2600
-				'calendardata' => $row['calendardata'],
2601
-				'uri' => $row['uri'],
2602
-				'lastmodified' => $row['lastmodified'],
2603
-				'etag' => '"' . $row['etag'] . '"',
2604
-				'size' => (int)$row['size'],
2605
-			];
2606
-		}
2607
-
2608
-		return $result;
2609
-	}
2610
-
2611
-	/**
2612
-	 * Deletes a scheduling object from the inbox collection.
2613
-	 *
2614
-	 * @param string $principalUri
2615
-	 * @param string $objectUri
2616
-	 * @return void
2617
-	 */
2618
-	public function deleteSchedulingObject($principalUri, $objectUri) {
2619
-		$query = $this->db->getQueryBuilder();
2620
-		$query->delete('schedulingobjects')
2621
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2622
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2623
-				->executeStatement();
2624
-	}
2625
-
2626
-	/**
2627
-	 * Creates a new scheduling object. This should land in a users' inbox.
2628
-	 *
2629
-	 * @param string $principalUri
2630
-	 * @param string $objectUri
2631
-	 * @param string $objectData
2632
-	 * @return void
2633
-	 */
2634
-	public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2635
-		$query = $this->db->getQueryBuilder();
2636
-		$query->insert('schedulingobjects')
2637
-			->values([
2638
-				'principaluri' => $query->createNamedParameter($principalUri),
2639
-				'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2640
-				'uri' => $query->createNamedParameter($objectUri),
2641
-				'lastmodified' => $query->createNamedParameter(time()),
2642
-				'etag' => $query->createNamedParameter(md5($objectData)),
2643
-				'size' => $query->createNamedParameter(strlen($objectData))
2644
-			])
2645
-			->executeStatement();
2646
-	}
2647
-
2648
-	/**
2649
-	 * Adds a change record to the calendarchanges table.
2650
-	 *
2651
-	 * @param mixed $calendarId
2652
-	 * @param string $objectUri
2653
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2654
-	 * @param int $calendarType
2655
-	 * @return void
2656
-	 */
2657
-	protected function addChange($calendarId, $objectUri, $operation, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2658
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2659
-
2660
-		$query = $this->db->getQueryBuilder();
2661
-		$query->select('synctoken')
2662
-			->from($table)
2663
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2664
-		$result = $query->executeQuery();
2665
-		$syncToken = (int)$result->fetchOne();
2666
-		$result->closeCursor();
2667
-
2668
-		$query = $this->db->getQueryBuilder();
2669
-		$query->insert('calendarchanges')
2670
-			->values([
2671
-				'uri' => $query->createNamedParameter($objectUri),
2672
-				'synctoken' => $query->createNamedParameter($syncToken),
2673
-				'calendarid' => $query->createNamedParameter($calendarId),
2674
-				'operation' => $query->createNamedParameter($operation),
2675
-				'calendartype' => $query->createNamedParameter($calendarType),
2676
-			])
2677
-			->executeStatement();
2678
-
2679
-		$stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2680
-		$stmt->execute([
2681
-			$calendarId
2682
-		]);
2683
-	}
2684
-
2685
-	/**
2686
-	 * Parses some information from calendar objects, used for optimized
2687
-	 * calendar-queries.
2688
-	 *
2689
-	 * Returns an array with the following keys:
2690
-	 *   * etag - An md5 checksum of the object without the quotes.
2691
-	 *   * size - Size of the object in bytes
2692
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
2693
-	 *   * firstOccurence
2694
-	 *   * lastOccurence
2695
-	 *   * uid - value of the UID property
2696
-	 *
2697
-	 * @param string $calendarData
2698
-	 * @return array
2699
-	 */
2700
-	public function getDenormalizedData($calendarData) {
2701
-		$vObject = Reader::read($calendarData);
2702
-		$vEvents = [];
2703
-		$componentType = null;
2704
-		$component = null;
2705
-		$firstOccurrence = null;
2706
-		$lastOccurrence = null;
2707
-		$uid = null;
2708
-		$classification = self::CLASSIFICATION_PUBLIC;
2709
-		$hasDTSTART = false;
2710
-		foreach ($vObject->getComponents() as $component) {
2711
-			if ($component->name !== 'VTIMEZONE') {
2712
-				// Finding all VEVENTs, and track them
2713
-				if ($component->name === 'VEVENT') {
2714
-					array_push($vEvents, $component);
2715
-					if ($component->DTSTART) {
2716
-						$hasDTSTART = true;
2717
-					}
2718
-				}
2719
-				// Track first component type and uid
2720
-				if ($uid === null) {
2721
-					$componentType = $component->name;
2722
-					$uid = (string)$component->UID;
2723
-				}
2724
-			}
2725
-		}
2726
-		if (!$componentType) {
2727
-			throw new BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2728
-		}
2729
-
2730
-		if ($hasDTSTART) {
2731
-			$component = $vEvents[0];
2732
-
2733
-			// Finding the last occurrence is a bit harder
2734
-			if (!isset($component->RRULE) && count($vEvents) === 1) {
2735
-				$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2736
-				if (isset($component->DTEND)) {
2737
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2738
-				} elseif (isset($component->DURATION)) {
2739
-					$endDate = clone $component->DTSTART->getDateTime();
2740
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2741
-					$lastOccurrence = $endDate->getTimeStamp();
2742
-				} elseif (!$component->DTSTART->hasTime()) {
2743
-					$endDate = clone $component->DTSTART->getDateTime();
2744
-					$endDate->modify('+1 day');
2745
-					$lastOccurrence = $endDate->getTimeStamp();
2746
-				} else {
2747
-					$lastOccurrence = $firstOccurrence;
2748
-				}
2749
-			} else {
2750
-				$it = new EventIterator($vEvents);
2751
-				$maxDate = new DateTime(self::MAX_DATE);
2752
-				$firstOccurrence = $it->getDtStart()->getTimestamp();
2753
-				if ($it->isInfinite()) {
2754
-					$lastOccurrence = $maxDate->getTimestamp();
2755
-				} else {
2756
-					$end = $it->getDtEnd();
2757
-					while ($it->valid() && $end < $maxDate) {
2758
-						$end = $it->getDtEnd();
2759
-						$it->next();
2760
-					}
2761
-					$lastOccurrence = $end->getTimestamp();
2762
-				}
2763
-			}
2764
-		}
2765
-
2766
-		if ($component->CLASS) {
2767
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2768
-			switch ($component->CLASS->getValue()) {
2769
-				case 'PUBLIC':
2770
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2771
-					break;
2772
-				case 'CONFIDENTIAL':
2773
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2774
-					break;
2775
-			}
2776
-		}
2777
-		return [
2778
-			'etag' => md5($calendarData),
2779
-			'size' => strlen($calendarData),
2780
-			'componentType' => $componentType,
2781
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2782
-			'lastOccurence' => $lastOccurrence,
2783
-			'uid' => $uid,
2784
-			'classification' => $classification
2785
-		];
2786
-	}
2787
-
2788
-	/**
2789
-	 * @param $cardData
2790
-	 * @return bool|string
2791
-	 */
2792
-	private function readBlob($cardData) {
2793
-		if (is_resource($cardData)) {
2794
-			return stream_get_contents($cardData);
2795
-		}
2796
-
2797
-		return $cardData;
2798
-	}
2799
-
2800
-	/**
2801
-	 * @param IShareable $shareable
2802
-	 * @param array $add
2803
-	 * @param array $remove
2804
-	 */
2805
-	public function updateShares($shareable, $add, $remove) {
2806
-		$calendarId = $shareable->getResourceId();
2807
-		$calendarRow = $this->getCalendarById($calendarId);
2808
-		$oldShares = $this->getShares($calendarId);
2809
-
2810
-		$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2811
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2812
-			[
2813
-				'calendarId' => $calendarId,
2814
-				'calendarData' => $calendarRow,
2815
-				'shares' => $oldShares,
2816
-				'add' => $add,
2817
-				'remove' => $remove,
2818
-			]));
2819
-		$this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2820
-
2821
-		$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent((int)$calendarId, $calendarRow, $oldShares, $add, $remove));
2822
-	}
2823
-
2824
-	/**
2825
-	 * @param int $resourceId
2826
-	 * @return array
2827
-	 */
2828
-	public function getShares($resourceId) {
2829
-		return $this->calendarSharingBackend->getShares($resourceId);
2830
-	}
2831
-
2832
-	/**
2833
-	 * @param boolean $value
2834
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2835
-	 * @return string|null
2836
-	 */
2837
-	public function setPublishStatus($value, $calendar) {
2838
-		$calendarId = $calendar->getResourceId();
2839
-		$calendarData = $this->getCalendarById($calendarId);
2840
-		$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2841
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2842
-			[
2843
-				'calendarId' => $calendarId,
2844
-				'calendarData' => $calendarData,
2845
-				'public' => $value,
2846
-			]));
2847
-
2848
-		$query = $this->db->getQueryBuilder();
2849
-		if ($value) {
2850
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2851
-			$query->insert('dav_shares')
2852
-				->values([
2853
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2854
-					'type' => $query->createNamedParameter('calendar'),
2855
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2856
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2857
-					'publicuri' => $query->createNamedParameter($publicUri)
2858
-				]);
2859
-			$query->executeStatement();
2860
-
2861
-			$this->dispatcher->dispatchTyped(new CalendarPublishedEvent((int)$calendarId, $calendarData, $publicUri));
2862
-			return $publicUri;
2863
-		}
2864
-		$query->delete('dav_shares')
2865
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2866
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2867
-		$query->executeStatement();
2868
-
2869
-		$this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent((int)$calendarId, $calendarData));
2870
-		return null;
2871
-	}
2872
-
2873
-	/**
2874
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2875
-	 * @return mixed
2876
-	 */
2877
-	public function getPublishStatus($calendar) {
2878
-		$query = $this->db->getQueryBuilder();
2879
-		$result = $query->select('publicuri')
2880
-			->from('dav_shares')
2881
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2882
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2883
-			->executeQuery();
2884
-
2885
-		$row = $result->fetch();
2886
-		$result->closeCursor();
2887
-		return $row ? reset($row) : false;
2888
-	}
2889
-
2890
-	/**
2891
-	 * @param int $resourceId
2892
-	 * @param array $acl
2893
-	 * @return array
2894
-	 */
2895
-	public function applyShareAcl($resourceId, $acl) {
2896
-		return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2897
-	}
2898
-
2899
-
2900
-
2901
-	/**
2902
-	 * update properties table
2903
-	 *
2904
-	 * @param int $calendarId
2905
-	 * @param string $objectUri
2906
-	 * @param string $calendarData
2907
-	 * @param int $calendarType
2908
-	 */
2909
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2910
-		$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2911
-
2912
-		try {
2913
-			$vCalendar = $this->readCalendarData($calendarData);
2914
-		} catch (\Exception $ex) {
2915
-			return;
2916
-		}
2917
-
2918
-		$this->purgeProperties($calendarId, $objectId);
2919
-
2920
-		$query = $this->db->getQueryBuilder();
2921
-		$query->insert($this->dbObjectPropertiesTable)
2922
-			->values(
2923
-				[
2924
-					'calendarid' => $query->createNamedParameter($calendarId),
2925
-					'calendartype' => $query->createNamedParameter($calendarType),
2926
-					'objectid' => $query->createNamedParameter($objectId),
2927
-					'name' => $query->createParameter('name'),
2928
-					'parameter' => $query->createParameter('parameter'),
2929
-					'value' => $query->createParameter('value'),
2930
-				]
2931
-			);
2932
-
2933
-		$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2934
-		foreach ($vCalendar->getComponents() as $component) {
2935
-			if (!in_array($component->name, $indexComponents)) {
2936
-				continue;
2937
-			}
2938
-
2939
-			foreach ($component->children() as $property) {
2940
-				if (in_array($property->name, self::$indexProperties)) {
2941
-					$value = $property->getValue();
2942
-					// is this a shitty db?
2943
-					if (!$this->db->supports4ByteText()) {
2944
-						$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2945
-					}
2946
-					$value = mb_strcut($value, 0, 254);
2947
-
2948
-					$query->setParameter('name', $property->name);
2949
-					$query->setParameter('parameter', null);
2950
-					$query->setParameter('value', $value);
2951
-					$query->executeStatement();
2952
-				}
2953
-
2954
-				if (array_key_exists($property->name, self::$indexParameters)) {
2955
-					$parameters = $property->parameters();
2956
-					$indexedParametersForProperty = self::$indexParameters[$property->name];
2957
-
2958
-					foreach ($parameters as $key => $value) {
2959
-						if (in_array($key, $indexedParametersForProperty)) {
2960
-							// is this a shitty db?
2961
-							if ($this->db->supports4ByteText()) {
2962
-								$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2963
-							}
2964
-
2965
-							$query->setParameter('name', $property->name);
2966
-							$query->setParameter('parameter', mb_strcut($key, 0, 254));
2967
-							$query->setParameter('value', mb_strcut($value, 0, 254));
2968
-							$query->executeStatement();
2969
-						}
2970
-					}
2971
-				}
2972
-			}
2973
-		}
2974
-	}
2975
-
2976
-	/**
2977
-	 * deletes all birthday calendars
2978
-	 */
2979
-	public function deleteAllBirthdayCalendars() {
2980
-		$query = $this->db->getQueryBuilder();
2981
-		$result = $query->select(['id'])->from('calendars')
2982
-			->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2983
-			->executeQuery();
2984
-
2985
-		$ids = $result->fetchAll();
2986
-		foreach ($ids as $id) {
2987
-			$this->deleteCalendar(
2988
-				$id['id'],
2989
-				true // No data to keep in the trashbin, if the user re-enables then we regenerate
2990
-			);
2991
-		}
2992
-	}
2993
-
2994
-	/**
2995
-	 * @param $subscriptionId
2996
-	 */
2997
-	public function purgeAllCachedEventsForSubscription($subscriptionId) {
2998
-		$query = $this->db->getQueryBuilder();
2999
-		$query->select('uri')
3000
-			->from('calendarobjects')
3001
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3002
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
3003
-		$stmt = $query->executeQuery();
3004
-
3005
-		$uris = [];
3006
-		foreach ($stmt->fetchAll() as $row) {
3007
-			$uris[] = $row['uri'];
3008
-		}
3009
-		$stmt->closeCursor();
3010
-
3011
-		$query = $this->db->getQueryBuilder();
3012
-		$query->delete('calendarobjects')
3013
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3014
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3015
-			->executeStatement();
3016
-
3017
-		$query->delete('calendarchanges')
3018
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3019
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3020
-			->executeStatement();
3021
-
3022
-		$query->delete($this->dbObjectPropertiesTable)
3023
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3024
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3025
-			->executeStatement();
3026
-
3027
-		foreach ($uris as $uri) {
3028
-			$this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3029
-		}
3030
-	}
3031
-
3032
-	/**
3033
-	 * Move a calendar from one user to another
3034
-	 *
3035
-	 * @param string $uriName
3036
-	 * @param string $uriOrigin
3037
-	 * @param string $uriDestination
3038
-	 * @param string $newUriName (optional) the new uriName
3039
-	 */
3040
-	public function moveCalendar($uriName, $uriOrigin, $uriDestination, $newUriName = null) {
3041
-		$query = $this->db->getQueryBuilder();
3042
-		$query->update('calendars')
3043
-			->set('principaluri', $query->createNamedParameter($uriDestination))
3044
-			->set('uri', $query->createNamedParameter($newUriName ?: $uriName))
3045
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
3046
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
3047
-			->executeStatement();
3048
-	}
3049
-
3050
-	/**
3051
-	 * read VCalendar data into a VCalendar object
3052
-	 *
3053
-	 * @param string $objectData
3054
-	 * @return VCalendar
3055
-	 */
3056
-	protected function readCalendarData($objectData) {
3057
-		return Reader::read($objectData);
3058
-	}
3059
-
3060
-	/**
3061
-	 * delete all properties from a given calendar object
3062
-	 *
3063
-	 * @param int $calendarId
3064
-	 * @param int $objectId
3065
-	 */
3066
-	protected function purgeProperties($calendarId, $objectId) {
3067
-		$query = $this->db->getQueryBuilder();
3068
-		$query->delete($this->dbObjectPropertiesTable)
3069
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
3070
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
3071
-		$query->executeStatement();
3072
-	}
3073
-
3074
-	/**
3075
-	 * get ID from a given calendar object
3076
-	 *
3077
-	 * @param int $calendarId
3078
-	 * @param string $uri
3079
-	 * @param int $calendarType
3080
-	 * @return int
3081
-	 */
3082
-	protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
3083
-		$query = $this->db->getQueryBuilder();
3084
-		$query->select('id')
3085
-			->from('calendarobjects')
3086
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
3087
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
3088
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
3089
-
3090
-		$result = $query->executeQuery();
3091
-		$objectIds = $result->fetch();
3092
-		$result->closeCursor();
3093
-
3094
-		if (!isset($objectIds['id'])) {
3095
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
3096
-		}
3097
-
3098
-		return (int)$objectIds['id'];
3099
-	}
3100
-
3101
-	/**
3102
-	 * return legacy endpoint principal name to new principal name
3103
-	 *
3104
-	 * @param $principalUri
3105
-	 * @param $toV2
3106
-	 * @return string
3107
-	 */
3108
-	private function convertPrincipal($principalUri, $toV2) {
3109
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
3110
-			[, $name] = Uri\split($principalUri);
3111
-			if ($toV2 === true) {
3112
-				return "principals/users/$name";
3113
-			}
3114
-			return "principals/$name";
3115
-		}
3116
-		return $principalUri;
3117
-	}
3118
-
3119
-	/**
3120
-	 * adds information about an owner to the calendar data
3121
-	 *
3122
-	 */
3123
-	private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
3124
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
3125
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
3126
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
3127
-			$uri = $calendarInfo[$ownerPrincipalKey];
3128
-		} else {
3129
-			$uri = $calendarInfo['principaluri'];
3130
-		}
3131
-
3132
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
3133
-		if (isset($principalInformation['{DAV:}displayname'])) {
3134
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
3135
-		}
3136
-		return $calendarInfo;
3137
-	}
3138
-
3139
-	private function addResourceTypeToCalendar(array $row, array $calendar): array {
3140
-		if (isset($row['deleted_at'])) {
3141
-			// Columns is set and not null -> this is a deleted calendar
3142
-			// we send a custom resourcetype to hide the deleted calendar
3143
-			// from ordinary DAV clients, but the Calendar app will know
3144
-			// how to handle this special resource.
3145
-			$calendar['{DAV:}resourcetype'] = new DAV\Xml\Property\ResourceType([
3146
-				'{DAV:}collection',
3147
-				sprintf('{%s}deleted-calendar', \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD),
3148
-			]);
3149
-		}
3150
-		return $calendar;
3151
-	}
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
+    public function getDeletedCalendarObjectsByPrincipal(string $principalUri): array {
1102
+        $query = $this->db->getQueryBuilder();
1103
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1104
+            ->selectAlias('c.uri', 'calendaruri')
1105
+            ->from('calendarobjects', 'co')
1106
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1107
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1108
+            ->andWhere($query->expr()->isNotNull('co.deleted_at'));
1109
+        $stmt = $query->executeQuery();
1110
+
1111
+        $result = [];
1112
+        while ($row = $stmt->fetch()) {
1113
+            $result[] = [
1114
+                'id' => $row['id'],
1115
+                'uri' => $row['uri'],
1116
+                'lastmodified' => $row['lastmodified'],
1117
+                'etag' => '"' . $row['etag'] . '"',
1118
+                'calendarid' => $row['calendarid'],
1119
+                'calendaruri' => $row['calendaruri'],
1120
+                'size' => (int)$row['size'],
1121
+                'component' => strtolower($row['componenttype']),
1122
+                'classification' => (int)$row['classification'],
1123
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'],
1124
+            ];
1125
+        }
1126
+        $stmt->closeCursor();
1127
+
1128
+        return $result;
1129
+    }
1130
+
1131
+    /**
1132
+     * Returns information from a single calendar object, based on it's object
1133
+     * uri.
1134
+     *
1135
+     * The object uri is only the basename, or filename and not a full path.
1136
+     *
1137
+     * The returned array must have the same keys as getCalendarObjects. The
1138
+     * 'calendardata' object is required here though, while it's not required
1139
+     * for getCalendarObjects.
1140
+     *
1141
+     * This method must return null if the object did not exist.
1142
+     *
1143
+     * @param mixed $calendarId
1144
+     * @param string $objectUri
1145
+     * @param int $calendarType
1146
+     * @return array|null
1147
+     */
1148
+    public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1149
+        $query = $this->db->getQueryBuilder();
1150
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1151
+            ->from('calendarobjects')
1152
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1153
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1154
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1155
+        $stmt = $query->executeQuery();
1156
+        $row = $stmt->fetch();
1157
+        $stmt->closeCursor();
1158
+
1159
+        if (!$row) {
1160
+            return null;
1161
+        }
1162
+
1163
+        return [
1164
+            'id' => $row['id'],
1165
+            'uri' => $row['uri'],
1166
+            'lastmodified' => $row['lastmodified'],
1167
+            'etag' => '"' . $row['etag'] . '"',
1168
+            'calendarid' => $row['calendarid'],
1169
+            'size' => (int)$row['size'],
1170
+            'calendardata' => $this->readBlob($row['calendardata']),
1171
+            'component' => strtolower($row['componenttype']),
1172
+            'classification' => (int)$row['classification']
1173
+        ];
1174
+    }
1175
+
1176
+    /**
1177
+     * Returns a list of calendar objects.
1178
+     *
1179
+     * This method should work identical to getCalendarObject, but instead
1180
+     * return all the calendar objects in the list as an array.
1181
+     *
1182
+     * If the backend supports this, it may allow for some speed-ups.
1183
+     *
1184
+     * @param mixed $calendarId
1185
+     * @param string[] $uris
1186
+     * @param int $calendarType
1187
+     * @return array
1188
+     */
1189
+    public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1190
+        if (empty($uris)) {
1191
+            return [];
1192
+        }
1193
+
1194
+        $chunks = array_chunk($uris, 100);
1195
+        $objects = [];
1196
+
1197
+        $query = $this->db->getQueryBuilder();
1198
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1199
+            ->from('calendarobjects')
1200
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1201
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1202
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1203
+            ->andWhere($query->expr()->isNull('deleted_at'));
1204
+
1205
+        foreach ($chunks as $uris) {
1206
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1207
+            $result = $query->executeQuery();
1208
+
1209
+            while ($row = $result->fetch()) {
1210
+                $objects[] = [
1211
+                    'id' => $row['id'],
1212
+                    'uri' => $row['uri'],
1213
+                    'lastmodified' => $row['lastmodified'],
1214
+                    'etag' => '"' . $row['etag'] . '"',
1215
+                    'calendarid' => $row['calendarid'],
1216
+                    'size' => (int)$row['size'],
1217
+                    'calendardata' => $this->readBlob($row['calendardata']),
1218
+                    'component' => strtolower($row['componenttype']),
1219
+                    'classification' => (int)$row['classification']
1220
+                ];
1221
+            }
1222
+            $result->closeCursor();
1223
+        }
1224
+
1225
+        return $objects;
1226
+    }
1227
+
1228
+    /**
1229
+     * Creates a new calendar object.
1230
+     *
1231
+     * The object uri is only the basename, or filename and not a full path.
1232
+     *
1233
+     * It is possible return an etag from this function, which will be used in
1234
+     * the response to this PUT request. Note that the ETag must be surrounded
1235
+     * by double-quotes.
1236
+     *
1237
+     * However, you should only really return this ETag if you don't mangle the
1238
+     * calendar-data. If the result of a subsequent GET to this object is not
1239
+     * the exact same as this request body, you should omit the ETag.
1240
+     *
1241
+     * @param mixed $calendarId
1242
+     * @param string $objectUri
1243
+     * @param string $calendarData
1244
+     * @param int $calendarType
1245
+     * @return string
1246
+     */
1247
+    public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1248
+        $extraData = $this->getDenormalizedData($calendarData);
1249
+
1250
+        // Try to detect duplicates
1251
+        $qb = $this->db->getQueryBuilder();
1252
+        $qb->select($qb->func()->count('*'))
1253
+            ->from('calendarobjects')
1254
+            ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1255
+            ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($extraData['uid'])))
1256
+            ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1257
+            ->andWhere($qb->expr()->isNull('deleted_at'));
1258
+        $result = $qb->executeQuery();
1259
+        $count = (int) $result->fetchOne();
1260
+        $result->closeCursor();
1261
+
1262
+        if ($count !== 0) {
1263
+            throw new BadRequest('Calendar object with uid already exists in this calendar collection.');
1264
+        }
1265
+        // For a more specific error message we also try to explicitly look up the UID but as a deleted entry
1266
+        $qbDel = $this->db->getQueryBuilder();
1267
+        $qbDel->select($qb->func()->count('*'))
1268
+            ->from('calendarobjects')
1269
+            ->where($qbDel->expr()->eq('calendarid', $qbDel->createNamedParameter($calendarId)))
1270
+            ->andWhere($qbDel->expr()->eq('uid', $qbDel->createNamedParameter($extraData['uid'])))
1271
+            ->andWhere($qbDel->expr()->eq('calendartype', $qbDel->createNamedParameter($calendarType)))
1272
+            ->andWhere($qbDel->expr()->isNotNull('deleted_at'));
1273
+        $result = $qbDel->executeQuery();
1274
+        $count = (int) $result->fetchOne();
1275
+        $result->closeCursor();
1276
+        if ($count !== 0) {
1277
+            throw new BadRequest('Deleted calendar object with uid already exists in this calendar collection.');
1278
+        }
1279
+
1280
+        $query = $this->db->getQueryBuilder();
1281
+        $query->insert('calendarobjects')
1282
+            ->values([
1283
+                'calendarid' => $query->createNamedParameter($calendarId),
1284
+                'uri' => $query->createNamedParameter($objectUri),
1285
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1286
+                'lastmodified' => $query->createNamedParameter(time()),
1287
+                'etag' => $query->createNamedParameter($extraData['etag']),
1288
+                'size' => $query->createNamedParameter($extraData['size']),
1289
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
1290
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1291
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1292
+                'classification' => $query->createNamedParameter($extraData['classification']),
1293
+                'uid' => $query->createNamedParameter($extraData['uid']),
1294
+                'calendartype' => $query->createNamedParameter($calendarType),
1295
+            ])
1296
+            ->executeStatement();
1297
+
1298
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1299
+        $this->addChange($calendarId, $objectUri, 1, $calendarType);
1300
+
1301
+        $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1302
+        if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1303
+            $calendarRow = $this->getCalendarById($calendarId);
1304
+            $shares = $this->getShares($calendarId);
1305
+
1306
+            $this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent((int)$calendarId, $calendarRow, $shares, $objectRow));
1307
+        } else {
1308
+            $subscriptionRow = $this->getSubscriptionById($calendarId);
1309
+
1310
+            $this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow));
1311
+            $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1312
+                '\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1313
+                [
1314
+                    'subscriptionId' => $calendarId,
1315
+                    'calendarData' => $subscriptionRow,
1316
+                    'shares' => [],
1317
+                    'objectData' => $objectRow,
1318
+                ]
1319
+            ));
1320
+        }
1321
+
1322
+        return '"' . $extraData['etag'] . '"';
1323
+    }
1324
+
1325
+    /**
1326
+     * Updates an existing calendarobject, based on it's uri.
1327
+     *
1328
+     * The object uri is only the basename, or filename and not a full path.
1329
+     *
1330
+     * It is possible return an etag from this function, which will be used in
1331
+     * the response to this PUT request. Note that the ETag must be surrounded
1332
+     * by double-quotes.
1333
+     *
1334
+     * However, you should only really return this ETag if you don't mangle the
1335
+     * calendar-data. If the result of a subsequent GET to this object is not
1336
+     * the exact same as this request body, you should omit the ETag.
1337
+     *
1338
+     * @param mixed $calendarId
1339
+     * @param string $objectUri
1340
+     * @param string $calendarData
1341
+     * @param int $calendarType
1342
+     * @return string
1343
+     */
1344
+    public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1345
+        $extraData = $this->getDenormalizedData($calendarData);
1346
+        $query = $this->db->getQueryBuilder();
1347
+        $query->update('calendarobjects')
1348
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1349
+                ->set('lastmodified', $query->createNamedParameter(time()))
1350
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1351
+                ->set('size', $query->createNamedParameter($extraData['size']))
1352
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1353
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1354
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1355
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1356
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1357
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1358
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1359
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1360
+            ->executeStatement();
1361
+
1362
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1363
+        $this->addChange($calendarId, $objectUri, 2, $calendarType);
1364
+
1365
+        $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1366
+        if (is_array($objectRow)) {
1367
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1368
+                $calendarRow = $this->getCalendarById($calendarId);
1369
+                $shares = $this->getShares($calendarId);
1370
+
1371
+                $this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent((int)$calendarId, $calendarRow, $shares, $objectRow));
1372
+            } else {
1373
+                $subscriptionRow = $this->getSubscriptionById($calendarId);
1374
+
1375
+                $this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow));
1376
+                $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1377
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1378
+                    [
1379
+                        'subscriptionId' => $calendarId,
1380
+                        'calendarData' => $subscriptionRow,
1381
+                        'shares' => [],
1382
+                        'objectData' => $objectRow,
1383
+                    ]
1384
+                ));
1385
+            }
1386
+        }
1387
+
1388
+        return '"' . $extraData['etag'] . '"';
1389
+    }
1390
+
1391
+    /**
1392
+     * @param int $calendarObjectId
1393
+     * @param int $classification
1394
+     */
1395
+    public function setClassification($calendarObjectId, $classification) {
1396
+        if (!in_array($classification, [
1397
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1398
+        ])) {
1399
+            throw new \InvalidArgumentException();
1400
+        }
1401
+        $query = $this->db->getQueryBuilder();
1402
+        $query->update('calendarobjects')
1403
+            ->set('classification', $query->createNamedParameter($classification))
1404
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1405
+            ->executeStatement();
1406
+    }
1407
+
1408
+    /**
1409
+     * Deletes an existing calendar object.
1410
+     *
1411
+     * The object uri is only the basename, or filename and not a full path.
1412
+     *
1413
+     * @param mixed $calendarId
1414
+     * @param string $objectUri
1415
+     * @param int $calendarType
1416
+     * @param bool $forceDeletePermanently
1417
+     * @return void
1418
+     */
1419
+    public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
1420
+        $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1421
+
1422
+        if ($data === null) {
1423
+            // Nothing to delete
1424
+            return;
1425
+        }
1426
+
1427
+        if ($forceDeletePermanently || $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0') {
1428
+            $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1429
+            $stmt->execute([$calendarId, $objectUri, $calendarType]);
1430
+
1431
+            $this->purgeProperties($calendarId, $data['id']);
1432
+
1433
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1434
+                $calendarRow = $this->getCalendarById($calendarId);
1435
+                $shares = $this->getShares($calendarId);
1436
+
1437
+                $this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent((int)$calendarId, $calendarRow, $shares, $data));
1438
+            } else {
1439
+                $subscriptionRow = $this->getSubscriptionById($calendarId);
1440
+
1441
+                $this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent((int)$calendarId, $subscriptionRow, [], $data));
1442
+                $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1443
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1444
+                    [
1445
+                        'subscriptionId' => $calendarId,
1446
+                        'calendarData' => $subscriptionRow,
1447
+                        'shares' => [],
1448
+                        'objectData' => $data,
1449
+                    ]
1450
+                ));
1451
+            }
1452
+        } else {
1453
+            $pathInfo = pathinfo($data['uri']);
1454
+            if (!empty($pathInfo['extension'])) {
1455
+                // Append a suffix to "free" the old URI for recreation
1456
+                $newUri = sprintf(
1457
+                    "%s-deleted.%s",
1458
+                    $pathInfo['filename'],
1459
+                    $pathInfo['extension']
1460
+                );
1461
+            } else {
1462
+                $newUri = sprintf(
1463
+                    "%s-deleted",
1464
+                    $pathInfo['filename']
1465
+                );
1466
+            }
1467
+
1468
+            // Try to detect conflicts before the DB does
1469
+            // As unlikely as it seems, this can happen when the user imports, then deletes, imports and deletes again
1470
+            $newObject = $this->getCalendarObject($calendarId, $newUri, $calendarType);
1471
+            if ($newObject !== null) {
1472
+                throw new Forbidden("A calendar object with URI $newUri already exists in calendar $calendarId, therefore this object can't be moved into the trashbin");
1473
+            }
1474
+
1475
+            $qb = $this->db->getQueryBuilder();
1476
+            $markObjectDeletedQuery = $qb->update('calendarobjects')
1477
+                ->set('deleted_at', $qb->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
1478
+                ->set('uri', $qb->createNamedParameter($newUri))
1479
+                ->where(
1480
+                    $qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
1481
+                    $qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
1482
+                    $qb->expr()->eq('uri', $qb->createNamedParameter($objectUri))
1483
+                );
1484
+            $markObjectDeletedQuery->executeStatement();
1485
+
1486
+            $calendarData = $this->getCalendarById($calendarId);
1487
+            if ($calendarData !== null) {
1488
+                $this->dispatcher->dispatchTyped(
1489
+                    new CalendarObjectMovedToTrashEvent(
1490
+                        (int)$calendarId,
1491
+                        $calendarData,
1492
+                        $this->getShares($calendarId),
1493
+                        $data
1494
+                    )
1495
+                );
1496
+            }
1497
+        }
1498
+
1499
+        $this->addChange($calendarId, $objectUri, 3, $calendarType);
1500
+    }
1501
+
1502
+    /**
1503
+     * @param mixed $objectData
1504
+     *
1505
+     * @throws Forbidden
1506
+     */
1507
+    public function restoreCalendarObject(array $objectData): void {
1508
+        $id = (int) $objectData['id'];
1509
+        $restoreUri = str_replace("-deleted.ics", ".ics", $objectData['uri']);
1510
+        $targetObject = $this->getCalendarObject(
1511
+            $objectData['calendarid'],
1512
+            $restoreUri
1513
+        );
1514
+        if ($targetObject !== null) {
1515
+            throw new Forbidden("Can not restore calendar $id because a calendar object with the URI $restoreUri already exists");
1516
+        }
1517
+
1518
+        $qb = $this->db->getQueryBuilder();
1519
+        $update = $qb->update('calendarobjects')
1520
+            ->set('uri', $qb->createNamedParameter($restoreUri))
1521
+            ->set('deleted_at', $qb->createNamedParameter(null))
1522
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1523
+        $update->executeStatement();
1524
+
1525
+        // Make sure this change is tracked in the changes table
1526
+        $qb2 = $this->db->getQueryBuilder();
1527
+        $selectObject = $qb2->select('calendardata', 'uri', 'calendarid', 'calendartype')
1528
+            ->selectAlias('componenttype', 'component')
1529
+            ->from('calendarobjects')
1530
+            ->where($qb2->expr()->eq('id', $qb2->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1531
+        $result = $selectObject->executeQuery();
1532
+        $row = $result->fetch();
1533
+        $result->closeCursor();
1534
+        if ($row === false) {
1535
+            // Welp, this should possibly not have happened, but let's ignore
1536
+            return;
1537
+        }
1538
+        $this->addChange($row['calendarid'], $row['uri'], 1, (int) $row['calendartype']);
1539
+
1540
+        $calendarRow = $this->getCalendarById((int) $row['calendarid']);
1541
+        if ($calendarRow === null) {
1542
+            throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
1543
+        }
1544
+        $this->dispatcher->dispatchTyped(
1545
+            new CalendarObjectRestoredEvent(
1546
+                (int) $objectData['calendarid'],
1547
+                $calendarRow,
1548
+                $this->getShares((int) $row['calendarid']),
1549
+                $row
1550
+            )
1551
+        );
1552
+    }
1553
+
1554
+    /**
1555
+     * Performs a calendar-query on the contents of this calendar.
1556
+     *
1557
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1558
+     * calendar-query it is possible for a client to request a specific set of
1559
+     * object, based on contents of iCalendar properties, date-ranges and
1560
+     * iCalendar component types (VTODO, VEVENT).
1561
+     *
1562
+     * This method should just return a list of (relative) urls that match this
1563
+     * query.
1564
+     *
1565
+     * The list of filters are specified as an array. The exact array is
1566
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1567
+     *
1568
+     * Note that it is extremely likely that getCalendarObject for every path
1569
+     * returned from this method will be called almost immediately after. You
1570
+     * may want to anticipate this to speed up these requests.
1571
+     *
1572
+     * This method provides a default implementation, which parses *all* the
1573
+     * iCalendar objects in the specified calendar.
1574
+     *
1575
+     * This default may well be good enough for personal use, and calendars
1576
+     * that aren't very large. But if you anticipate high usage, big calendars
1577
+     * or high loads, you are strongly advised to optimize certain paths.
1578
+     *
1579
+     * The best way to do so is override this method and to optimize
1580
+     * specifically for 'common filters'.
1581
+     *
1582
+     * Requests that are extremely common are:
1583
+     *   * requests for just VEVENTS
1584
+     *   * requests for just VTODO
1585
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1586
+     *
1587
+     * ..and combinations of these requests. It may not be worth it to try to
1588
+     * handle every possible situation and just rely on the (relatively
1589
+     * easy to use) CalendarQueryValidator to handle the rest.
1590
+     *
1591
+     * Note that especially time-range-filters may be difficult to parse. A
1592
+     * time-range filter specified on a VEVENT must for instance also handle
1593
+     * recurrence rules correctly.
1594
+     * A good example of how to interprete all these filters can also simply
1595
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1596
+     * as possible, so it gives you a good idea on what type of stuff you need
1597
+     * to think of.
1598
+     *
1599
+     * @param mixed $calendarId
1600
+     * @param array $filters
1601
+     * @param int $calendarType
1602
+     * @return array
1603
+     */
1604
+    public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1605
+        $componentType = null;
1606
+        $requirePostFilter = true;
1607
+        $timeRange = null;
1608
+
1609
+        // if no filters were specified, we don't need to filter after a query
1610
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1611
+            $requirePostFilter = false;
1612
+        }
1613
+
1614
+        // Figuring out if there's a component filter
1615
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1616
+            $componentType = $filters['comp-filters'][0]['name'];
1617
+
1618
+            // Checking if we need post-filters
1619
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1620
+                $requirePostFilter = false;
1621
+            }
1622
+            // There was a time-range filter
1623
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
1624
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1625
+
1626
+                // If start time OR the end time is not specified, we can do a
1627
+                // 100% accurate mysql query.
1628
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1629
+                    $requirePostFilter = false;
1630
+                }
1631
+            }
1632
+        }
1633
+        $columns = ['uri'];
1634
+        if ($requirePostFilter) {
1635
+            $columns = ['uri', 'calendardata'];
1636
+        }
1637
+        $query = $this->db->getQueryBuilder();
1638
+        $query->select($columns)
1639
+            ->from('calendarobjects')
1640
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1641
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1642
+            ->andWhere($query->expr()->isNull('deleted_at'));
1643
+
1644
+        if ($componentType) {
1645
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1646
+        }
1647
+
1648
+        if ($timeRange && $timeRange['start']) {
1649
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1650
+        }
1651
+        if ($timeRange && $timeRange['end']) {
1652
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1653
+        }
1654
+
1655
+        $stmt = $query->executeQuery();
1656
+
1657
+        $result = [];
1658
+        while ($row = $stmt->fetch()) {
1659
+            if ($requirePostFilter) {
1660
+                // validateFilterForObject will parse the calendar data
1661
+                // catch parsing errors
1662
+                try {
1663
+                    $matches = $this->validateFilterForObject($row, $filters);
1664
+                } catch (ParseException $ex) {
1665
+                    $this->logger->logException($ex, [
1666
+                        'app' => 'dav',
1667
+                        'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1668
+                    ]);
1669
+                    continue;
1670
+                } catch (InvalidDataException $ex) {
1671
+                    $this->logger->logException($ex, [
1672
+                        'app' => 'dav',
1673
+                        'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri']
1674
+                    ]);
1675
+                    continue;
1676
+                }
1677
+
1678
+                if (!$matches) {
1679
+                    continue;
1680
+                }
1681
+            }
1682
+            $result[] = $row['uri'];
1683
+        }
1684
+
1685
+        return $result;
1686
+    }
1687
+
1688
+    /**
1689
+     * custom Nextcloud search extension for CalDAV
1690
+     *
1691
+     * TODO - this should optionally cover cached calendar objects as well
1692
+     *
1693
+     * @param string $principalUri
1694
+     * @param array $filters
1695
+     * @param integer|null $limit
1696
+     * @param integer|null $offset
1697
+     * @return array
1698
+     */
1699
+    public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1700
+        $calendars = $this->getCalendarsForUser($principalUri);
1701
+        $ownCalendars = [];
1702
+        $sharedCalendars = [];
1703
+
1704
+        $uriMapper = [];
1705
+
1706
+        foreach ($calendars as $calendar) {
1707
+            if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1708
+                $ownCalendars[] = $calendar['id'];
1709
+            } else {
1710
+                $sharedCalendars[] = $calendar['id'];
1711
+            }
1712
+            $uriMapper[$calendar['id']] = $calendar['uri'];
1713
+        }
1714
+        if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1715
+            return [];
1716
+        }
1717
+
1718
+        $query = $this->db->getQueryBuilder();
1719
+        // Calendar id expressions
1720
+        $calendarExpressions = [];
1721
+        foreach ($ownCalendars as $id) {
1722
+            $calendarExpressions[] = $query->expr()->andX(
1723
+                $query->expr()->eq('c.calendarid',
1724
+                    $query->createNamedParameter($id)),
1725
+                $query->expr()->eq('c.calendartype',
1726
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1727
+        }
1728
+        foreach ($sharedCalendars as $id) {
1729
+            $calendarExpressions[] = $query->expr()->andX(
1730
+                $query->expr()->eq('c.calendarid',
1731
+                    $query->createNamedParameter($id)),
1732
+                $query->expr()->eq('c.classification',
1733
+                    $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1734
+                $query->expr()->eq('c.calendartype',
1735
+                    $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1736
+        }
1737
+
1738
+        if (count($calendarExpressions) === 1) {
1739
+            $calExpr = $calendarExpressions[0];
1740
+        } else {
1741
+            $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1742
+        }
1743
+
1744
+        // Component expressions
1745
+        $compExpressions = [];
1746
+        foreach ($filters['comps'] as $comp) {
1747
+            $compExpressions[] = $query->expr()
1748
+                ->eq('c.componenttype', $query->createNamedParameter($comp));
1749
+        }
1750
+
1751
+        if (count($compExpressions) === 1) {
1752
+            $compExpr = $compExpressions[0];
1753
+        } else {
1754
+            $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1755
+        }
1756
+
1757
+        if (!isset($filters['props'])) {
1758
+            $filters['props'] = [];
1759
+        }
1760
+        if (!isset($filters['params'])) {
1761
+            $filters['params'] = [];
1762
+        }
1763
+
1764
+        $propParamExpressions = [];
1765
+        foreach ($filters['props'] as $prop) {
1766
+            $propParamExpressions[] = $query->expr()->andX(
1767
+                $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1768
+                $query->expr()->isNull('i.parameter')
1769
+            );
1770
+        }
1771
+        foreach ($filters['params'] as $param) {
1772
+            $propParamExpressions[] = $query->expr()->andX(
1773
+                $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1774
+                $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1775
+            );
1776
+        }
1777
+
1778
+        if (count($propParamExpressions) === 1) {
1779
+            $propParamExpr = $propParamExpressions[0];
1780
+        } else {
1781
+            $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1782
+        }
1783
+
1784
+        $query->select(['c.calendarid', 'c.uri'])
1785
+            ->from($this->dbObjectPropertiesTable, 'i')
1786
+            ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1787
+            ->where($calExpr)
1788
+            ->andWhere($compExpr)
1789
+            ->andWhere($propParamExpr)
1790
+            ->andWhere($query->expr()->iLike('i.value',
1791
+                $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')))
1792
+            ->andWhere($query->expr()->isNull('deleted_at'));
1793
+
1794
+        if ($offset) {
1795
+            $query->setFirstResult($offset);
1796
+        }
1797
+        if ($limit) {
1798
+            $query->setMaxResults($limit);
1799
+        }
1800
+
1801
+        $stmt = $query->executeQuery();
1802
+
1803
+        $result = [];
1804
+        while ($row = $stmt->fetch()) {
1805
+            $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1806
+            if (!in_array($path, $result)) {
1807
+                $result[] = $path;
1808
+            }
1809
+        }
1810
+
1811
+        return $result;
1812
+    }
1813
+
1814
+    /**
1815
+     * used for Nextcloud's calendar API
1816
+     *
1817
+     * @param array $calendarInfo
1818
+     * @param string $pattern
1819
+     * @param array $searchProperties
1820
+     * @param array $options
1821
+     * @param integer|null $limit
1822
+     * @param integer|null $offset
1823
+     *
1824
+     * @return array
1825
+     */
1826
+    public function search(array $calendarInfo, $pattern, array $searchProperties,
1827
+                            array $options, $limit, $offset) {
1828
+        $outerQuery = $this->db->getQueryBuilder();
1829
+        $innerQuery = $this->db->getQueryBuilder();
1830
+
1831
+        $innerQuery->selectDistinct('op.objectid')
1832
+            ->from($this->dbObjectPropertiesTable, 'op')
1833
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
1834
+                $outerQuery->createNamedParameter($calendarInfo['id'])))
1835
+            ->andWhere($innerQuery->expr()->eq('op.calendartype',
1836
+                $outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1837
+
1838
+        // only return public items for shared calendars for now
1839
+        if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1840
+            $innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1841
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1842
+        }
1843
+
1844
+        $or = $innerQuery->expr()->orX();
1845
+        foreach ($searchProperties as $searchProperty) {
1846
+            $or->add($innerQuery->expr()->eq('op.name',
1847
+                $outerQuery->createNamedParameter($searchProperty)));
1848
+        }
1849
+        $innerQuery->andWhere($or);
1850
+
1851
+        if ($pattern !== '') {
1852
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1853
+                $outerQuery->createNamedParameter('%' .
1854
+                    $this->db->escapeLikeParameter($pattern) . '%')));
1855
+        }
1856
+
1857
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1858
+            ->from('calendarobjects', 'c')
1859
+            ->where($outerQuery->expr()->isNull('deleted_at'));
1860
+
1861
+        if (isset($options['timerange'])) {
1862
+            if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTime) {
1863
+                $outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1864
+                    $outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp())));
1865
+            }
1866
+            if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTime) {
1867
+                $outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1868
+                    $outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp())));
1869
+            }
1870
+        }
1871
+
1872
+        if (isset($options['types'])) {
1873
+            $or = $outerQuery->expr()->orX();
1874
+            foreach ($options['types'] as $type) {
1875
+                $or->add($outerQuery->expr()->eq('componenttype',
1876
+                    $outerQuery->createNamedParameter($type)));
1877
+            }
1878
+            $outerQuery->andWhere($or);
1879
+        }
1880
+
1881
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id',
1882
+            $outerQuery->createFunction($innerQuery->getSQL())));
1883
+
1884
+        if ($offset) {
1885
+            $outerQuery->setFirstResult($offset);
1886
+        }
1887
+        if ($limit) {
1888
+            $outerQuery->setMaxResults($limit);
1889
+        }
1890
+
1891
+        $result = $outerQuery->executeQuery();
1892
+        $calendarObjects = $result->fetchAll();
1893
+
1894
+        return array_map(function ($o) {
1895
+            $calendarData = Reader::read($o['calendardata']);
1896
+            $comps = $calendarData->getComponents();
1897
+            $objects = [];
1898
+            $timezones = [];
1899
+            foreach ($comps as $comp) {
1900
+                if ($comp instanceof VTimeZone) {
1901
+                    $timezones[] = $comp;
1902
+                } else {
1903
+                    $objects[] = $comp;
1904
+                }
1905
+            }
1906
+
1907
+            return [
1908
+                'id' => $o['id'],
1909
+                'type' => $o['componenttype'],
1910
+                'uid' => $o['uid'],
1911
+                'uri' => $o['uri'],
1912
+                'objects' => array_map(function ($c) {
1913
+                    return $this->transformSearchData($c);
1914
+                }, $objects),
1915
+                'timezones' => array_map(function ($c) {
1916
+                    return $this->transformSearchData($c);
1917
+                }, $timezones),
1918
+            ];
1919
+        }, $calendarObjects);
1920
+    }
1921
+
1922
+    /**
1923
+     * @param Component $comp
1924
+     * @return array
1925
+     */
1926
+    private function transformSearchData(Component $comp) {
1927
+        $data = [];
1928
+        /** @var Component[] $subComponents */
1929
+        $subComponents = $comp->getComponents();
1930
+        /** @var Property[] $properties */
1931
+        $properties = array_filter($comp->children(), function ($c) {
1932
+            return $c instanceof Property;
1933
+        });
1934
+        $validationRules = $comp->getValidationRules();
1935
+
1936
+        foreach ($subComponents as $subComponent) {
1937
+            $name = $subComponent->name;
1938
+            if (!isset($data[$name])) {
1939
+                $data[$name] = [];
1940
+            }
1941
+            $data[$name][] = $this->transformSearchData($subComponent);
1942
+        }
1943
+
1944
+        foreach ($properties as $property) {
1945
+            $name = $property->name;
1946
+            if (!isset($validationRules[$name])) {
1947
+                $validationRules[$name] = '*';
1948
+            }
1949
+
1950
+            $rule = $validationRules[$property->name];
1951
+            if ($rule === '+' || $rule === '*') { // multiple
1952
+                if (!isset($data[$name])) {
1953
+                    $data[$name] = [];
1954
+                }
1955
+
1956
+                $data[$name][] = $this->transformSearchProperty($property);
1957
+            } else { // once
1958
+                $data[$name] = $this->transformSearchProperty($property);
1959
+            }
1960
+        }
1961
+
1962
+        return $data;
1963
+    }
1964
+
1965
+    /**
1966
+     * @param Property $prop
1967
+     * @return array
1968
+     */
1969
+    private function transformSearchProperty(Property $prop) {
1970
+        // No need to check Date, as it extends DateTime
1971
+        if ($prop instanceof Property\ICalendar\DateTime) {
1972
+            $value = $prop->getDateTime();
1973
+        } else {
1974
+            $value = $prop->getValue();
1975
+        }
1976
+
1977
+        return [
1978
+            $value,
1979
+            $prop->parameters()
1980
+        ];
1981
+    }
1982
+
1983
+    /**
1984
+     * @param string $principalUri
1985
+     * @param string $pattern
1986
+     * @param array $componentTypes
1987
+     * @param array $searchProperties
1988
+     * @param array $searchParameters
1989
+     * @param array $options
1990
+     * @return array
1991
+     */
1992
+    public function searchPrincipalUri(string $principalUri,
1993
+                                        string $pattern,
1994
+                                        array $componentTypes,
1995
+                                        array $searchProperties,
1996
+                                        array $searchParameters,
1997
+                                        array $options = []): array {
1998
+        $escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
1999
+
2000
+        $calendarObjectIdQuery = $this->db->getQueryBuilder();
2001
+        $calendarOr = $calendarObjectIdQuery->expr()->orX();
2002
+        $searchOr = $calendarObjectIdQuery->expr()->orX();
2003
+
2004
+        // Fetch calendars and subscription
2005
+        $calendars = $this->getCalendarsForUser($principalUri);
2006
+        $subscriptions = $this->getSubscriptionsForUser($principalUri);
2007
+        foreach ($calendars as $calendar) {
2008
+            $calendarAnd = $calendarObjectIdQuery->expr()->andX();
2009
+            $calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])));
2010
+            $calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
2011
+
2012
+            // If it's shared, limit search to public events
2013
+            if (isset($calendar['{http://owncloud.org/ns}owner-principal'])
2014
+                && $calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
2015
+                $calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2016
+            }
2017
+
2018
+            $calendarOr->add($calendarAnd);
2019
+        }
2020
+        foreach ($subscriptions as $subscription) {
2021
+            $subscriptionAnd = $calendarObjectIdQuery->expr()->andX();
2022
+            $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])));
2023
+            $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2024
+
2025
+            // If it's shared, limit search to public events
2026
+            if (isset($subscription['{http://owncloud.org/ns}owner-principal'])
2027
+                && $subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
2028
+                $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2029
+            }
2030
+
2031
+            $calendarOr->add($subscriptionAnd);
2032
+        }
2033
+
2034
+        foreach ($searchProperties as $property) {
2035
+            $propertyAnd = $calendarObjectIdQuery->expr()->andX();
2036
+            $propertyAnd->add($calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)));
2037
+            $propertyAnd->add($calendarObjectIdQuery->expr()->isNull('cob.parameter'));
2038
+
2039
+            $searchOr->add($propertyAnd);
2040
+        }
2041
+        foreach ($searchParameters as $property => $parameter) {
2042
+            $parameterAnd = $calendarObjectIdQuery->expr()->andX();
2043
+            $parameterAnd->add($calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)));
2044
+            $parameterAnd->add($calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)));
2045
+
2046
+            $searchOr->add($parameterAnd);
2047
+        }
2048
+
2049
+        if ($calendarOr->count() === 0) {
2050
+            return [];
2051
+        }
2052
+        if ($searchOr->count() === 0) {
2053
+            return [];
2054
+        }
2055
+
2056
+        $calendarObjectIdQuery->selectDistinct('cob.objectid')
2057
+            ->from($this->dbObjectPropertiesTable, 'cob')
2058
+            ->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
2059
+            ->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
2060
+            ->andWhere($calendarOr)
2061
+            ->andWhere($searchOr)
2062
+            ->andWhere($calendarObjectIdQuery->expr()->isNull('deleted_at'));
2063
+
2064
+        if ('' !== $pattern) {
2065
+            if (!$escapePattern) {
2066
+                $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
2067
+            } else {
2068
+                $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
2069
+            }
2070
+        }
2071
+
2072
+        if (isset($options['limit'])) {
2073
+            $calendarObjectIdQuery->setMaxResults($options['limit']);
2074
+        }
2075
+        if (isset($options['offset'])) {
2076
+            $calendarObjectIdQuery->setFirstResult($options['offset']);
2077
+        }
2078
+
2079
+        $result = $calendarObjectIdQuery->executeQuery();
2080
+        $matches = $result->fetchAll();
2081
+        $result->closeCursor();
2082
+        $matches = array_map(static function (array $match):int {
2083
+            return (int) $match['objectid'];
2084
+        }, $matches);
2085
+
2086
+        $query = $this->db->getQueryBuilder();
2087
+        $query->select('calendardata', 'uri', 'calendarid', 'calendartype')
2088
+            ->from('calendarobjects')
2089
+            ->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
2090
+
2091
+        $result = $query->executeQuery();
2092
+        $calendarObjects = $result->fetchAll();
2093
+        $result->closeCursor();
2094
+
2095
+        return array_map(function (array $array): array {
2096
+            $array['calendarid'] = (int)$array['calendarid'];
2097
+            $array['calendartype'] = (int)$array['calendartype'];
2098
+            $array['calendardata'] = $this->readBlob($array['calendardata']);
2099
+
2100
+            return $array;
2101
+        }, $calendarObjects);
2102
+    }
2103
+
2104
+    /**
2105
+     * Searches through all of a users calendars and calendar objects to find
2106
+     * an object with a specific UID.
2107
+     *
2108
+     * This method should return the path to this object, relative to the
2109
+     * calendar home, so this path usually only contains two parts:
2110
+     *
2111
+     * calendarpath/objectpath.ics
2112
+     *
2113
+     * If the uid is not found, return null.
2114
+     *
2115
+     * This method should only consider * objects that the principal owns, so
2116
+     * any calendars owned by other principals that also appear in this
2117
+     * collection should be ignored.
2118
+     *
2119
+     * @param string $principalUri
2120
+     * @param string $uid
2121
+     * @return string|null
2122
+     */
2123
+    public function getCalendarObjectByUID($principalUri, $uid) {
2124
+        $query = $this->db->getQueryBuilder();
2125
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
2126
+            ->from('calendarobjects', 'co')
2127
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
2128
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2129
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
2130
+            ->andWhere($query->expr()->isNull('co.deleted_at'));
2131
+        $stmt = $query->executeQuery();
2132
+        $row = $stmt->fetch();
2133
+        $stmt->closeCursor();
2134
+        if ($row) {
2135
+            return $row['calendaruri'] . '/' . $row['objecturi'];
2136
+        }
2137
+
2138
+        return null;
2139
+    }
2140
+
2141
+    public function getCalendarObjectById(string $principalUri, int $id): ?array {
2142
+        $query = $this->db->getQueryBuilder();
2143
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.calendardata', 'co.componenttype', 'co.classification', 'co.deleted_at'])
2144
+            ->selectAlias('c.uri', 'calendaruri')
2145
+            ->from('calendarobjects', 'co')
2146
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
2147
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2148
+            ->andWhere($query->expr()->eq('co.id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
2149
+        $stmt = $query->executeQuery();
2150
+        $row = $stmt->fetch();
2151
+        $stmt->closeCursor();
2152
+
2153
+        if (!$row) {
2154
+            return null;
2155
+        }
2156
+
2157
+        return [
2158
+            'id' => $row['id'],
2159
+            'uri' => $row['uri'],
2160
+            'lastmodified' => $row['lastmodified'],
2161
+            'etag' => '"' . $row['etag'] . '"',
2162
+            'calendarid' => $row['calendarid'],
2163
+            'calendaruri' => $row['calendaruri'],
2164
+            'size' => (int)$row['size'],
2165
+            'calendardata' => $this->readBlob($row['calendardata']),
2166
+            'component' => strtolower($row['componenttype']),
2167
+            'classification' => (int)$row['classification'],
2168
+            'deleted_at' => isset($row['deleted_at']) ? ((int) $row['deleted_at']) : null,
2169
+        ];
2170
+    }
2171
+
2172
+    /**
2173
+     * The getChanges method returns all the changes that have happened, since
2174
+     * the specified syncToken in the specified calendar.
2175
+     *
2176
+     * This function should return an array, such as the following:
2177
+     *
2178
+     * [
2179
+     *   'syncToken' => 'The current synctoken',
2180
+     *   'added'   => [
2181
+     *      'new.txt',
2182
+     *   ],
2183
+     *   'modified'   => [
2184
+     *      'modified.txt',
2185
+     *   ],
2186
+     *   'deleted' => [
2187
+     *      'foo.php.bak',
2188
+     *      'old.txt'
2189
+     *   ]
2190
+     * );
2191
+     *
2192
+     * The returned syncToken property should reflect the *current* syncToken
2193
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
2194
+     * property This is * needed here too, to ensure the operation is atomic.
2195
+     *
2196
+     * If the $syncToken argument is specified as null, this is an initial
2197
+     * sync, and all members should be reported.
2198
+     *
2199
+     * The modified property is an array of nodenames that have changed since
2200
+     * the last token.
2201
+     *
2202
+     * The deleted property is an array with nodenames, that have been deleted
2203
+     * from collection.
2204
+     *
2205
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
2206
+     * 1, you only have to report changes that happened only directly in
2207
+     * immediate descendants. If it's 2, it should also include changes from
2208
+     * the nodes below the child collections. (grandchildren)
2209
+     *
2210
+     * The $limit argument allows a client to specify how many results should
2211
+     * be returned at most. If the limit is not specified, it should be treated
2212
+     * as infinite.
2213
+     *
2214
+     * If the limit (infinite or not) is higher than you're willing to return,
2215
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
2216
+     *
2217
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
2218
+     * return null.
2219
+     *
2220
+     * The limit is 'suggestive'. You are free to ignore it.
2221
+     *
2222
+     * @param string $calendarId
2223
+     * @param string $syncToken
2224
+     * @param int $syncLevel
2225
+     * @param int|null $limit
2226
+     * @param int $calendarType
2227
+     * @return array
2228
+     */
2229
+    public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2230
+        // Current synctoken
2231
+        $qb = $this->db->getQueryBuilder();
2232
+        $qb->select('synctoken')
2233
+            ->from('calendars')
2234
+            ->where(
2235
+                $qb->expr()->eq('id', $qb->createNamedParameter($calendarId))
2236
+            );
2237
+        $stmt = $qb->executeQuery();
2238
+        $currentToken = $stmt->fetchOne();
2239
+
2240
+        if ($currentToken === false) {
2241
+            return null;
2242
+        }
2243
+
2244
+        $result = [
2245
+            'syncToken' => $currentToken,
2246
+            'added' => [],
2247
+            'modified' => [],
2248
+            'deleted' => [],
2249
+        ];
2250
+
2251
+        if ($syncToken) {
2252
+            $qb = $this->db->getQueryBuilder();
2253
+
2254
+            $qb->select('uri', 'operation')
2255
+                ->from('calendarchanges')
2256
+                ->where(
2257
+                    $qb->expr()->andX(
2258
+                        $qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)),
2259
+                        $qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)),
2260
+                        $qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
2261
+                        $qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType))
2262
+                    )
2263
+                )->orderBy('synctoken');
2264
+            if (is_int($limit) && $limit > 0) {
2265
+                $qb->setMaxResults($limit);
2266
+            }
2267
+
2268
+            // Fetching all changes
2269
+            $stmt = $qb->executeQuery();
2270
+            $changes = [];
2271
+
2272
+            // This loop ensures that any duplicates are overwritten, only the
2273
+            // last change on a node is relevant.
2274
+            while ($row = $stmt->fetch()) {
2275
+                $changes[$row['uri']] = $row['operation'];
2276
+            }
2277
+            $stmt->closeCursor();
2278
+
2279
+            foreach ($changes as $uri => $operation) {
2280
+                switch ($operation) {
2281
+                    case 1:
2282
+                        $result['added'][] = $uri;
2283
+                        break;
2284
+                    case 2:
2285
+                        $result['modified'][] = $uri;
2286
+                        break;
2287
+                    case 3:
2288
+                        $result['deleted'][] = $uri;
2289
+                        break;
2290
+                }
2291
+            }
2292
+        } else {
2293
+            // No synctoken supplied, this is the initial sync.
2294
+            $qb = $this->db->getQueryBuilder();
2295
+            $qb->select('uri')
2296
+                ->from('calendarobjects')
2297
+                ->where(
2298
+                    $qb->expr()->andX(
2299
+                        $qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
2300
+                        $qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType))
2301
+                    )
2302
+                );
2303
+            $stmt = $qb->executeQuery();
2304
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
2305
+            $stmt->closeCursor();
2306
+        }
2307
+        return $result;
2308
+    }
2309
+
2310
+    /**
2311
+     * Returns a list of subscriptions for a principal.
2312
+     *
2313
+     * Every subscription is an array with the following keys:
2314
+     *  * id, a unique id that will be used by other functions to modify the
2315
+     *    subscription. This can be the same as the uri or a database key.
2316
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
2317
+     *  * principaluri. The owner of the subscription. Almost always the same as
2318
+     *    principalUri passed to this method.
2319
+     *
2320
+     * Furthermore, all the subscription info must be returned too:
2321
+     *
2322
+     * 1. {DAV:}displayname
2323
+     * 2. {http://apple.com/ns/ical/}refreshrate
2324
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
2325
+     *    should not be stripped).
2326
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
2327
+     *    should not be stripped).
2328
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
2329
+     *    attachments should not be stripped).
2330
+     * 6. {http://calendarserver.org/ns/}source (Must be a
2331
+     *     Sabre\DAV\Property\Href).
2332
+     * 7. {http://apple.com/ns/ical/}calendar-color
2333
+     * 8. {http://apple.com/ns/ical/}calendar-order
2334
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
2335
+     *    (should just be an instance of
2336
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
2337
+     *    default components).
2338
+     *
2339
+     * @param string $principalUri
2340
+     * @return array
2341
+     */
2342
+    public function getSubscriptionsForUser($principalUri) {
2343
+        $fields = array_values($this->subscriptionPropertyMap);
2344
+        $fields[] = 'id';
2345
+        $fields[] = 'uri';
2346
+        $fields[] = 'source';
2347
+        $fields[] = 'principaluri';
2348
+        $fields[] = 'lastmodified';
2349
+        $fields[] = 'synctoken';
2350
+
2351
+        $query = $this->db->getQueryBuilder();
2352
+        $query->select($fields)
2353
+            ->from('calendarsubscriptions')
2354
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2355
+            ->orderBy('calendarorder', 'asc');
2356
+        $stmt = $query->executeQuery();
2357
+
2358
+        $subscriptions = [];
2359
+        while ($row = $stmt->fetch()) {
2360
+            $subscription = [
2361
+                'id' => $row['id'],
2362
+                'uri' => $row['uri'],
2363
+                'principaluri' => $row['principaluri'],
2364
+                'source' => $row['source'],
2365
+                'lastmodified' => $row['lastmodified'],
2366
+
2367
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2368
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
2369
+            ];
2370
+
2371
+            foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
2372
+                if (!is_null($row[$dbName])) {
2373
+                    $subscription[$xmlName] = $row[$dbName];
2374
+                }
2375
+            }
2376
+
2377
+            $subscriptions[] = $subscription;
2378
+        }
2379
+
2380
+        return $subscriptions;
2381
+    }
2382
+
2383
+    /**
2384
+     * Creates a new subscription for a principal.
2385
+     *
2386
+     * If the creation was a success, an id must be returned that can be used to reference
2387
+     * this subscription in other methods, such as updateSubscription.
2388
+     *
2389
+     * @param string $principalUri
2390
+     * @param string $uri
2391
+     * @param array $properties
2392
+     * @return mixed
2393
+     */
2394
+    public function createSubscription($principalUri, $uri, array $properties) {
2395
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2396
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2397
+        }
2398
+
2399
+        $values = [
2400
+            'principaluri' => $principalUri,
2401
+            'uri' => $uri,
2402
+            'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2403
+            'lastmodified' => time(),
2404
+        ];
2405
+
2406
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2407
+
2408
+        foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
2409
+            if (array_key_exists($xmlName, $properties)) {
2410
+                $values[$dbName] = $properties[$xmlName];
2411
+                if (in_array($dbName, $propertiesBoolean)) {
2412
+                    $values[$dbName] = true;
2413
+                }
2414
+            }
2415
+        }
2416
+
2417
+        $valuesToInsert = [];
2418
+
2419
+        $query = $this->db->getQueryBuilder();
2420
+
2421
+        foreach (array_keys($values) as $name) {
2422
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2423
+        }
2424
+
2425
+        $query->insert('calendarsubscriptions')
2426
+            ->values($valuesToInsert)
2427
+            ->executeStatement();
2428
+
2429
+        $subscriptionId = $query->getLastInsertId();
2430
+
2431
+        $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2432
+        $this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow));
2433
+        $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
2434
+            '\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
2435
+            [
2436
+                'subscriptionId' => $subscriptionId,
2437
+                'subscriptionData' => $subscriptionRow,
2438
+            ]));
2439
+
2440
+        return $subscriptionId;
2441
+    }
2442
+
2443
+    /**
2444
+     * Updates a subscription
2445
+     *
2446
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2447
+     * To do the actual updates, you must tell this object which properties
2448
+     * you're going to process with the handle() method.
2449
+     *
2450
+     * Calling the handle method is like telling the PropPatch object "I
2451
+     * promise I can handle updating this property".
2452
+     *
2453
+     * Read the PropPatch documentation for more info and examples.
2454
+     *
2455
+     * @param mixed $subscriptionId
2456
+     * @param PropPatch $propPatch
2457
+     * @return void
2458
+     */
2459
+    public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2460
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
2461
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
2462
+
2463
+        $propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2464
+            $newValues = [];
2465
+
2466
+            foreach ($mutations as $propertyName => $propertyValue) {
2467
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
2468
+                    $newValues['source'] = $propertyValue->getHref();
2469
+                } else {
2470
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
2471
+                    $newValues[$fieldName] = $propertyValue;
2472
+                }
2473
+            }
2474
+
2475
+            $query = $this->db->getQueryBuilder();
2476
+            $query->update('calendarsubscriptions')
2477
+                ->set('lastmodified', $query->createNamedParameter(time()));
2478
+            foreach ($newValues as $fieldName => $value) {
2479
+                $query->set($fieldName, $query->createNamedParameter($value));
2480
+            }
2481
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2482
+                ->executeStatement();
2483
+
2484
+            $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2485
+            $this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2486
+            $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2487
+                '\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2488
+                [
2489
+                    'subscriptionId' => $subscriptionId,
2490
+                    'subscriptionData' => $subscriptionRow,
2491
+                    'propertyMutations' => $mutations,
2492
+                ]));
2493
+
2494
+            return true;
2495
+        });
2496
+    }
2497
+
2498
+    /**
2499
+     * Deletes a subscription.
2500
+     *
2501
+     * @param mixed $subscriptionId
2502
+     * @return void
2503
+     */
2504
+    public function deleteSubscription($subscriptionId) {
2505
+        $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2506
+
2507
+        $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2508
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2509
+            [
2510
+                'subscriptionId' => $subscriptionId,
2511
+                'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2512
+            ]));
2513
+
2514
+        $query = $this->db->getQueryBuilder();
2515
+        $query->delete('calendarsubscriptions')
2516
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2517
+            ->executeStatement();
2518
+
2519
+        $query = $this->db->getQueryBuilder();
2520
+        $query->delete('calendarobjects')
2521
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2522
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2523
+            ->executeStatement();
2524
+
2525
+        $query->delete('calendarchanges')
2526
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2527
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2528
+            ->executeStatement();
2529
+
2530
+        $query->delete($this->dbObjectPropertiesTable)
2531
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2532
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2533
+            ->executeStatement();
2534
+
2535
+        if ($subscriptionRow) {
2536
+            $this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2537
+        }
2538
+    }
2539
+
2540
+    /**
2541
+     * Returns a single scheduling object for the inbox collection.
2542
+     *
2543
+     * The returned array should contain the following elements:
2544
+     *   * uri - A unique basename for the object. This will be used to
2545
+     *           construct a full uri.
2546
+     *   * calendardata - The iCalendar object
2547
+     *   * lastmodified - The last modification date. Can be an int for a unix
2548
+     *                    timestamp, or a PHP DateTime object.
2549
+     *   * etag - A unique token that must change if the object changed.
2550
+     *   * size - The size of the object, in bytes.
2551
+     *
2552
+     * @param string $principalUri
2553
+     * @param string $objectUri
2554
+     * @return array
2555
+     */
2556
+    public function getSchedulingObject($principalUri, $objectUri) {
2557
+        $query = $this->db->getQueryBuilder();
2558
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2559
+            ->from('schedulingobjects')
2560
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2561
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2562
+            ->executeQuery();
2563
+
2564
+        $row = $stmt->fetch();
2565
+
2566
+        if (!$row) {
2567
+            return null;
2568
+        }
2569
+
2570
+        return [
2571
+            'uri' => $row['uri'],
2572
+            'calendardata' => $row['calendardata'],
2573
+            'lastmodified' => $row['lastmodified'],
2574
+            'etag' => '"' . $row['etag'] . '"',
2575
+            'size' => (int)$row['size'],
2576
+        ];
2577
+    }
2578
+
2579
+    /**
2580
+     * Returns all scheduling objects for the inbox collection.
2581
+     *
2582
+     * These objects should be returned as an array. Every item in the array
2583
+     * should follow the same structure as returned from getSchedulingObject.
2584
+     *
2585
+     * The main difference is that 'calendardata' is optional.
2586
+     *
2587
+     * @param string $principalUri
2588
+     * @return array
2589
+     */
2590
+    public function getSchedulingObjects($principalUri) {
2591
+        $query = $this->db->getQueryBuilder();
2592
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2593
+                ->from('schedulingobjects')
2594
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2595
+                ->executeQuery();
2596
+
2597
+        $result = [];
2598
+        foreach ($stmt->fetchAll() as $row) {
2599
+            $result[] = [
2600
+                'calendardata' => $row['calendardata'],
2601
+                'uri' => $row['uri'],
2602
+                'lastmodified' => $row['lastmodified'],
2603
+                'etag' => '"' . $row['etag'] . '"',
2604
+                'size' => (int)$row['size'],
2605
+            ];
2606
+        }
2607
+
2608
+        return $result;
2609
+    }
2610
+
2611
+    /**
2612
+     * Deletes a scheduling object from the inbox collection.
2613
+     *
2614
+     * @param string $principalUri
2615
+     * @param string $objectUri
2616
+     * @return void
2617
+     */
2618
+    public function deleteSchedulingObject($principalUri, $objectUri) {
2619
+        $query = $this->db->getQueryBuilder();
2620
+        $query->delete('schedulingobjects')
2621
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2622
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2623
+                ->executeStatement();
2624
+    }
2625
+
2626
+    /**
2627
+     * Creates a new scheduling object. This should land in a users' inbox.
2628
+     *
2629
+     * @param string $principalUri
2630
+     * @param string $objectUri
2631
+     * @param string $objectData
2632
+     * @return void
2633
+     */
2634
+    public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2635
+        $query = $this->db->getQueryBuilder();
2636
+        $query->insert('schedulingobjects')
2637
+            ->values([
2638
+                'principaluri' => $query->createNamedParameter($principalUri),
2639
+                'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2640
+                'uri' => $query->createNamedParameter($objectUri),
2641
+                'lastmodified' => $query->createNamedParameter(time()),
2642
+                'etag' => $query->createNamedParameter(md5($objectData)),
2643
+                'size' => $query->createNamedParameter(strlen($objectData))
2644
+            ])
2645
+            ->executeStatement();
2646
+    }
2647
+
2648
+    /**
2649
+     * Adds a change record to the calendarchanges table.
2650
+     *
2651
+     * @param mixed $calendarId
2652
+     * @param string $objectUri
2653
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2654
+     * @param int $calendarType
2655
+     * @return void
2656
+     */
2657
+    protected function addChange($calendarId, $objectUri, $operation, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2658
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2659
+
2660
+        $query = $this->db->getQueryBuilder();
2661
+        $query->select('synctoken')
2662
+            ->from($table)
2663
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2664
+        $result = $query->executeQuery();
2665
+        $syncToken = (int)$result->fetchOne();
2666
+        $result->closeCursor();
2667
+
2668
+        $query = $this->db->getQueryBuilder();
2669
+        $query->insert('calendarchanges')
2670
+            ->values([
2671
+                'uri' => $query->createNamedParameter($objectUri),
2672
+                'synctoken' => $query->createNamedParameter($syncToken),
2673
+                'calendarid' => $query->createNamedParameter($calendarId),
2674
+                'operation' => $query->createNamedParameter($operation),
2675
+                'calendartype' => $query->createNamedParameter($calendarType),
2676
+            ])
2677
+            ->executeStatement();
2678
+
2679
+        $stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2680
+        $stmt->execute([
2681
+            $calendarId
2682
+        ]);
2683
+    }
2684
+
2685
+    /**
2686
+     * Parses some information from calendar objects, used for optimized
2687
+     * calendar-queries.
2688
+     *
2689
+     * Returns an array with the following keys:
2690
+     *   * etag - An md5 checksum of the object without the quotes.
2691
+     *   * size - Size of the object in bytes
2692
+     *   * componentType - VEVENT, VTODO or VJOURNAL
2693
+     *   * firstOccurence
2694
+     *   * lastOccurence
2695
+     *   * uid - value of the UID property
2696
+     *
2697
+     * @param string $calendarData
2698
+     * @return array
2699
+     */
2700
+    public function getDenormalizedData($calendarData) {
2701
+        $vObject = Reader::read($calendarData);
2702
+        $vEvents = [];
2703
+        $componentType = null;
2704
+        $component = null;
2705
+        $firstOccurrence = null;
2706
+        $lastOccurrence = null;
2707
+        $uid = null;
2708
+        $classification = self::CLASSIFICATION_PUBLIC;
2709
+        $hasDTSTART = false;
2710
+        foreach ($vObject->getComponents() as $component) {
2711
+            if ($component->name !== 'VTIMEZONE') {
2712
+                // Finding all VEVENTs, and track them
2713
+                if ($component->name === 'VEVENT') {
2714
+                    array_push($vEvents, $component);
2715
+                    if ($component->DTSTART) {
2716
+                        $hasDTSTART = true;
2717
+                    }
2718
+                }
2719
+                // Track first component type and uid
2720
+                if ($uid === null) {
2721
+                    $componentType = $component->name;
2722
+                    $uid = (string)$component->UID;
2723
+                }
2724
+            }
2725
+        }
2726
+        if (!$componentType) {
2727
+            throw new BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2728
+        }
2729
+
2730
+        if ($hasDTSTART) {
2731
+            $component = $vEvents[0];
2732
+
2733
+            // Finding the last occurrence is a bit harder
2734
+            if (!isset($component->RRULE) && count($vEvents) === 1) {
2735
+                $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2736
+                if (isset($component->DTEND)) {
2737
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2738
+                } elseif (isset($component->DURATION)) {
2739
+                    $endDate = clone $component->DTSTART->getDateTime();
2740
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2741
+                    $lastOccurrence = $endDate->getTimeStamp();
2742
+                } elseif (!$component->DTSTART->hasTime()) {
2743
+                    $endDate = clone $component->DTSTART->getDateTime();
2744
+                    $endDate->modify('+1 day');
2745
+                    $lastOccurrence = $endDate->getTimeStamp();
2746
+                } else {
2747
+                    $lastOccurrence = $firstOccurrence;
2748
+                }
2749
+            } else {
2750
+                $it = new EventIterator($vEvents);
2751
+                $maxDate = new DateTime(self::MAX_DATE);
2752
+                $firstOccurrence = $it->getDtStart()->getTimestamp();
2753
+                if ($it->isInfinite()) {
2754
+                    $lastOccurrence = $maxDate->getTimestamp();
2755
+                } else {
2756
+                    $end = $it->getDtEnd();
2757
+                    while ($it->valid() && $end < $maxDate) {
2758
+                        $end = $it->getDtEnd();
2759
+                        $it->next();
2760
+                    }
2761
+                    $lastOccurrence = $end->getTimestamp();
2762
+                }
2763
+            }
2764
+        }
2765
+
2766
+        if ($component->CLASS) {
2767
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2768
+            switch ($component->CLASS->getValue()) {
2769
+                case 'PUBLIC':
2770
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2771
+                    break;
2772
+                case 'CONFIDENTIAL':
2773
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2774
+                    break;
2775
+            }
2776
+        }
2777
+        return [
2778
+            'etag' => md5($calendarData),
2779
+            'size' => strlen($calendarData),
2780
+            'componentType' => $componentType,
2781
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2782
+            'lastOccurence' => $lastOccurrence,
2783
+            'uid' => $uid,
2784
+            'classification' => $classification
2785
+        ];
2786
+    }
2787
+
2788
+    /**
2789
+     * @param $cardData
2790
+     * @return bool|string
2791
+     */
2792
+    private function readBlob($cardData) {
2793
+        if (is_resource($cardData)) {
2794
+            return stream_get_contents($cardData);
2795
+        }
2796
+
2797
+        return $cardData;
2798
+    }
2799
+
2800
+    /**
2801
+     * @param IShareable $shareable
2802
+     * @param array $add
2803
+     * @param array $remove
2804
+     */
2805
+    public function updateShares($shareable, $add, $remove) {
2806
+        $calendarId = $shareable->getResourceId();
2807
+        $calendarRow = $this->getCalendarById($calendarId);
2808
+        $oldShares = $this->getShares($calendarId);
2809
+
2810
+        $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2811
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2812
+            [
2813
+                'calendarId' => $calendarId,
2814
+                'calendarData' => $calendarRow,
2815
+                'shares' => $oldShares,
2816
+                'add' => $add,
2817
+                'remove' => $remove,
2818
+            ]));
2819
+        $this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2820
+
2821
+        $this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent((int)$calendarId, $calendarRow, $oldShares, $add, $remove));
2822
+    }
2823
+
2824
+    /**
2825
+     * @param int $resourceId
2826
+     * @return array
2827
+     */
2828
+    public function getShares($resourceId) {
2829
+        return $this->calendarSharingBackend->getShares($resourceId);
2830
+    }
2831
+
2832
+    /**
2833
+     * @param boolean $value
2834
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2835
+     * @return string|null
2836
+     */
2837
+    public function setPublishStatus($value, $calendar) {
2838
+        $calendarId = $calendar->getResourceId();
2839
+        $calendarData = $this->getCalendarById($calendarId);
2840
+        $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2841
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2842
+            [
2843
+                'calendarId' => $calendarId,
2844
+                'calendarData' => $calendarData,
2845
+                'public' => $value,
2846
+            ]));
2847
+
2848
+        $query = $this->db->getQueryBuilder();
2849
+        if ($value) {
2850
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2851
+            $query->insert('dav_shares')
2852
+                ->values([
2853
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2854
+                    'type' => $query->createNamedParameter('calendar'),
2855
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2856
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2857
+                    'publicuri' => $query->createNamedParameter($publicUri)
2858
+                ]);
2859
+            $query->executeStatement();
2860
+
2861
+            $this->dispatcher->dispatchTyped(new CalendarPublishedEvent((int)$calendarId, $calendarData, $publicUri));
2862
+            return $publicUri;
2863
+        }
2864
+        $query->delete('dav_shares')
2865
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2866
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2867
+        $query->executeStatement();
2868
+
2869
+        $this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent((int)$calendarId, $calendarData));
2870
+        return null;
2871
+    }
2872
+
2873
+    /**
2874
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2875
+     * @return mixed
2876
+     */
2877
+    public function getPublishStatus($calendar) {
2878
+        $query = $this->db->getQueryBuilder();
2879
+        $result = $query->select('publicuri')
2880
+            ->from('dav_shares')
2881
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2882
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2883
+            ->executeQuery();
2884
+
2885
+        $row = $result->fetch();
2886
+        $result->closeCursor();
2887
+        return $row ? reset($row) : false;
2888
+    }
2889
+
2890
+    /**
2891
+     * @param int $resourceId
2892
+     * @param array $acl
2893
+     * @return array
2894
+     */
2895
+    public function applyShareAcl($resourceId, $acl) {
2896
+        return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2897
+    }
2898
+
2899
+
2900
+
2901
+    /**
2902
+     * update properties table
2903
+     *
2904
+     * @param int $calendarId
2905
+     * @param string $objectUri
2906
+     * @param string $calendarData
2907
+     * @param int $calendarType
2908
+     */
2909
+    public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2910
+        $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2911
+
2912
+        try {
2913
+            $vCalendar = $this->readCalendarData($calendarData);
2914
+        } catch (\Exception $ex) {
2915
+            return;
2916
+        }
2917
+
2918
+        $this->purgeProperties($calendarId, $objectId);
2919
+
2920
+        $query = $this->db->getQueryBuilder();
2921
+        $query->insert($this->dbObjectPropertiesTable)
2922
+            ->values(
2923
+                [
2924
+                    'calendarid' => $query->createNamedParameter($calendarId),
2925
+                    'calendartype' => $query->createNamedParameter($calendarType),
2926
+                    'objectid' => $query->createNamedParameter($objectId),
2927
+                    'name' => $query->createParameter('name'),
2928
+                    'parameter' => $query->createParameter('parameter'),
2929
+                    'value' => $query->createParameter('value'),
2930
+                ]
2931
+            );
2932
+
2933
+        $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2934
+        foreach ($vCalendar->getComponents() as $component) {
2935
+            if (!in_array($component->name, $indexComponents)) {
2936
+                continue;
2937
+            }
2938
+
2939
+            foreach ($component->children() as $property) {
2940
+                if (in_array($property->name, self::$indexProperties)) {
2941
+                    $value = $property->getValue();
2942
+                    // is this a shitty db?
2943
+                    if (!$this->db->supports4ByteText()) {
2944
+                        $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2945
+                    }
2946
+                    $value = mb_strcut($value, 0, 254);
2947
+
2948
+                    $query->setParameter('name', $property->name);
2949
+                    $query->setParameter('parameter', null);
2950
+                    $query->setParameter('value', $value);
2951
+                    $query->executeStatement();
2952
+                }
2953
+
2954
+                if (array_key_exists($property->name, self::$indexParameters)) {
2955
+                    $parameters = $property->parameters();
2956
+                    $indexedParametersForProperty = self::$indexParameters[$property->name];
2957
+
2958
+                    foreach ($parameters as $key => $value) {
2959
+                        if (in_array($key, $indexedParametersForProperty)) {
2960
+                            // is this a shitty db?
2961
+                            if ($this->db->supports4ByteText()) {
2962
+                                $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2963
+                            }
2964
+
2965
+                            $query->setParameter('name', $property->name);
2966
+                            $query->setParameter('parameter', mb_strcut($key, 0, 254));
2967
+                            $query->setParameter('value', mb_strcut($value, 0, 254));
2968
+                            $query->executeStatement();
2969
+                        }
2970
+                    }
2971
+                }
2972
+            }
2973
+        }
2974
+    }
2975
+
2976
+    /**
2977
+     * deletes all birthday calendars
2978
+     */
2979
+    public function deleteAllBirthdayCalendars() {
2980
+        $query = $this->db->getQueryBuilder();
2981
+        $result = $query->select(['id'])->from('calendars')
2982
+            ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2983
+            ->executeQuery();
2984
+
2985
+        $ids = $result->fetchAll();
2986
+        foreach ($ids as $id) {
2987
+            $this->deleteCalendar(
2988
+                $id['id'],
2989
+                true // No data to keep in the trashbin, if the user re-enables then we regenerate
2990
+            );
2991
+        }
2992
+    }
2993
+
2994
+    /**
2995
+     * @param $subscriptionId
2996
+     */
2997
+    public function purgeAllCachedEventsForSubscription($subscriptionId) {
2998
+        $query = $this->db->getQueryBuilder();
2999
+        $query->select('uri')
3000
+            ->from('calendarobjects')
3001
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3002
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
3003
+        $stmt = $query->executeQuery();
3004
+
3005
+        $uris = [];
3006
+        foreach ($stmt->fetchAll() as $row) {
3007
+            $uris[] = $row['uri'];
3008
+        }
3009
+        $stmt->closeCursor();
3010
+
3011
+        $query = $this->db->getQueryBuilder();
3012
+        $query->delete('calendarobjects')
3013
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3014
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3015
+            ->executeStatement();
3016
+
3017
+        $query->delete('calendarchanges')
3018
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3019
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3020
+            ->executeStatement();
3021
+
3022
+        $query->delete($this->dbObjectPropertiesTable)
3023
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3024
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3025
+            ->executeStatement();
3026
+
3027
+        foreach ($uris as $uri) {
3028
+            $this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3029
+        }
3030
+    }
3031
+
3032
+    /**
3033
+     * Move a calendar from one user to another
3034
+     *
3035
+     * @param string $uriName
3036
+     * @param string $uriOrigin
3037
+     * @param string $uriDestination
3038
+     * @param string $newUriName (optional) the new uriName
3039
+     */
3040
+    public function moveCalendar($uriName, $uriOrigin, $uriDestination, $newUriName = null) {
3041
+        $query = $this->db->getQueryBuilder();
3042
+        $query->update('calendars')
3043
+            ->set('principaluri', $query->createNamedParameter($uriDestination))
3044
+            ->set('uri', $query->createNamedParameter($newUriName ?: $uriName))
3045
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
3046
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
3047
+            ->executeStatement();
3048
+    }
3049
+
3050
+    /**
3051
+     * read VCalendar data into a VCalendar object
3052
+     *
3053
+     * @param string $objectData
3054
+     * @return VCalendar
3055
+     */
3056
+    protected function readCalendarData($objectData) {
3057
+        return Reader::read($objectData);
3058
+    }
3059
+
3060
+    /**
3061
+     * delete all properties from a given calendar object
3062
+     *
3063
+     * @param int $calendarId
3064
+     * @param int $objectId
3065
+     */
3066
+    protected function purgeProperties($calendarId, $objectId) {
3067
+        $query = $this->db->getQueryBuilder();
3068
+        $query->delete($this->dbObjectPropertiesTable)
3069
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
3070
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
3071
+        $query->executeStatement();
3072
+    }
3073
+
3074
+    /**
3075
+     * get ID from a given calendar object
3076
+     *
3077
+     * @param int $calendarId
3078
+     * @param string $uri
3079
+     * @param int $calendarType
3080
+     * @return int
3081
+     */
3082
+    protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
3083
+        $query = $this->db->getQueryBuilder();
3084
+        $query->select('id')
3085
+            ->from('calendarobjects')
3086
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
3087
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
3088
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
3089
+
3090
+        $result = $query->executeQuery();
3091
+        $objectIds = $result->fetch();
3092
+        $result->closeCursor();
3093
+
3094
+        if (!isset($objectIds['id'])) {
3095
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
3096
+        }
3097
+
3098
+        return (int)$objectIds['id'];
3099
+    }
3100
+
3101
+    /**
3102
+     * return legacy endpoint principal name to new principal name
3103
+     *
3104
+     * @param $principalUri
3105
+     * @param $toV2
3106
+     * @return string
3107
+     */
3108
+    private function convertPrincipal($principalUri, $toV2) {
3109
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
3110
+            [, $name] = Uri\split($principalUri);
3111
+            if ($toV2 === true) {
3112
+                return "principals/users/$name";
3113
+            }
3114
+            return "principals/$name";
3115
+        }
3116
+        return $principalUri;
3117
+    }
3118
+
3119
+    /**
3120
+     * adds information about an owner to the calendar data
3121
+     *
3122
+     */
3123
+    private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
3124
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
3125
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
3126
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
3127
+            $uri = $calendarInfo[$ownerPrincipalKey];
3128
+        } else {
3129
+            $uri = $calendarInfo['principaluri'];
3130
+        }
3131
+
3132
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
3133
+        if (isset($principalInformation['{DAV:}displayname'])) {
3134
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
3135
+        }
3136
+        return $calendarInfo;
3137
+    }
3138
+
3139
+    private function addResourceTypeToCalendar(array $row, array $calendar): array {
3140
+        if (isset($row['deleted_at'])) {
3141
+            // Columns is set and not null -> this is a deleted calendar
3142
+            // we send a custom resourcetype to hide the deleted calendar
3143
+            // from ordinary DAV clients, but the Calendar app will know
3144
+            // how to handle this special resource.
3145
+            $calendar['{DAV:}resourcetype'] = new DAV\Xml\Property\ResourceType([
3146
+                '{DAV:}collection',
3147
+                sprintf('{%s}deleted-calendar', \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD),
3148
+            ]);
3149
+        }
3150
+        return $calendar;
3151
+    }
3152 3152
 }
Please login to merge, or discard this patch.
Spacing   +125 added lines, -125 removed lines patch added patch discarded remove patch
@@ -151,7 +151,7 @@  discard block
 block discarded – undo
151 151
 		'{urn:ietf:params:xml:ns:caldav}calendar-timezone' => 'timezone',
152 152
 		'{http://apple.com/ns/ical/}calendar-order' => 'calendarorder',
153 153
 		'{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor',
154
-		'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => 'deleted_at',
154
+		'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}deleted-at' => 'deleted_at',
155 155
 	];
156 156
 
157 157
 	/**
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
 		}
280 280
 
281 281
 		$result = $query->executeQuery();
282
-		$column = (int)$result->fetchOne();
282
+		$column = (int) $result->fetchOne();
283 283
 		$result->closeCursor();
284 284
 		return $column;
285 285
 	}
@@ -296,7 +296,7 @@  discard block
 block discarded – undo
296 296
 		$result = $qb->executeQuery();
297 297
 		$raw = $result->fetchAll();
298 298
 		$result->closeCursor();
299
-		return array_map(function ($row) {
299
+		return array_map(function($row) {
300 300
 			return [
301 301
 				'id' => (int) $row['id'],
302 302
 				'deleted_at' => (int) $row['deleted_at'],
@@ -359,18 +359,18 @@  discard block
 block discarded – undo
359 359
 			$row['principaluri'] = (string) $row['principaluri'];
360 360
 			$components = [];
361 361
 			if ($row['components']) {
362
-				$components = explode(',',$row['components']);
362
+				$components = explode(',', $row['components']);
363 363
 			}
364 364
 
365 365
 			$calendar = [
366 366
 				'id' => $row['id'],
367 367
 				'uri' => $row['uri'],
368 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),
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 374
 			];
375 375
 
376 376
 			foreach ($this->propertyMap as $xmlName => $dbName) {
@@ -411,7 +411,7 @@  discard block
 block discarded – undo
411 411
 
412 412
 		$result = $query->executeQuery();
413 413
 
414
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
414
+		$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
415 415
 		while ($row = $result->fetch()) {
416 416
 			$row['principaluri'] = (string) $row['principaluri'];
417 417
 			if ($row['principaluri'] === $principalUri) {
@@ -432,21 +432,21 @@  discard block
 block discarded – undo
432 432
 			}
433 433
 
434 434
 			[, $name] = Uri\split($row['principaluri']);
435
-			$uri = $row['uri'] . '_shared_by_' . $name;
436
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
435
+			$uri = $row['uri'].'_shared_by_'.$name;
436
+			$row['displayname'] = $row['displayname'].' ('.$this->getUserDisplayName($name).')';
437 437
 			$components = [];
438 438
 			if ($row['components']) {
439
-				$components = explode(',',$row['components']);
439
+				$components = explode(',', $row['components']);
440 440
 			}
441 441
 			$calendar = [
442 442
 				'id' => $row['id'],
443 443
 				'uri' => $uri,
444 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),
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 450
 				$readOnlyPropertyName => $readOnly,
451 451
 			];
452 452
 
@@ -488,16 +488,16 @@  discard block
 block discarded – undo
488 488
 			$row['principaluri'] = (string) $row['principaluri'];
489 489
 			$components = [];
490 490
 			if ($row['components']) {
491
-				$components = explode(',',$row['components']);
491
+				$components = explode(',', $row['components']);
492 492
 			}
493 493
 			$calendar = [
494 494
 				'id' => $row['id'],
495 495
 				'uri' => $row['uri'],
496 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'),
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 501
 			];
502 502
 			foreach ($this->propertyMap as $xmlName => $dbName) {
503 503
 				$calendar[$xmlName] = $row[$dbName];
@@ -558,22 +558,22 @@  discard block
 block discarded – undo
558 558
 		while ($row = $result->fetch()) {
559 559
 			$row['principaluri'] = (string) $row['principaluri'];
560 560
 			[, $name] = Uri\split($row['principaluri']);
561
-			$row['displayname'] = $row['displayname'] . "($name)";
561
+			$row['displayname'] = $row['displayname']."($name)";
562 562
 			$components = [];
563 563
 			if ($row['components']) {
564
-				$components = explode(',',$row['components']);
564
+				$components = explode(',', $row['components']);
565 565
 			}
566 566
 			$calendar = [
567 567
 				'id' => $row['id'],
568 568
 				'uri' => $row['publicuri'],
569 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,
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 577
 			];
578 578
 
579 579
 			foreach ($this->propertyMap as $xmlName => $dbName) {
@@ -621,27 +621,27 @@  discard block
 block discarded – undo
621 621
 		$result->closeCursor();
622 622
 
623 623
 		if ($row === false) {
624
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
624
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
625 625
 		}
626 626
 
627 627
 		$row['principaluri'] = (string) $row['principaluri'];
628 628
 		[, $name] = Uri\split($row['principaluri']);
629
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
629
+		$row['displayname'] = $row['displayname'].' '."($name)";
630 630
 		$components = [];
631 631
 		if ($row['components']) {
632
-			$components = explode(',',$row['components']);
632
+			$components = explode(',', $row['components']);
633 633
 		}
634 634
 		$calendar = [
635 635
 			'id' => $row['id'],
636 636
 			'uri' => $row['publicuri'],
637 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,
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 645
 		];
646 646
 
647 647
 		foreach ($this->propertyMap as $xmlName => $dbName) {
@@ -685,17 +685,17 @@  discard block
 block discarded – undo
685 685
 		$row['principaluri'] = (string) $row['principaluri'];
686 686
 		$components = [];
687 687
 		if ($row['components']) {
688
-			$components = explode(',',$row['components']);
688
+			$components = explode(',', $row['components']);
689 689
 		}
690 690
 
691 691
 		$calendar = [
692 692
 			'id' => $row['id'],
693 693
 			'uri' => $row['uri'],
694 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'),
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 699
 		];
700 700
 
701 701
 		foreach ($this->propertyMap as $xmlName => $dbName) {
@@ -737,17 +737,17 @@  discard block
 block discarded – undo
737 737
 		$row['principaluri'] = (string) $row['principaluri'];
738 738
 		$components = [];
739 739
 		if ($row['components']) {
740
-			$components = explode(',',$row['components']);
740
+			$components = explode(',', $row['components']);
741 741
 		}
742 742
 
743 743
 		$calendar = [
744 744
 			'id' => $row['id'],
745 745
 			'uri' => $row['uri'],
746 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'),
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 751
 		];
752 752
 
753 753
 		foreach ($this->propertyMap as $xmlName => $dbName) {
@@ -792,8 +792,8 @@  discard block
 block discarded – undo
792 792
 			'principaluri' => $row['principaluri'],
793 793
 			'source' => $row['source'],
794 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',
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 797
 		];
798 798
 
799 799
 		foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
@@ -830,16 +830,16 @@  discard block
 block discarded – undo
830 830
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
831 831
 		if (isset($properties[$sccs])) {
832 832
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
833
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
833
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
834 834
 			}
835
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
835
+			$values['components'] = implode(',', $properties[$sccs]->getValue());
836 836
 		} elseif (isset($properties['components'])) {
837 837
 			// Allow to provide components internally without having
838 838
 			// to create a SupportedCalendarComponentSet object
839 839
 			$values['components'] = $properties['components'];
840 840
 		}
841 841
 
842
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
842
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
843 843
 		if (isset($properties[$transp])) {
844 844
 			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
845 845
 		}
@@ -859,7 +859,7 @@  discard block
 block discarded – undo
859 859
 		$calendarId = $query->getLastInsertId();
860 860
 
861 861
 		$calendarData = $this->getCalendarById($calendarId);
862
-		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
862
+		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int) $calendarId, $calendarData));
863 863
 
864 864
 		return $calendarId;
865 865
 	}
@@ -882,13 +882,13 @@  discard block
 block discarded – undo
882 882
 	 */
883 883
 	public function updateCalendar($calendarId, PropPatch $propPatch) {
884 884
 		$supportedProperties = array_keys($this->propertyMap);
885
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
885
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
886 886
 
887
-		$propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
887
+		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
888 888
 			$newValues = [];
889 889
 			foreach ($mutations as $propertyName => $propertyValue) {
890 890
 				switch ($propertyName) {
891
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
891
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp':
892 892
 						$fieldName = 'transparent';
893 893
 						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
894 894
 						break;
@@ -910,7 +910,7 @@  discard block
 block discarded – undo
910 910
 
911 911
 			$calendarData = $this->getCalendarById($calendarId);
912 912
 			$shares = $this->getShares($calendarId);
913
-			$this->dispatcher->dispatchTyped(new CalendarUpdatedEvent((int)$calendarId, $calendarData, $shares, $mutations));
913
+			$this->dispatcher->dispatchTyped(new CalendarUpdatedEvent((int) $calendarId, $calendarData, $shares, $mutations));
914 914
 
915 915
 			return true;
916 916
 		});
@@ -960,7 +960,7 @@  discard block
 block discarded – undo
960 960
 
961 961
 			// Only dispatch if we actually deleted anything
962 962
 			if ($calendarData) {
963
-				$this->dispatcher->dispatchTyped(new CalendarDeletedEvent((int)$calendarId, $calendarData, $shares));
963
+				$this->dispatcher->dispatchTyped(new CalendarDeletedEvent((int) $calendarId, $calendarData, $shares));
964 964
 			}
965 965
 		} else {
966 966
 			$qbMarkCalendarDeleted = $this->db->getQueryBuilder();
@@ -973,7 +973,7 @@  discard block
 block discarded – undo
973 973
 			$shares = $this->getShares($calendarId);
974 974
 			if ($calendarData) {
975 975
 				$this->dispatcher->dispatchTyped(new CalendarMovedToTrashEvent(
976
-					(int)$calendarId,
976
+					(int) $calendarId,
977 977
 					$calendarData,
978 978
 					$shares
979 979
 				));
@@ -1057,11 +1057,11 @@  discard block
 block discarded – undo
1057 1057
 				'id' => $row['id'],
1058 1058
 				'uri' => $row['uri'],
1059 1059
 				'lastmodified' => $row['lastmodified'],
1060
-				'etag' => '"' . $row['etag'] . '"',
1060
+				'etag' => '"'.$row['etag'].'"',
1061 1061
 				'calendarid' => $row['calendarid'],
1062
-				'size' => (int)$row['size'],
1062
+				'size' => (int) $row['size'],
1063 1063
 				'component' => strtolower($row['componenttype']),
1064
-				'classification' => (int)$row['classification']
1064
+				'classification' => (int) $row['classification']
1065 1065
 			];
1066 1066
 		}
1067 1067
 		$stmt->closeCursor();
@@ -1084,13 +1084,13 @@  discard block
 block discarded – undo
1084 1084
 				'id' => $row['id'],
1085 1085
 				'uri' => $row['uri'],
1086 1086
 				'lastmodified' => $row['lastmodified'],
1087
-				'etag' => '"' . $row['etag'] . '"',
1087
+				'etag' => '"'.$row['etag'].'"',
1088 1088
 				'calendarid' => (int) $row['calendarid'],
1089 1089
 				'calendartype' => (int) $row['calendartype'],
1090 1090
 				'size' => (int) $row['size'],
1091 1091
 				'component' => strtolower($row['componenttype']),
1092 1092
 				'classification' => (int) $row['classification'],
1093
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'],
1093
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}deleted-at' => $row['deleted_at'],
1094 1094
 			];
1095 1095
 		}
1096 1096
 		$stmt->closeCursor();
@@ -1114,13 +1114,13 @@  discard block
 block discarded – undo
1114 1114
 				'id' => $row['id'],
1115 1115
 				'uri' => $row['uri'],
1116 1116
 				'lastmodified' => $row['lastmodified'],
1117
-				'etag' => '"' . $row['etag'] . '"',
1117
+				'etag' => '"'.$row['etag'].'"',
1118 1118
 				'calendarid' => $row['calendarid'],
1119 1119
 				'calendaruri' => $row['calendaruri'],
1120
-				'size' => (int)$row['size'],
1120
+				'size' => (int) $row['size'],
1121 1121
 				'component' => strtolower($row['componenttype']),
1122
-				'classification' => (int)$row['classification'],
1123
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'],
1122
+				'classification' => (int) $row['classification'],
1123
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}deleted-at' => $row['deleted_at'],
1124 1124
 			];
1125 1125
 		}
1126 1126
 		$stmt->closeCursor();
@@ -1164,12 +1164,12 @@  discard block
 block discarded – undo
1164 1164
 			'id' => $row['id'],
1165 1165
 			'uri' => $row['uri'],
1166 1166
 			'lastmodified' => $row['lastmodified'],
1167
-			'etag' => '"' . $row['etag'] . '"',
1167
+			'etag' => '"'.$row['etag'].'"',
1168 1168
 			'calendarid' => $row['calendarid'],
1169
-			'size' => (int)$row['size'],
1169
+			'size' => (int) $row['size'],
1170 1170
 			'calendardata' => $this->readBlob($row['calendardata']),
1171 1171
 			'component' => strtolower($row['componenttype']),
1172
-			'classification' => (int)$row['classification']
1172
+			'classification' => (int) $row['classification']
1173 1173
 		];
1174 1174
 	}
1175 1175
 
@@ -1211,12 +1211,12 @@  discard block
 block discarded – undo
1211 1211
 					'id' => $row['id'],
1212 1212
 					'uri' => $row['uri'],
1213 1213
 					'lastmodified' => $row['lastmodified'],
1214
-					'etag' => '"' . $row['etag'] . '"',
1214
+					'etag' => '"'.$row['etag'].'"',
1215 1215
 					'calendarid' => $row['calendarid'],
1216
-					'size' => (int)$row['size'],
1216
+					'size' => (int) $row['size'],
1217 1217
 					'calendardata' => $this->readBlob($row['calendardata']),
1218 1218
 					'component' => strtolower($row['componenttype']),
1219
-					'classification' => (int)$row['classification']
1219
+					'classification' => (int) $row['classification']
1220 1220
 				];
1221 1221
 			}
1222 1222
 			$result->closeCursor();
@@ -1303,11 +1303,11 @@  discard block
 block discarded – undo
1303 1303
 			$calendarRow = $this->getCalendarById($calendarId);
1304 1304
 			$shares = $this->getShares($calendarId);
1305 1305
 
1306
-			$this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent((int)$calendarId, $calendarRow, $shares, $objectRow));
1306
+			$this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent((int) $calendarId, $calendarRow, $shares, $objectRow));
1307 1307
 		} else {
1308 1308
 			$subscriptionRow = $this->getSubscriptionById($calendarId);
1309 1309
 
1310
-			$this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow));
1310
+			$this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent((int) $calendarId, $subscriptionRow, [], $objectRow));
1311 1311
 			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1312 1312
 				'\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1313 1313
 				[
@@ -1319,7 +1319,7 @@  discard block
 block discarded – undo
1319 1319
 			));
1320 1320
 		}
1321 1321
 
1322
-		return '"' . $extraData['etag'] . '"';
1322
+		return '"'.$extraData['etag'].'"';
1323 1323
 	}
1324 1324
 
1325 1325
 	/**
@@ -1368,11 +1368,11 @@  discard block
 block discarded – undo
1368 1368
 				$calendarRow = $this->getCalendarById($calendarId);
1369 1369
 				$shares = $this->getShares($calendarId);
1370 1370
 
1371
-				$this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent((int)$calendarId, $calendarRow, $shares, $objectRow));
1371
+				$this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent((int) $calendarId, $calendarRow, $shares, $objectRow));
1372 1372
 			} else {
1373 1373
 				$subscriptionRow = $this->getSubscriptionById($calendarId);
1374 1374
 
1375
-				$this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow));
1375
+				$this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent((int) $calendarId, $subscriptionRow, [], $objectRow));
1376 1376
 				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1377 1377
 					'\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1378 1378
 					[
@@ -1385,7 +1385,7 @@  discard block
 block discarded – undo
1385 1385
 			}
1386 1386
 		}
1387 1387
 
1388
-		return '"' . $extraData['etag'] . '"';
1388
+		return '"'.$extraData['etag'].'"';
1389 1389
 	}
1390 1390
 
1391 1391
 	/**
@@ -1434,11 +1434,11 @@  discard block
 block discarded – undo
1434 1434
 				$calendarRow = $this->getCalendarById($calendarId);
1435 1435
 				$shares = $this->getShares($calendarId);
1436 1436
 
1437
-				$this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent((int)$calendarId, $calendarRow, $shares, $data));
1437
+				$this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent((int) $calendarId, $calendarRow, $shares, $data));
1438 1438
 			} else {
1439 1439
 				$subscriptionRow = $this->getSubscriptionById($calendarId);
1440 1440
 
1441
-				$this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent((int)$calendarId, $subscriptionRow, [], $data));
1441
+				$this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent((int) $calendarId, $subscriptionRow, [], $data));
1442 1442
 				$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1443 1443
 					'\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1444 1444
 					[
@@ -1487,7 +1487,7 @@  discard block
 block discarded – undo
1487 1487
 			if ($calendarData !== null) {
1488 1488
 				$this->dispatcher->dispatchTyped(
1489 1489
 					new CalendarObjectMovedToTrashEvent(
1490
-						(int)$calendarId,
1490
+						(int) $calendarId,
1491 1491
 						$calendarData,
1492 1492
 						$this->getShares($calendarId),
1493 1493
 						$data
@@ -1802,7 +1802,7 @@  discard block
 block discarded – undo
1802 1802
 
1803 1803
 		$result = [];
1804 1804
 		while ($row = $stmt->fetch()) {
1805
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1805
+			$path = $uriMapper[$row['calendarid']].'/'.$row['uri'];
1806 1806
 			if (!in_array($path, $result)) {
1807 1807
 				$result[] = $path;
1808 1808
 			}
@@ -1850,8 +1850,8 @@  discard block
 block discarded – undo
1850 1850
 
1851 1851
 		if ($pattern !== '') {
1852 1852
 			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1853
-				$outerQuery->createNamedParameter('%' .
1854
-					$this->db->escapeLikeParameter($pattern) . '%')));
1853
+				$outerQuery->createNamedParameter('%'.
1854
+					$this->db->escapeLikeParameter($pattern).'%')));
1855 1855
 		}
1856 1856
 
1857 1857
 		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
@@ -1891,7 +1891,7 @@  discard block
 block discarded – undo
1891 1891
 		$result = $outerQuery->executeQuery();
1892 1892
 		$calendarObjects = $result->fetchAll();
1893 1893
 
1894
-		return array_map(function ($o) {
1894
+		return array_map(function($o) {
1895 1895
 			$calendarData = Reader::read($o['calendardata']);
1896 1896
 			$comps = $calendarData->getComponents();
1897 1897
 			$objects = [];
@@ -1909,10 +1909,10 @@  discard block
 block discarded – undo
1909 1909
 				'type' => $o['componenttype'],
1910 1910
 				'uid' => $o['uid'],
1911 1911
 				'uri' => $o['uri'],
1912
-				'objects' => array_map(function ($c) {
1912
+				'objects' => array_map(function($c) {
1913 1913
 					return $this->transformSearchData($c);
1914 1914
 				}, $objects),
1915
-				'timezones' => array_map(function ($c) {
1915
+				'timezones' => array_map(function($c) {
1916 1916
 					return $this->transformSearchData($c);
1917 1917
 				}, $timezones),
1918 1918
 			];
@@ -1928,7 +1928,7 @@  discard block
 block discarded – undo
1928 1928
 		/** @var Component[] $subComponents */
1929 1929
 		$subComponents = $comp->getComponents();
1930 1930
 		/** @var Property[] $properties */
1931
-		$properties = array_filter($comp->children(), function ($c) {
1931
+		$properties = array_filter($comp->children(), function($c) {
1932 1932
 			return $c instanceof Property;
1933 1933
 		});
1934 1934
 		$validationRules = $comp->getValidationRules();
@@ -2006,7 +2006,7 @@  discard block
 block discarded – undo
2006 2006
 		$subscriptions = $this->getSubscriptionsForUser($principalUri);
2007 2007
 		foreach ($calendars as $calendar) {
2008 2008
 			$calendarAnd = $calendarObjectIdQuery->expr()->andX();
2009
-			$calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])));
2009
+			$calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int) $calendar['id'])));
2010 2010
 			$calendarAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
2011 2011
 
2012 2012
 			// If it's shared, limit search to public events
@@ -2019,7 +2019,7 @@  discard block
 block discarded – undo
2019 2019
 		}
2020 2020
 		foreach ($subscriptions as $subscription) {
2021 2021
 			$subscriptionAnd = $calendarObjectIdQuery->expr()->andX();
2022
-			$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])));
2022
+			$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int) $subscription['id'])));
2023 2023
 			$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2024 2024
 
2025 2025
 			// If it's shared, limit search to public events
@@ -2065,7 +2065,7 @@  discard block
 block discarded – undo
2065 2065
 			if (!$escapePattern) {
2066 2066
 				$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
2067 2067
 			} else {
2068
-				$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
2068
+				$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%'.$this->db->escapeLikeParameter($pattern).'%')));
2069 2069
 			}
2070 2070
 		}
2071 2071
 
@@ -2079,7 +2079,7 @@  discard block
 block discarded – undo
2079 2079
 		$result = $calendarObjectIdQuery->executeQuery();
2080 2080
 		$matches = $result->fetchAll();
2081 2081
 		$result->closeCursor();
2082
-		$matches = array_map(static function (array $match):int {
2082
+		$matches = array_map(static function(array $match):int {
2083 2083
 			return (int) $match['objectid'];
2084 2084
 		}, $matches);
2085 2085
 
@@ -2092,9 +2092,9 @@  discard block
 block discarded – undo
2092 2092
 		$calendarObjects = $result->fetchAll();
2093 2093
 		$result->closeCursor();
2094 2094
 
2095
-		return array_map(function (array $array): array {
2096
-			$array['calendarid'] = (int)$array['calendarid'];
2097
-			$array['calendartype'] = (int)$array['calendartype'];
2095
+		return array_map(function(array $array): array {
2096
+			$array['calendarid'] = (int) $array['calendarid'];
2097
+			$array['calendartype'] = (int) $array['calendartype'];
2098 2098
 			$array['calendardata'] = $this->readBlob($array['calendardata']);
2099 2099
 
2100 2100
 			return $array;
@@ -2132,7 +2132,7 @@  discard block
 block discarded – undo
2132 2132
 		$row = $stmt->fetch();
2133 2133
 		$stmt->closeCursor();
2134 2134
 		if ($row) {
2135
-			return $row['calendaruri'] . '/' . $row['objecturi'];
2135
+			return $row['calendaruri'].'/'.$row['objecturi'];
2136 2136
 		}
2137 2137
 
2138 2138
 		return null;
@@ -2158,13 +2158,13 @@  discard block
 block discarded – undo
2158 2158
 			'id' => $row['id'],
2159 2159
 			'uri' => $row['uri'],
2160 2160
 			'lastmodified' => $row['lastmodified'],
2161
-			'etag' => '"' . $row['etag'] . '"',
2161
+			'etag' => '"'.$row['etag'].'"',
2162 2162
 			'calendarid' => $row['calendarid'],
2163 2163
 			'calendaruri' => $row['calendaruri'],
2164
-			'size' => (int)$row['size'],
2164
+			'size' => (int) $row['size'],
2165 2165
 			'calendardata' => $this->readBlob($row['calendardata']),
2166 2166
 			'component' => strtolower($row['componenttype']),
2167
-			'classification' => (int)$row['classification'],
2167
+			'classification' => (int) $row['classification'],
2168 2168
 			'deleted_at' => isset($row['deleted_at']) ? ((int) $row['deleted_at']) : null,
2169 2169
 		];
2170 2170
 	}
@@ -2364,8 +2364,8 @@  discard block
 block discarded – undo
2364 2364
 				'source' => $row['source'],
2365 2365
 				'lastmodified' => $row['lastmodified'],
2366 2366
 
2367
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2368
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
2367
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2368
+				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ? $row['synctoken'] : '0',
2369 2369
 			];
2370 2370
 
2371 2371
 			foreach ($this->subscriptionPropertyMap as $xmlName => $dbName) {
@@ -2460,7 +2460,7 @@  discard block
 block discarded – undo
2460 2460
 		$supportedProperties = array_keys($this->subscriptionPropertyMap);
2461 2461
 		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
2462 2462
 
2463
-		$propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2463
+		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
2464 2464
 			$newValues = [];
2465 2465
 
2466 2466
 			foreach ($mutations as $propertyName => $propertyValue) {
@@ -2482,7 +2482,7 @@  discard block
 block discarded – undo
2482 2482
 				->executeStatement();
2483 2483
 
2484 2484
 			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2485
-			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2485
+			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int) $subscriptionId, $subscriptionRow, [], $mutations));
2486 2486
 			$this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2487 2487
 				'\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2488 2488
 				[
@@ -2533,7 +2533,7 @@  discard block
 block discarded – undo
2533 2533
 			->executeStatement();
2534 2534
 
2535 2535
 		if ($subscriptionRow) {
2536
-			$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2536
+			$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int) $subscriptionId, $subscriptionRow, []));
2537 2537
 		}
2538 2538
 	}
2539 2539
 
@@ -2571,8 +2571,8 @@  discard block
 block discarded – undo
2571 2571
 			'uri' => $row['uri'],
2572 2572
 			'calendardata' => $row['calendardata'],
2573 2573
 			'lastmodified' => $row['lastmodified'],
2574
-			'etag' => '"' . $row['etag'] . '"',
2575
-			'size' => (int)$row['size'],
2574
+			'etag' => '"'.$row['etag'].'"',
2575
+			'size' => (int) $row['size'],
2576 2576
 		];
2577 2577
 	}
2578 2578
 
@@ -2600,8 +2600,8 @@  discard block
 block discarded – undo
2600 2600
 				'calendardata' => $row['calendardata'],
2601 2601
 				'uri' => $row['uri'],
2602 2602
 				'lastmodified' => $row['lastmodified'],
2603
-				'etag' => '"' . $row['etag'] . '"',
2604
-				'size' => (int)$row['size'],
2603
+				'etag' => '"'.$row['etag'].'"',
2604
+				'size' => (int) $row['size'],
2605 2605
 			];
2606 2606
 		}
2607 2607
 
@@ -2655,14 +2655,14 @@  discard block
 block discarded – undo
2655 2655
 	 * @return void
2656 2656
 	 */
2657 2657
 	protected function addChange($calendarId, $objectUri, $operation, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2658
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2658
+		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars' : 'calendarsubscriptions';
2659 2659
 
2660 2660
 		$query = $this->db->getQueryBuilder();
2661 2661
 		$query->select('synctoken')
2662 2662
 			->from($table)
2663 2663
 			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2664 2664
 		$result = $query->executeQuery();
2665
-		$syncToken = (int)$result->fetchOne();
2665
+		$syncToken = (int) $result->fetchOne();
2666 2666
 		$result->closeCursor();
2667 2667
 
2668 2668
 		$query = $this->db->getQueryBuilder();
@@ -2719,7 +2719,7 @@  discard block
 block discarded – undo
2719 2719
 				// Track first component type and uid
2720 2720
 				if ($uid === null) {
2721 2721
 					$componentType = $component->name;
2722
-					$uid = (string)$component->UID;
2722
+					$uid = (string) $component->UID;
2723 2723
 				}
2724 2724
 			}
2725 2725
 		}
@@ -2818,7 +2818,7 @@  discard block
 block discarded – undo
2818 2818
 			]));
2819 2819
 		$this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2820 2820
 
2821
-		$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent((int)$calendarId, $calendarRow, $oldShares, $add, $remove));
2821
+		$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent((int) $calendarId, $calendarRow, $oldShares, $add, $remove));
2822 2822
 	}
2823 2823
 
2824 2824
 	/**
@@ -2858,7 +2858,7 @@  discard block
 block discarded – undo
2858 2858
 				]);
2859 2859
 			$query->executeStatement();
2860 2860
 
2861
-			$this->dispatcher->dispatchTyped(new CalendarPublishedEvent((int)$calendarId, $calendarData, $publicUri));
2861
+			$this->dispatcher->dispatchTyped(new CalendarPublishedEvent((int) $calendarId, $calendarData, $publicUri));
2862 2862
 			return $publicUri;
2863 2863
 		}
2864 2864
 		$query->delete('dav_shares')
@@ -2866,7 +2866,7 @@  discard block
 block discarded – undo
2866 2866
 			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2867 2867
 		$query->executeStatement();
2868 2868
 
2869
-		$this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent((int)$calendarId, $calendarData));
2869
+		$this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent((int) $calendarId, $calendarData));
2870 2870
 		return null;
2871 2871
 	}
2872 2872
 
@@ -3092,10 +3092,10 @@  discard block
 block discarded – undo
3092 3092
 		$result->closeCursor();
3093 3093
 
3094 3094
 		if (!isset($objectIds['id'])) {
3095
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
3095
+			throw new \InvalidArgumentException('Calendarobject does not exists: '.$uri);
3096 3096
 		}
3097 3097
 
3098
-		return (int)$objectIds['id'];
3098
+		return (int) $objectIds['id'];
3099 3099
 	}
3100 3100
 
3101 3101
 	/**
@@ -3121,8 +3121,8 @@  discard block
 block discarded – undo
3121 3121
 	 *
3122 3122
 	 */
3123 3123
 	private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
3124
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
3125
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
3124
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
3125
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
3126 3126
 		if (isset($calendarInfo[$ownerPrincipalKey])) {
3127 3127
 			$uri = $calendarInfo[$ownerPrincipalKey];
3128 3128
 		} else {
Please login to merge, or discard this patch.