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