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