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