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