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