Completed
Push — master ( d785bc...9001ae )
by
unknown
30:18
created
apps/dav/lib/Command/CreateCalendar.php 1 patch
Indentation   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -31,61 +31,61 @@
 block discarded – undo
31 31
 use Symfony\Component\Console\Output\OutputInterface;
32 32
 
33 33
 class CreateCalendar extends Command {
34
-	public function __construct(
35
-		protected IUserManager $userManager,
36
-		private IGroupManager $groupManager,
37
-		protected IDBConnection $dbConnection,
38
-	) {
39
-		parent::__construct();
40
-	}
34
+    public function __construct(
35
+        protected IUserManager $userManager,
36
+        private IGroupManager $groupManager,
37
+        protected IDBConnection $dbConnection,
38
+    ) {
39
+        parent::__construct();
40
+    }
41 41
 
42
-	protected function configure(): void {
43
-		$this
44
-			->setName('dav:create-calendar')
45
-			->setDescription('Create a dav calendar')
46
-			->addArgument('user',
47
-				InputArgument::REQUIRED,
48
-				'User for whom the calendar will be created')
49
-			->addArgument('name',
50
-				InputArgument::REQUIRED,
51
-				'Name of the calendar');
52
-	}
42
+    protected function configure(): void {
43
+        $this
44
+            ->setName('dav:create-calendar')
45
+            ->setDescription('Create a dav calendar')
46
+            ->addArgument('user',
47
+                InputArgument::REQUIRED,
48
+                'User for whom the calendar will be created')
49
+            ->addArgument('name',
50
+                InputArgument::REQUIRED,
51
+                'Name of the calendar');
52
+    }
53 53
 
54
-	protected function execute(InputInterface $input, OutputInterface $output): int {
55
-		$user = $input->getArgument('user');
56
-		if (!$this->userManager->userExists($user)) {
57
-			throw new \InvalidArgumentException("User <$user> in unknown.");
58
-		}
59
-		$principalBackend = new Principal(
60
-			$this->userManager,
61
-			$this->groupManager,
62
-			Server::get(IAccountManager::class),
63
-			Server::get(\OCP\Share\IManager::class),
64
-			Server::get(IUserSession::class),
65
-			Server::get(IAppManager::class),
66
-			Server::get(ProxyMapper::class),
67
-			Server::get(KnownUserService::class),
68
-			Server::get(IConfig::class),
69
-			\OC::$server->getL10NFactory(),
70
-		);
71
-		$random = Server::get(ISecureRandom::class);
72
-		$logger = Server::get(LoggerInterface::class);
73
-		$dispatcher = Server::get(IEventDispatcher::class);
74
-		$config = Server::get(IConfig::class);
75
-		$name = $input->getArgument('name');
76
-		$caldav = new CalDavBackend(
77
-			$this->dbConnection,
78
-			$principalBackend,
79
-			$this->userManager,
80
-			$random,
81
-			$logger,
82
-			$dispatcher,
83
-			$config,
84
-			Server::get(Backend::class),
85
-			Server::get(FederatedCalendarMapper::class),
86
-			Server::get(ICacheFactory::class),
87
-		);
88
-		$caldav->createCalendar("principals/users/$user", $name, []);
89
-		return self::SUCCESS;
90
-	}
54
+    protected function execute(InputInterface $input, OutputInterface $output): int {
55
+        $user = $input->getArgument('user');
56
+        if (!$this->userManager->userExists($user)) {
57
+            throw new \InvalidArgumentException("User <$user> in unknown.");
58
+        }
59
+        $principalBackend = new Principal(
60
+            $this->userManager,
61
+            $this->groupManager,
62
+            Server::get(IAccountManager::class),
63
+            Server::get(\OCP\Share\IManager::class),
64
+            Server::get(IUserSession::class),
65
+            Server::get(IAppManager::class),
66
+            Server::get(ProxyMapper::class),
67
+            Server::get(KnownUserService::class),
68
+            Server::get(IConfig::class),
69
+            \OC::$server->getL10NFactory(),
70
+        );
71
+        $random = Server::get(ISecureRandom::class);
72
+        $logger = Server::get(LoggerInterface::class);
73
+        $dispatcher = Server::get(IEventDispatcher::class);
74
+        $config = Server::get(IConfig::class);
75
+        $name = $input->getArgument('name');
76
+        $caldav = new CalDavBackend(
77
+            $this->dbConnection,
78
+            $principalBackend,
79
+            $this->userManager,
80
+            $random,
81
+            $logger,
82
+            $dispatcher,
83
+            $config,
84
+            Server::get(Backend::class),
85
+            Server::get(FederatedCalendarMapper::class),
86
+            Server::get(ICacheFactory::class),
87
+        );
88
+        $caldav->createCalendar("principals/users/$user", $name, []);
89
+        return self::SUCCESS;
90
+    }
91 91
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 2 patches
Indentation   +3665 added lines, -3665 removed lines patch added patch discarded remove patch
@@ -110,3669 +110,3669 @@
 block discarded – undo
110 110
  * }
111 111
  */
112 112
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
113
-	use TTransactional;
114
-
115
-	public const CALENDAR_TYPE_CALENDAR = 0;
116
-	public const CALENDAR_TYPE_SUBSCRIPTION = 1;
117
-	public const CALENDAR_TYPE_FEDERATED = 2;
118
-
119
-	public const PERSONAL_CALENDAR_URI = 'personal';
120
-	public const PERSONAL_CALENDAR_NAME = 'Personal';
121
-
122
-	public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
123
-	public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
124
-
125
-	/**
126
-	 * We need to specify a max date, because we need to stop *somewhere*
127
-	 *
128
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
129
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
130
-	 * in 2038-01-19 to avoid problems when the date is converted
131
-	 * to a unix timestamp.
132
-	 */
133
-	public const MAX_DATE = '2038-01-01';
134
-
135
-	public const ACCESS_PUBLIC = 4;
136
-	public const CLASSIFICATION_PUBLIC = 0;
137
-	public const CLASSIFICATION_PRIVATE = 1;
138
-	public const CLASSIFICATION_CONFIDENTIAL = 2;
139
-
140
-	/**
141
-	 * List of CalDAV properties, and how they map to database field names and their type
142
-	 * Add your own properties by simply adding on to this array.
143
-	 *
144
-	 * @var array
145
-	 * @psalm-var array<string, string[]>
146
-	 */
147
-	public array $propertyMap = [
148
-		'{DAV:}displayname' => ['displayname', 'string'],
149
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => ['description', 'string'],
150
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone' => ['timezone', 'string'],
151
-		'{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
152
-		'{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
153
-		'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => ['deleted_at', 'int'],
154
-	];
155
-
156
-	/**
157
-	 * List of subscription properties, and how they map to database field names.
158
-	 *
159
-	 * @var array
160
-	 */
161
-	public array $subscriptionPropertyMap = [
162
-		'{DAV:}displayname' => ['displayname', 'string'],
163
-		'{http://apple.com/ns/ical/}refreshrate' => ['refreshrate', 'string'],
164
-		'{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
165
-		'{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
166
-		'{http://calendarserver.org/ns/}subscribed-strip-todos' => ['striptodos', 'bool'],
167
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms' => ['stripalarms', 'string'],
168
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => ['stripattachments', 'string'],
169
-	];
170
-
171
-	/**
172
-	 * properties to index
173
-	 *
174
-	 * This list has to be kept in sync with ICalendarQuery::SEARCH_PROPERTY_*
175
-	 *
176
-	 * @see \OCP\Calendar\ICalendarQuery
177
-	 */
178
-	private const INDEXED_PROPERTIES = [
179
-		'CATEGORIES',
180
-		'COMMENT',
181
-		'DESCRIPTION',
182
-		'LOCATION',
183
-		'RESOURCES',
184
-		'STATUS',
185
-		'SUMMARY',
186
-		'ATTENDEE',
187
-		'CONTACT',
188
-		'ORGANIZER'
189
-	];
190
-
191
-	/** @var array parameters to index */
192
-	public static array $indexParameters = [
193
-		'ATTENDEE' => ['CN'],
194
-		'ORGANIZER' => ['CN'],
195
-	];
196
-
197
-	/**
198
-	 * @var string[] Map of uid => display name
199
-	 */
200
-	protected array $userDisplayNames;
201
-
202
-	private string $dbObjectsTable = 'calendarobjects';
203
-	private string $dbObjectPropertiesTable = 'calendarobjects_props';
204
-	private string $dbObjectInvitationsTable = 'calendar_invitations';
205
-	private array $cachedObjects = [];
206
-
207
-	private readonly ICache $publishStatusCache;
208
-
209
-	public function __construct(
210
-		private IDBConnection $db,
211
-		private Principal $principalBackend,
212
-		private IUserManager $userManager,
213
-		private ISecureRandom $random,
214
-		private LoggerInterface $logger,
215
-		private IEventDispatcher $dispatcher,
216
-		private IConfig $config,
217
-		private Sharing\Backend $calendarSharingBackend,
218
-		private FederatedCalendarMapper $federatedCalendarMapper,
219
-		ICacheFactory $cacheFactory,
220
-		private bool $legacyEndpoint = false,
221
-	) {
222
-		$this->publishStatusCache = $cacheFactory->createInMemory();
223
-	}
224
-
225
-	/**
226
-	 * Return the number of calendars owned by the given principal.
227
-	 *
228
-	 * Calendars shared with the given principal are not counted!
229
-	 *
230
-	 * By default, this excludes the automatically generated birthday calendar.
231
-	 */
232
-	public function getCalendarsForUserCount(string $principalUri, bool $excludeBirthday = true): int {
233
-		$principalUri = $this->convertPrincipal($principalUri, true);
234
-		$query = $this->db->getQueryBuilder();
235
-		$query->select($query->func()->count('*'))
236
-			->from('calendars');
237
-
238
-		if ($principalUri === '') {
239
-			$query->where($query->expr()->emptyString('principaluri'));
240
-		} else {
241
-			$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
242
-		}
243
-
244
-		if ($excludeBirthday) {
245
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
246
-		}
247
-
248
-		$result = $query->executeQuery();
249
-		$column = (int)$result->fetchOne();
250
-		$result->closeCursor();
251
-		return $column;
252
-	}
253
-
254
-	/**
255
-	 * Return the number of subscriptions for a principal
256
-	 */
257
-	public function getSubscriptionsForUserCount(string $principalUri): int {
258
-		$principalUri = $this->convertPrincipal($principalUri, true);
259
-		$query = $this->db->getQueryBuilder();
260
-		$query->select($query->func()->count('*'))
261
-			->from('calendarsubscriptions');
262
-
263
-		if ($principalUri === '') {
264
-			$query->where($query->expr()->emptyString('principaluri'));
265
-		} else {
266
-			$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
267
-		}
268
-
269
-		$result = $query->executeQuery();
270
-		$column = (int)$result->fetchOne();
271
-		$result->closeCursor();
272
-		return $column;
273
-	}
274
-
275
-	/**
276
-	 * @return array{id: int, deleted_at: int}[]
277
-	 */
278
-	public function getDeletedCalendars(int $deletedBefore): array {
279
-		$qb = $this->db->getQueryBuilder();
280
-		$qb->select(['id', 'deleted_at'])
281
-			->from('calendars')
282
-			->where($qb->expr()->isNotNull('deleted_at'))
283
-			->andWhere($qb->expr()->lt('deleted_at', $qb->createNamedParameter($deletedBefore)));
284
-		$result = $qb->executeQuery();
285
-		$calendars = [];
286
-		while (($row = $result->fetch()) !== false) {
287
-			$calendars[] = [
288
-				'id' => (int)$row['id'],
289
-				'deleted_at' => (int)$row['deleted_at'],
290
-			];
291
-		}
292
-		$result->closeCursor();
293
-		return $calendars;
294
-	}
295
-
296
-	/**
297
-	 * Returns a list of calendars for a principal.
298
-	 *
299
-	 * Every project is an array with the following keys:
300
-	 *  * id, a unique id that will be used by other functions to modify the
301
-	 *    calendar. This can be the same as the uri or a database key.
302
-	 *  * uri, which the basename of the uri with which the calendar is
303
-	 *    accessed.
304
-	 *  * principaluri. The owner of the calendar. Almost always the same as
305
-	 *    principalUri passed to this method.
306
-	 *
307
-	 * Furthermore it can contain webdav properties in clark notation. A very
308
-	 * common one is '{DAV:}displayname'.
309
-	 *
310
-	 * Many clients also require:
311
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
312
-	 * For this property, you can just return an instance of
313
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
314
-	 *
315
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
316
-	 * ACL will automatically be put in read-only mode.
317
-	 *
318
-	 * @param string $principalUri
319
-	 * @return array
320
-	 */
321
-	public function getCalendarsForUser($principalUri) {
322
-		return $this->atomic(function () use ($principalUri) {
323
-			$principalUriOriginal = $principalUri;
324
-			$principalUri = $this->convertPrincipal($principalUri, true);
325
-			$fields = array_column($this->propertyMap, 0);
326
-			$fields[] = 'id';
327
-			$fields[] = 'uri';
328
-			$fields[] = 'synctoken';
329
-			$fields[] = 'components';
330
-			$fields[] = 'principaluri';
331
-			$fields[] = 'transparent';
332
-
333
-			// Making fields a comma-delimited list
334
-			$query = $this->db->getQueryBuilder();
335
-			$query->select($fields)
336
-				->from('calendars')
337
-				->orderBy('calendarorder', 'ASC');
338
-
339
-			if ($principalUri === '') {
340
-				$query->where($query->expr()->emptyString('principaluri'));
341
-			} else {
342
-				$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
343
-			}
344
-
345
-			$result = $query->executeQuery();
346
-
347
-			$calendars = [];
348
-			while ($row = $result->fetch()) {
349
-				$row['principaluri'] = (string)$row['principaluri'];
350
-				$components = [];
351
-				if ($row['components']) {
352
-					$components = explode(',', $row['components']);
353
-				}
354
-
355
-				$calendar = [
356
-					'id' => $row['id'],
357
-					'uri' => $row['uri'],
358
-					'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
359
-					'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
360
-					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
361
-					'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
362
-					'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
363
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
364
-				];
365
-
366
-				$calendar = $this->rowToCalendar($row, $calendar);
367
-				$calendar = $this->addOwnerPrincipalToCalendar($calendar);
368
-				$calendar = $this->addResourceTypeToCalendar($row, $calendar);
369
-
370
-				if (!isset($calendars[$calendar['id']])) {
371
-					$calendars[$calendar['id']] = $calendar;
372
-				}
373
-			}
374
-			$result->closeCursor();
375
-
376
-			// query for shared calendars
377
-			$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
378
-			$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
379
-			$principals[] = $principalUri;
380
-
381
-			$fields = array_column($this->propertyMap, 0);
382
-			$fields = array_map(function (string $field) {
383
-				return 'a.' . $field;
384
-			}, $fields);
385
-			$fields[] = 'a.id';
386
-			$fields[] = 'a.uri';
387
-			$fields[] = 'a.synctoken';
388
-			$fields[] = 'a.components';
389
-			$fields[] = 'a.principaluri';
390
-			$fields[] = 'a.transparent';
391
-			$fields[] = 's.access';
392
-
393
-			$select = $this->db->getQueryBuilder();
394
-			$subSelect = $this->db->getQueryBuilder();
395
-
396
-			$subSelect->select('resourceid')
397
-				->from('dav_shares', 'd')
398
-				->where($subSelect->expr()->eq('d.access', $select->createNamedParameter(Backend::ACCESS_UNSHARED, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
399
-				->andWhere($subSelect->expr()->in('d.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY));
400
-
401
-			$select->select($fields)
402
-				->from('dav_shares', 's')
403
-				->join('s', 'calendars', 'a', $select->expr()->eq('s.resourceid', 'a.id', IQueryBuilder::PARAM_INT))
404
-				->where($select->expr()->in('s.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
405
-				->andWhere($select->expr()->eq('s.type', $select->createNamedParameter('calendar', IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR))
406
-				->andWhere($select->expr()->notIn('a.id', $select->createFunction($subSelect->getSQL()), IQueryBuilder::PARAM_INT_ARRAY));
407
-
408
-			$results = $select->executeQuery();
409
-
410
-			$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
411
-			while ($row = $results->fetch()) {
412
-				$row['principaluri'] = (string)$row['principaluri'];
413
-				if ($row['principaluri'] === $principalUri) {
414
-					continue;
415
-				}
416
-
417
-				$readOnly = (int)$row['access'] === Backend::ACCESS_READ;
418
-				if (isset($calendars[$row['id']])) {
419
-					if ($readOnly) {
420
-						// New share can not have more permissions than the old one.
421
-						continue;
422
-					}
423
-					if (isset($calendars[$row['id']][$readOnlyPropertyName])
424
-						&& $calendars[$row['id']][$readOnlyPropertyName] === 0) {
425
-						// Old share is already read-write, no more permissions can be gained
426
-						continue;
427
-					}
428
-				}
429
-
430
-				[, $name] = Uri\split($row['principaluri']);
431
-				$uri = $row['uri'] . '_shared_by_' . $name;
432
-				$row['displayname'] = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? ($name ?? '')) . ')';
433
-				$components = [];
434
-				if ($row['components']) {
435
-					$components = explode(',', $row['components']);
436
-				}
437
-				$calendar = [
438
-					'id' => $row['id'],
439
-					'uri' => $uri,
440
-					'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
441
-					'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
442
-					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
443
-					'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
444
-					'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
445
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
446
-					$readOnlyPropertyName => $readOnly,
447
-				];
448
-
449
-				$calendar = $this->rowToCalendar($row, $calendar);
450
-				$calendar = $this->addOwnerPrincipalToCalendar($calendar);
451
-				$calendar = $this->addResourceTypeToCalendar($row, $calendar);
452
-
453
-				$calendars[$calendar['id']] = $calendar;
454
-			}
455
-			$result->closeCursor();
456
-
457
-			return array_values($calendars);
458
-		}, $this->db);
459
-	}
460
-
461
-	/**
462
-	 * @param $principalUri
463
-	 * @return array
464
-	 */
465
-	public function getUsersOwnCalendars($principalUri) {
466
-		$principalUri = $this->convertPrincipal($principalUri, true);
467
-		$fields = array_column($this->propertyMap, 0);
468
-		$fields[] = 'id';
469
-		$fields[] = 'uri';
470
-		$fields[] = 'synctoken';
471
-		$fields[] = 'components';
472
-		$fields[] = 'principaluri';
473
-		$fields[] = 'transparent';
474
-		// Making fields a comma-delimited list
475
-		$query = $this->db->getQueryBuilder();
476
-		$query->select($fields)->from('calendars')
477
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
478
-			->orderBy('calendarorder', 'ASC');
479
-		$stmt = $query->executeQuery();
480
-		$calendars = [];
481
-		while ($row = $stmt->fetch()) {
482
-			$row['principaluri'] = (string)$row['principaluri'];
483
-			$components = [];
484
-			if ($row['components']) {
485
-				$components = explode(',', $row['components']);
486
-			}
487
-			$calendar = [
488
-				'id' => $row['id'],
489
-				'uri' => $row['uri'],
490
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
491
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
492
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
493
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
494
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
495
-			];
496
-
497
-			$calendar = $this->rowToCalendar($row, $calendar);
498
-			$calendar = $this->addOwnerPrincipalToCalendar($calendar);
499
-			$calendar = $this->addResourceTypeToCalendar($row, $calendar);
500
-
501
-			if (!isset($calendars[$calendar['id']])) {
502
-				$calendars[$calendar['id']] = $calendar;
503
-			}
504
-		}
505
-		$stmt->closeCursor();
506
-		return array_values($calendars);
507
-	}
508
-
509
-	/**
510
-	 * @return array
511
-	 */
512
-	public function getPublicCalendars() {
513
-		$fields = array_column($this->propertyMap, 0);
514
-		$fields[] = 'a.id';
515
-		$fields[] = 'a.uri';
516
-		$fields[] = 'a.synctoken';
517
-		$fields[] = 'a.components';
518
-		$fields[] = 'a.principaluri';
519
-		$fields[] = 'a.transparent';
520
-		$fields[] = 's.access';
521
-		$fields[] = 's.publicuri';
522
-		$calendars = [];
523
-		$query = $this->db->getQueryBuilder();
524
-		$result = $query->select($fields)
525
-			->from('dav_shares', 's')
526
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
527
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
528
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
529
-			->executeQuery();
530
-
531
-		while ($row = $result->fetch()) {
532
-			$row['principaluri'] = (string)$row['principaluri'];
533
-			[, $name] = Uri\split($row['principaluri']);
534
-			$row['displayname'] = $row['displayname'] . "($name)";
535
-			$components = [];
536
-			if ($row['components']) {
537
-				$components = explode(',', $row['components']);
538
-			}
539
-			$calendar = [
540
-				'id' => $row['id'],
541
-				'uri' => $row['publicuri'],
542
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
543
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
544
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
545
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
546
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
547
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
548
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => true,
549
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
550
-			];
551
-
552
-			$calendar = $this->rowToCalendar($row, $calendar);
553
-			$calendar = $this->addOwnerPrincipalToCalendar($calendar);
554
-			$calendar = $this->addResourceTypeToCalendar($row, $calendar);
555
-
556
-			if (!isset($calendars[$calendar['id']])) {
557
-				$calendars[$calendar['id']] = $calendar;
558
-			}
559
-		}
560
-		$result->closeCursor();
561
-
562
-		return array_values($calendars);
563
-	}
564
-
565
-	/**
566
-	 * @param string $uri
567
-	 * @return array
568
-	 * @throws NotFound
569
-	 */
570
-	public function getPublicCalendar($uri) {
571
-		$fields = array_column($this->propertyMap, 0);
572
-		$fields[] = 'a.id';
573
-		$fields[] = 'a.uri';
574
-		$fields[] = 'a.synctoken';
575
-		$fields[] = 'a.components';
576
-		$fields[] = 'a.principaluri';
577
-		$fields[] = 'a.transparent';
578
-		$fields[] = 's.access';
579
-		$fields[] = 's.publicuri';
580
-		$query = $this->db->getQueryBuilder();
581
-		$result = $query->select($fields)
582
-			->from('dav_shares', 's')
583
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
584
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
585
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
586
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
587
-			->executeQuery();
588
-
589
-		$row = $result->fetch();
590
-
591
-		$result->closeCursor();
592
-
593
-		if ($row === false) {
594
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
595
-		}
596
-
597
-		$row['principaluri'] = (string)$row['principaluri'];
598
-		[, $name] = Uri\split($row['principaluri']);
599
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
600
-		$components = [];
601
-		if ($row['components']) {
602
-			$components = explode(',', $row['components']);
603
-		}
604
-		$calendar = [
605
-			'id' => $row['id'],
606
-			'uri' => $row['publicuri'],
607
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
608
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
609
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
610
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
611
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
612
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
613
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => true,
614
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
615
-		];
616
-
617
-		$calendar = $this->rowToCalendar($row, $calendar);
618
-		$calendar = $this->addOwnerPrincipalToCalendar($calendar);
619
-		$calendar = $this->addResourceTypeToCalendar($row, $calendar);
620
-
621
-		return $calendar;
622
-	}
623
-
624
-	/**
625
-	 * @param string $principal
626
-	 * @param string $uri
627
-	 * @return array|null
628
-	 */
629
-	public function getCalendarByUri($principal, $uri) {
630
-		$fields = array_column($this->propertyMap, 0);
631
-		$fields[] = 'id';
632
-		$fields[] = 'uri';
633
-		$fields[] = 'synctoken';
634
-		$fields[] = 'components';
635
-		$fields[] = 'principaluri';
636
-		$fields[] = 'transparent';
637
-
638
-		// Making fields a comma-delimited list
639
-		$query = $this->db->getQueryBuilder();
640
-		$query->select($fields)->from('calendars')
641
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
642
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
643
-			->setMaxResults(1);
644
-		$stmt = $query->executeQuery();
645
-
646
-		$row = $stmt->fetch();
647
-		$stmt->closeCursor();
648
-		if ($row === false) {
649
-			return null;
650
-		}
651
-
652
-		$row['principaluri'] = (string)$row['principaluri'];
653
-		$components = [];
654
-		if ($row['components']) {
655
-			$components = explode(',', $row['components']);
656
-		}
657
-
658
-		$calendar = [
659
-			'id' => $row['id'],
660
-			'uri' => $row['uri'],
661
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
662
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
663
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
664
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
665
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
666
-		];
667
-
668
-		$calendar = $this->rowToCalendar($row, $calendar);
669
-		$calendar = $this->addOwnerPrincipalToCalendar($calendar);
670
-		$calendar = $this->addResourceTypeToCalendar($row, $calendar);
671
-
672
-		return $calendar;
673
-	}
674
-
675
-	/**
676
-	 * @psalm-return CalendarInfo|null
677
-	 * @return array|null
678
-	 */
679
-	public function getCalendarById(int $calendarId): ?array {
680
-		$fields = array_column($this->propertyMap, 0);
681
-		$fields[] = 'id';
682
-		$fields[] = 'uri';
683
-		$fields[] = 'synctoken';
684
-		$fields[] = 'components';
685
-		$fields[] = 'principaluri';
686
-		$fields[] = 'transparent';
687
-
688
-		// Making fields a comma-delimited list
689
-		$query = $this->db->getQueryBuilder();
690
-		$query->select($fields)->from('calendars')
691
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
692
-			->setMaxResults(1);
693
-		$stmt = $query->executeQuery();
694
-
695
-		$row = $stmt->fetch();
696
-		$stmt->closeCursor();
697
-		if ($row === false) {
698
-			return null;
699
-		}
700
-
701
-		$row['principaluri'] = (string)$row['principaluri'];
702
-		$components = [];
703
-		if ($row['components']) {
704
-			$components = explode(',', $row['components']);
705
-		}
706
-
707
-		$calendar = [
708
-			'id' => $row['id'],
709
-			'uri' => $row['uri'],
710
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
711
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
712
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?? 0,
713
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
714
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
715
-		];
716
-
717
-		$calendar = $this->rowToCalendar($row, $calendar);
718
-		$calendar = $this->addOwnerPrincipalToCalendar($calendar);
719
-		$calendar = $this->addResourceTypeToCalendar($row, $calendar);
720
-
721
-		return $calendar;
722
-	}
723
-
724
-	/**
725
-	 * @param $subscriptionId
726
-	 */
727
-	public function getSubscriptionById($subscriptionId) {
728
-		$fields = array_column($this->subscriptionPropertyMap, 0);
729
-		$fields[] = 'id';
730
-		$fields[] = 'uri';
731
-		$fields[] = 'source';
732
-		$fields[] = 'synctoken';
733
-		$fields[] = 'principaluri';
734
-		$fields[] = 'lastmodified';
735
-
736
-		$query = $this->db->getQueryBuilder();
737
-		$query->select($fields)
738
-			->from('calendarsubscriptions')
739
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
740
-			->orderBy('calendarorder', 'asc');
741
-		$stmt = $query->executeQuery();
742
-
743
-		$row = $stmt->fetch();
744
-		$stmt->closeCursor();
745
-		if ($row === false) {
746
-			return null;
747
-		}
748
-
749
-		$row['principaluri'] = (string)$row['principaluri'];
750
-		$subscription = [
751
-			'id' => $row['id'],
752
-			'uri' => $row['uri'],
753
-			'principaluri' => $row['principaluri'],
754
-			'source' => $row['source'],
755
-			'lastmodified' => $row['lastmodified'],
756
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
757
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
758
-		];
759
-
760
-		return $this->rowToSubscription($row, $subscription);
761
-	}
762
-
763
-	public function getSubscriptionByUri(string $principal, string $uri): ?array {
764
-		$fields = array_column($this->subscriptionPropertyMap, 0);
765
-		$fields[] = 'id';
766
-		$fields[] = 'uri';
767
-		$fields[] = 'source';
768
-		$fields[] = 'synctoken';
769
-		$fields[] = 'principaluri';
770
-		$fields[] = 'lastmodified';
771
-
772
-		$query = $this->db->getQueryBuilder();
773
-		$query->select($fields)
774
-			->from('calendarsubscriptions')
775
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
776
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
777
-			->setMaxResults(1);
778
-		$stmt = $query->executeQuery();
779
-
780
-		$row = $stmt->fetch();
781
-		$stmt->closeCursor();
782
-		if ($row === false) {
783
-			return null;
784
-		}
785
-
786
-		$row['principaluri'] = (string)$row['principaluri'];
787
-		$subscription = [
788
-			'id' => $row['id'],
789
-			'uri' => $row['uri'],
790
-			'principaluri' => $row['principaluri'],
791
-			'source' => $row['source'],
792
-			'lastmodified' => $row['lastmodified'],
793
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
794
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
795
-		];
796
-
797
-		return $this->rowToSubscription($row, $subscription);
798
-	}
799
-
800
-	/**
801
-	 * Creates a new calendar for a principal.
802
-	 *
803
-	 * If the creation was a success, an id must be returned that can be used to reference
804
-	 * this calendar in other methods, such as updateCalendar.
805
-	 *
806
-	 * @param string $principalUri
807
-	 * @param string $calendarUri
808
-	 * @param array $properties
809
-	 * @return int
810
-	 *
811
-	 * @throws CalendarException
812
-	 */
813
-	public function createCalendar($principalUri, $calendarUri, array $properties) {
814
-		if (strlen($calendarUri) > 255) {
815
-			throw new CalendarException('URI too long. Calendar not created');
816
-		}
817
-
818
-		$values = [
819
-			'principaluri' => $this->convertPrincipal($principalUri, true),
820
-			'uri' => $calendarUri,
821
-			'synctoken' => 1,
822
-			'transparent' => 0,
823
-			'components' => 'VEVENT,VTODO,VJOURNAL',
824
-			'displayname' => $calendarUri
825
-		];
826
-
827
-		// Default value
828
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
829
-		if (isset($properties[$sccs])) {
830
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
831
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
832
-			}
833
-			$values['components'] = implode(',', $properties[$sccs]->getValue());
834
-		} elseif (isset($properties['components'])) {
835
-			// Allow to provide components internally without having
836
-			// to create a SupportedCalendarComponentSet object
837
-			$values['components'] = $properties['components'];
838
-		}
839
-
840
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
841
-		if (isset($properties[$transp])) {
842
-			$values['transparent'] = (int)($properties[$transp]->getValue() === 'transparent');
843
-		}
844
-
845
-		foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
846
-			if (isset($properties[$xmlName])) {
847
-				$values[$dbName] = $properties[$xmlName];
848
-			}
849
-		}
850
-
851
-		[$calendarId, $calendarData] = $this->atomic(function () use ($values) {
852
-			$query = $this->db->getQueryBuilder();
853
-			$query->insert('calendars');
854
-			foreach ($values as $column => $value) {
855
-				$query->setValue($column, $query->createNamedParameter($value));
856
-			}
857
-			$query->executeStatement();
858
-			$calendarId = $query->getLastInsertId();
859
-
860
-			$calendarData = $this->getCalendarById($calendarId);
861
-			return [$calendarId, $calendarData];
862
-		}, $this->db);
863
-
864
-		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
865
-
866
-		return $calendarId;
867
-	}
868
-
869
-	/**
870
-	 * Updates properties for a calendar.
871
-	 *
872
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
873
-	 * To do the actual updates, you must tell this object which properties
874
-	 * you're going to process with the handle() method.
875
-	 *
876
-	 * Calling the handle method is like telling the PropPatch object "I
877
-	 * promise I can handle updating this property".
878
-	 *
879
-	 * Read the PropPatch documentation for more info and examples.
880
-	 *
881
-	 * @param mixed $calendarId
882
-	 * @param PropPatch $propPatch
883
-	 * @return void
884
-	 */
885
-	public function updateCalendar($calendarId, PropPatch $propPatch) {
886
-		$supportedProperties = array_keys($this->propertyMap);
887
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
888
-
889
-		$propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
890
-			$newValues = [];
891
-			foreach ($mutations as $propertyName => $propertyValue) {
892
-				switch ($propertyName) {
893
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
894
-						$fieldName = 'transparent';
895
-						$newValues[$fieldName] = (int)($propertyValue->getValue() === 'transparent');
896
-						break;
897
-					default:
898
-						$fieldName = $this->propertyMap[$propertyName][0];
899
-						$newValues[$fieldName] = $propertyValue;
900
-						break;
901
-				}
902
-			}
903
-			[$calendarData, $shares] = $this->atomic(function () use ($calendarId, $newValues) {
904
-				$query = $this->db->getQueryBuilder();
905
-				$query->update('calendars');
906
-				foreach ($newValues as $fieldName => $value) {
907
-					$query->set($fieldName, $query->createNamedParameter($value));
908
-				}
909
-				$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
910
-				$query->executeStatement();
911
-
912
-				$this->addChanges($calendarId, [''], 2);
913
-
914
-				$calendarData = $this->getCalendarById($calendarId);
915
-				$shares = $this->getShares($calendarId);
916
-				return [$calendarData, $shares];
917
-			}, $this->db);
918
-
919
-			$this->dispatcher->dispatchTyped(new CalendarUpdatedEvent($calendarId, $calendarData, $shares, $mutations));
920
-
921
-			return true;
922
-		});
923
-	}
924
-
925
-	/**
926
-	 * Delete a calendar and all it's objects
927
-	 *
928
-	 * @param mixed $calendarId
929
-	 * @return void
930
-	 */
931
-	public function deleteCalendar($calendarId, bool $forceDeletePermanently = false) {
932
-		$this->publishStatusCache->remove((string)$calendarId);
933
-
934
-		$this->atomic(function () use ($calendarId, $forceDeletePermanently): void {
935
-			// The calendar is deleted right away if this is either enforced by the caller
936
-			// or the special contacts birthday calendar or when the preference of an empty
937
-			// retention (0 seconds) is set, which signals a disabled trashbin.
938
-			$calendarData = $this->getCalendarById($calendarId);
939
-			$isBirthdayCalendar = isset($calendarData['uri']) && $calendarData['uri'] === BirthdayService::BIRTHDAY_CALENDAR_URI;
940
-			$trashbinDisabled = $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0';
941
-			if ($forceDeletePermanently || $isBirthdayCalendar || $trashbinDisabled) {
942
-				$calendarData = $this->getCalendarById($calendarId);
943
-				$shares = $this->getShares($calendarId);
944
-
945
-				$this->purgeCalendarInvitations($calendarId);
946
-
947
-				$qbDeleteCalendarObjectProps = $this->db->getQueryBuilder();
948
-				$qbDeleteCalendarObjectProps->delete($this->dbObjectPropertiesTable)
949
-					->where($qbDeleteCalendarObjectProps->expr()->eq('calendarid', $qbDeleteCalendarObjectProps->createNamedParameter($calendarId)))
950
-					->andWhere($qbDeleteCalendarObjectProps->expr()->eq('calendartype', $qbDeleteCalendarObjectProps->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
951
-					->executeStatement();
952
-
953
-				$qbDeleteCalendarObjects = $this->db->getQueryBuilder();
954
-				$qbDeleteCalendarObjects->delete('calendarobjects')
955
-					->where($qbDeleteCalendarObjects->expr()->eq('calendarid', $qbDeleteCalendarObjects->createNamedParameter($calendarId)))
956
-					->andWhere($qbDeleteCalendarObjects->expr()->eq('calendartype', $qbDeleteCalendarObjects->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
957
-					->executeStatement();
958
-
959
-				$qbDeleteCalendarChanges = $this->db->getQueryBuilder();
960
-				$qbDeleteCalendarChanges->delete('calendarchanges')
961
-					->where($qbDeleteCalendarChanges->expr()->eq('calendarid', $qbDeleteCalendarChanges->createNamedParameter($calendarId)))
962
-					->andWhere($qbDeleteCalendarChanges->expr()->eq('calendartype', $qbDeleteCalendarChanges->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
963
-					->executeStatement();
964
-
965
-				$this->calendarSharingBackend->deleteAllShares($calendarId);
966
-
967
-				$qbDeleteCalendar = $this->db->getQueryBuilder();
968
-				$qbDeleteCalendar->delete('calendars')
969
-					->where($qbDeleteCalendar->expr()->eq('id', $qbDeleteCalendar->createNamedParameter($calendarId)))
970
-					->executeStatement();
971
-
972
-				// Only dispatch if we actually deleted anything
973
-				if ($calendarData) {
974
-					$this->dispatcher->dispatchTyped(new CalendarDeletedEvent($calendarId, $calendarData, $shares));
975
-				}
976
-			} else {
977
-				$qbMarkCalendarDeleted = $this->db->getQueryBuilder();
978
-				$qbMarkCalendarDeleted->update('calendars')
979
-					->set('deleted_at', $qbMarkCalendarDeleted->createNamedParameter(time()))
980
-					->where($qbMarkCalendarDeleted->expr()->eq('id', $qbMarkCalendarDeleted->createNamedParameter($calendarId)))
981
-					->executeStatement();
982
-
983
-				$calendarData = $this->getCalendarById($calendarId);
984
-				$shares = $this->getShares($calendarId);
985
-				if ($calendarData) {
986
-					$this->dispatcher->dispatchTyped(new CalendarMovedToTrashEvent(
987
-						$calendarId,
988
-						$calendarData,
989
-						$shares
990
-					));
991
-				}
992
-			}
993
-		}, $this->db);
994
-	}
995
-
996
-	public function restoreCalendar(int $id): void {
997
-		$this->atomic(function () use ($id): void {
998
-			$qb = $this->db->getQueryBuilder();
999
-			$update = $qb->update('calendars')
1000
-				->set('deleted_at', $qb->createNamedParameter(null))
1001
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1002
-			$update->executeStatement();
1003
-
1004
-			$calendarData = $this->getCalendarById($id);
1005
-			$shares = $this->getShares($id);
1006
-			if ($calendarData === null) {
1007
-				throw new RuntimeException('Calendar data that was just written can\'t be read back. Check your database configuration.');
1008
-			}
1009
-			$this->dispatcher->dispatchTyped(new CalendarRestoredEvent(
1010
-				$id,
1011
-				$calendarData,
1012
-				$shares
1013
-			));
1014
-		}, $this->db);
1015
-	}
1016
-
1017
-	/**
1018
-	 * Returns all calendar entries as a stream of data
1019
-	 *
1020
-	 * @since 32.0.0
1021
-	 *
1022
-	 * @return Generator<array>
1023
-	 */
1024
-	public function exportCalendar(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR, ?CalendarExportOptions $options = null): Generator {
1025
-		// extract options
1026
-		$rangeStart = $options?->getRangeStart();
1027
-		$rangeCount = $options?->getRangeCount();
1028
-		// construct query
1029
-		$qb = $this->db->getQueryBuilder();
1030
-		$qb->select('*')
1031
-			->from('calendarobjects')
1032
-			->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1033
-			->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1034
-			->andWhere($qb->expr()->isNull('deleted_at'));
1035
-		if ($rangeStart !== null) {
1036
-			$qb->andWhere($qb->expr()->gt('uid', $qb->createNamedParameter($rangeStart)));
1037
-		}
1038
-		if ($rangeCount !== null) {
1039
-			$qb->setMaxResults($rangeCount);
1040
-		}
1041
-		if ($rangeStart !== null || $rangeCount !== null) {
1042
-			$qb->orderBy('uid', 'ASC');
1043
-		}
1044
-		$rs = $qb->executeQuery();
1045
-		// iterate through results
1046
-		try {
1047
-			while (($row = $rs->fetch()) !== false) {
1048
-				yield $row;
1049
-			}
1050
-		} finally {
1051
-			$rs->closeCursor();
1052
-		}
1053
-	}
1054
-
1055
-	/**
1056
-	 * Returns all calendar objects with limited metadata for a calendar
1057
-	 *
1058
-	 * Every item contains an array with the following keys:
1059
-	 *   * id - the table row id
1060
-	 *   * etag - An arbitrary string
1061
-	 *   * uri - a unique key which will be used to construct the uri. This can
1062
-	 *     be any arbitrary string.
1063
-	 *   * calendardata - The iCalendar-compatible calendar data
1064
-	 *
1065
-	 * @param mixed $calendarId
1066
-	 * @param int $calendarType
1067
-	 * @return array
1068
-	 */
1069
-	public function getLimitedCalendarObjects(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1070
-		$query = $this->db->getQueryBuilder();
1071
-		$query->select(['id','uid', 'etag', 'uri', 'calendardata'])
1072
-			->from('calendarobjects')
1073
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1074
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1075
-			->andWhere($query->expr()->isNull('deleted_at'));
1076
-		$stmt = $query->executeQuery();
1077
-
1078
-		$result = [];
1079
-		while (($row = $stmt->fetch()) !== false) {
1080
-			$result[$row['uid']] = [
1081
-				'id' => $row['id'],
1082
-				'etag' => $row['etag'],
1083
-				'uri' => $row['uri'],
1084
-				'calendardata' => $row['calendardata'],
1085
-			];
1086
-		}
1087
-		$stmt->closeCursor();
1088
-
1089
-		return $result;
1090
-	}
1091
-
1092
-	/**
1093
-	 * Delete all of an user's shares
1094
-	 *
1095
-	 * @param string $principaluri
1096
-	 * @return void
1097
-	 */
1098
-	public function deleteAllSharesByUser($principaluri) {
1099
-		$this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
1100
-	}
1101
-
1102
-	/**
1103
-	 * Returns all calendar objects within a calendar.
1104
-	 *
1105
-	 * Every item contains an array with the following keys:
1106
-	 *   * calendardata - The iCalendar-compatible calendar data
1107
-	 *   * uri - a unique key which will be used to construct the uri. This can
1108
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
1109
-	 *     good idea. This is only the basename, or filename, not the full
1110
-	 *     path.
1111
-	 *   * lastmodified - a timestamp of the last modification time
1112
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
1113
-	 *   '"abcdef"')
1114
-	 *   * size - The size of the calendar objects, in bytes.
1115
-	 *   * component - optional, a string containing the type of object, such
1116
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
1117
-	 *     the Content-Type header.
1118
-	 *
1119
-	 * Note that the etag is optional, but it's highly encouraged to return for
1120
-	 * speed reasons.
1121
-	 *
1122
-	 * The calendardata is also optional. If it's not returned
1123
-	 * 'getCalendarObject' will be called later, which *is* expected to return
1124
-	 * calendardata.
1125
-	 *
1126
-	 * If neither etag or size are specified, the calendardata will be
1127
-	 * used/fetched to determine these numbers. If both are specified the
1128
-	 * amount of times this is needed is reduced by a great degree.
1129
-	 *
1130
-	 * @param mixed $calendarId
1131
-	 * @param int $calendarType
1132
-	 * @return array
1133
-	 */
1134
-	public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1135
-		$query = $this->db->getQueryBuilder();
1136
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
1137
-			->from('calendarobjects')
1138
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1139
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1140
-			->andWhere($query->expr()->isNull('deleted_at'));
1141
-		$stmt = $query->executeQuery();
1142
-
1143
-		$result = [];
1144
-		while (($row = $stmt->fetch()) !== false) {
1145
-			$result[] = [
1146
-				'id' => $row['id'],
1147
-				'uri' => $row['uri'],
1148
-				'lastmodified' => $row['lastmodified'],
1149
-				'etag' => '"' . $row['etag'] . '"',
1150
-				'calendarid' => $row['calendarid'],
1151
-				'size' => (int)$row['size'],
1152
-				'component' => strtolower($row['componenttype']),
1153
-				'classification' => (int)$row['classification']
1154
-			];
1155
-		}
1156
-		$stmt->closeCursor();
1157
-
1158
-		return $result;
1159
-	}
1160
-
1161
-	public function getDeletedCalendarObjects(int $deletedBefore): array {
1162
-		$query = $this->db->getQueryBuilder();
1163
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.calendartype', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1164
-			->from('calendarobjects', 'co')
1165
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1166
-			->where($query->expr()->isNotNull('co.deleted_at'))
1167
-			->andWhere($query->expr()->lt('co.deleted_at', $query->createNamedParameter($deletedBefore)));
1168
-		$stmt = $query->executeQuery();
1169
-
1170
-		$result = [];
1171
-		while (($row = $stmt->fetch()) !== false) {
1172
-			$result[] = [
1173
-				'id' => $row['id'],
1174
-				'uri' => $row['uri'],
1175
-				'lastmodified' => $row['lastmodified'],
1176
-				'etag' => '"' . $row['etag'] . '"',
1177
-				'calendarid' => (int)$row['calendarid'],
1178
-				'calendartype' => (int)$row['calendartype'],
1179
-				'size' => (int)$row['size'],
1180
-				'component' => strtolower($row['componenttype']),
1181
-				'classification' => (int)$row['classification'],
1182
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1183
-			];
1184
-		}
1185
-		$stmt->closeCursor();
1186
-
1187
-		return $result;
1188
-	}
1189
-
1190
-	/**
1191
-	 * Return all deleted calendar objects by the given principal that are not
1192
-	 * in deleted calendars.
1193
-	 *
1194
-	 * @param string $principalUri
1195
-	 * @return array
1196
-	 * @throws Exception
1197
-	 */
1198
-	public function getDeletedCalendarObjectsByPrincipal(string $principalUri): array {
1199
-		$query = $this->db->getQueryBuilder();
1200
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1201
-			->selectAlias('c.uri', 'calendaruri')
1202
-			->from('calendarobjects', 'co')
1203
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1204
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1205
-			->andWhere($query->expr()->isNotNull('co.deleted_at'))
1206
-			->andWhere($query->expr()->isNull('c.deleted_at'));
1207
-		$stmt = $query->executeQuery();
1208
-
1209
-		$result = [];
1210
-		while ($row = $stmt->fetch()) {
1211
-			$result[] = [
1212
-				'id' => $row['id'],
1213
-				'uri' => $row['uri'],
1214
-				'lastmodified' => $row['lastmodified'],
1215
-				'etag' => '"' . $row['etag'] . '"',
1216
-				'calendarid' => $row['calendarid'],
1217
-				'calendaruri' => $row['calendaruri'],
1218
-				'size' => (int)$row['size'],
1219
-				'component' => strtolower($row['componenttype']),
1220
-				'classification' => (int)$row['classification'],
1221
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1222
-			];
1223
-		}
1224
-		$stmt->closeCursor();
1225
-
1226
-		return $result;
1227
-	}
1228
-
1229
-	/**
1230
-	 * Returns information from a single calendar object, based on it's object
1231
-	 * uri.
1232
-	 *
1233
-	 * The object uri is only the basename, or filename and not a full path.
1234
-	 *
1235
-	 * The returned array must have the same keys as getCalendarObjects. The
1236
-	 * 'calendardata' object is required here though, while it's not required
1237
-	 * for getCalendarObjects.
1238
-	 *
1239
-	 * This method must return null if the object did not exist.
1240
-	 *
1241
-	 * @param mixed $calendarId
1242
-	 * @param string $objectUri
1243
-	 * @param int $calendarType
1244
-	 * @return array|null
1245
-	 */
1246
-	public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1247
-		$key = $calendarId . '::' . $objectUri . '::' . $calendarType;
1248
-		if (isset($this->cachedObjects[$key])) {
1249
-			return $this->cachedObjects[$key];
1250
-		}
1251
-		$query = $this->db->getQueryBuilder();
1252
-		$query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1253
-			->from('calendarobjects')
1254
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1255
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1256
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1257
-		$stmt = $query->executeQuery();
1258
-		$row = $stmt->fetch();
1259
-		$stmt->closeCursor();
1260
-
1261
-		if (!$row) {
1262
-			return null;
1263
-		}
1264
-
1265
-		$object = $this->rowToCalendarObject($row);
1266
-		$this->cachedObjects[$key] = $object;
1267
-		return $object;
1268
-	}
1269
-
1270
-	private function rowToCalendarObject(array $row): array {
1271
-		return [
1272
-			'id' => $row['id'],
1273
-			'uri' => $row['uri'],
1274
-			'uid' => $row['uid'],
1275
-			'lastmodified' => $row['lastmodified'],
1276
-			'etag' => '"' . $row['etag'] . '"',
1277
-			'calendarid' => $row['calendarid'],
1278
-			'size' => (int)$row['size'],
1279
-			'calendardata' => $this->readBlob($row['calendardata']),
1280
-			'component' => strtolower($row['componenttype']),
1281
-			'classification' => (int)$row['classification'],
1282
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1283
-		];
1284
-	}
1285
-
1286
-	/**
1287
-	 * Returns a list of calendar objects.
1288
-	 *
1289
-	 * This method should work identical to getCalendarObject, but instead
1290
-	 * return all the calendar objects in the list as an array.
1291
-	 *
1292
-	 * If the backend supports this, it may allow for some speed-ups.
1293
-	 *
1294
-	 * @param mixed $calendarId
1295
-	 * @param string[] $uris
1296
-	 * @param int $calendarType
1297
-	 * @return array
1298
-	 */
1299
-	public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1300
-		if (empty($uris)) {
1301
-			return [];
1302
-		}
1303
-
1304
-		$chunks = array_chunk($uris, 100);
1305
-		$objects = [];
1306
-
1307
-		$query = $this->db->getQueryBuilder();
1308
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1309
-			->from('calendarobjects')
1310
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1311
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1312
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1313
-			->andWhere($query->expr()->isNull('deleted_at'));
1314
-
1315
-		foreach ($chunks as $uris) {
1316
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1317
-			$result = $query->executeQuery();
1318
-
1319
-			while ($row = $result->fetch()) {
1320
-				$objects[] = [
1321
-					'id' => $row['id'],
1322
-					'uri' => $row['uri'],
1323
-					'lastmodified' => $row['lastmodified'],
1324
-					'etag' => '"' . $row['etag'] . '"',
1325
-					'calendarid' => $row['calendarid'],
1326
-					'size' => (int)$row['size'],
1327
-					'calendardata' => $this->readBlob($row['calendardata']),
1328
-					'component' => strtolower($row['componenttype']),
1329
-					'classification' => (int)$row['classification']
1330
-				];
1331
-			}
1332
-			$result->closeCursor();
1333
-		}
1334
-
1335
-		return $objects;
1336
-	}
1337
-
1338
-	/**
1339
-	 * Creates a new calendar object.
1340
-	 *
1341
-	 * The object uri is only the basename, or filename and not a full path.
1342
-	 *
1343
-	 * It is possible return an etag from this function, which will be used in
1344
-	 * the response to this PUT request. Note that the ETag must be surrounded
1345
-	 * by double-quotes.
1346
-	 *
1347
-	 * However, you should only really return this ETag if you don't mangle the
1348
-	 * calendar-data. If the result of a subsequent GET to this object is not
1349
-	 * the exact same as this request body, you should omit the ETag.
1350
-	 *
1351
-	 * @param mixed $calendarId
1352
-	 * @param string $objectUri
1353
-	 * @param string $calendarData
1354
-	 * @param int $calendarType
1355
-	 * @return string
1356
-	 */
1357
-	public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1358
-		$this->cachedObjects = [];
1359
-		$extraData = $this->getDenormalizedData($calendarData);
1360
-
1361
-		return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1362
-			// Try to detect duplicates
1363
-			$qb = $this->db->getQueryBuilder();
1364
-			$qb->select($qb->func()->count('*'))
1365
-				->from('calendarobjects')
1366
-				->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1367
-				->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($extraData['uid'])))
1368
-				->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1369
-				->andWhere($qb->expr()->isNull('deleted_at'));
1370
-			$result = $qb->executeQuery();
1371
-			$count = (int)$result->fetchOne();
1372
-			$result->closeCursor();
1373
-
1374
-			if ($count !== 0) {
1375
-				throw new BadRequest('Calendar object with uid already exists in this calendar collection.');
1376
-			}
1377
-			// For a more specific error message we also try to explicitly look up the UID but as a deleted entry
1378
-			$qbDel = $this->db->getQueryBuilder();
1379
-			$qbDel->select('*')
1380
-				->from('calendarobjects')
1381
-				->where($qbDel->expr()->eq('calendarid', $qbDel->createNamedParameter($calendarId)))
1382
-				->andWhere($qbDel->expr()->eq('uid', $qbDel->createNamedParameter($extraData['uid'])))
1383
-				->andWhere($qbDel->expr()->eq('calendartype', $qbDel->createNamedParameter($calendarType)))
1384
-				->andWhere($qbDel->expr()->isNotNull('deleted_at'));
1385
-			$result = $qbDel->executeQuery();
1386
-			$found = $result->fetch();
1387
-			$result->closeCursor();
1388
-			if ($found !== false) {
1389
-				// the object existed previously but has been deleted
1390
-				// remove the trashbin entry and continue as if it was a new object
1391
-				$this->deleteCalendarObject($calendarId, $found['uri']);
1392
-			}
1393
-
1394
-			$query = $this->db->getQueryBuilder();
1395
-			$query->insert('calendarobjects')
1396
-				->values([
1397
-					'calendarid' => $query->createNamedParameter($calendarId),
1398
-					'uri' => $query->createNamedParameter($objectUri),
1399
-					'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1400
-					'lastmodified' => $query->createNamedParameter(time()),
1401
-					'etag' => $query->createNamedParameter($extraData['etag']),
1402
-					'size' => $query->createNamedParameter($extraData['size']),
1403
-					'componenttype' => $query->createNamedParameter($extraData['componentType']),
1404
-					'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1405
-					'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1406
-					'classification' => $query->createNamedParameter($extraData['classification']),
1407
-					'uid' => $query->createNamedParameter($extraData['uid']),
1408
-					'calendartype' => $query->createNamedParameter($calendarType),
1409
-				])
1410
-				->executeStatement();
1411
-
1412
-			$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1413
-			$this->addChanges($calendarId, [$objectUri], 1, $calendarType);
1414
-
1415
-			$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1416
-			assert($objectRow !== null);
1417
-
1418
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1419
-				$calendarRow = $this->getCalendarById($calendarId);
1420
-				$shares = $this->getShares($calendarId);
1421
-
1422
-				$this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1423
-			} elseif ($calendarType === self::CALENDAR_TYPE_SUBSCRIPTION) {
1424
-				$subscriptionRow = $this->getSubscriptionById($calendarId);
1425
-
1426
-				$this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1427
-			} elseif ($calendarType === self::CALENDAR_TYPE_FEDERATED) {
1428
-				// TODO: implement custom event for federated calendars
1429
-			}
1430
-
1431
-			return '"' . $extraData['etag'] . '"';
1432
-		}, $this->db);
1433
-	}
1434
-
1435
-	/**
1436
-	 * Updates an existing calendarobject, based on it's uri.
1437
-	 *
1438
-	 * The object uri is only the basename, or filename and not a full path.
1439
-	 *
1440
-	 * It is possible return an etag from this function, which will be used in
1441
-	 * the response to this PUT request. Note that the ETag must be surrounded
1442
-	 * by double-quotes.
1443
-	 *
1444
-	 * However, you should only really return this ETag if you don't mangle the
1445
-	 * calendar-data. If the result of a subsequent GET to this object is not
1446
-	 * the exact same as this request body, you should omit the ETag.
1447
-	 *
1448
-	 * @param mixed $calendarId
1449
-	 * @param string $objectUri
1450
-	 * @param string $calendarData
1451
-	 * @param int $calendarType
1452
-	 * @return string
1453
-	 */
1454
-	public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1455
-		$this->cachedObjects = [];
1456
-		$extraData = $this->getDenormalizedData($calendarData);
1457
-
1458
-		return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1459
-			$query = $this->db->getQueryBuilder();
1460
-			$query->update('calendarobjects')
1461
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1462
-				->set('lastmodified', $query->createNamedParameter(time()))
1463
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1464
-				->set('size', $query->createNamedParameter($extraData['size']))
1465
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1466
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1467
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1468
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1469
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1470
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1471
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1472
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1473
-				->executeStatement();
1474
-
1475
-			$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1476
-			$this->addChanges($calendarId, [$objectUri], 2, $calendarType);
1477
-
1478
-			$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1479
-			if (is_array($objectRow)) {
1480
-				if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1481
-					$calendarRow = $this->getCalendarById($calendarId);
1482
-					$shares = $this->getShares($calendarId);
1483
-
1484
-					$this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1485
-				} elseif ($calendarType === self::CALENDAR_TYPE_SUBSCRIPTION) {
1486
-					$subscriptionRow = $this->getSubscriptionById($calendarId);
1487
-
1488
-					$this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1489
-				} elseif ($calendarType === self::CALENDAR_TYPE_FEDERATED) {
1490
-					// TODO: implement custom event for federated calendars
1491
-				}
1492
-			}
1493
-
1494
-			return '"' . $extraData['etag'] . '"';
1495
-		}, $this->db);
1496
-	}
1497
-
1498
-	/**
1499
-	 * Moves a calendar object from calendar to calendar.
1500
-	 *
1501
-	 * @param string $sourcePrincipalUri
1502
-	 * @param int $sourceObjectId
1503
-	 * @param string $targetPrincipalUri
1504
-	 * @param int $targetCalendarId
1505
-	 * @param string $tragetObjectUri
1506
-	 * @param int $calendarType
1507
-	 * @return bool
1508
-	 * @throws Exception
1509
-	 */
1510
-	public function moveCalendarObject(string $sourcePrincipalUri, int $sourceObjectId, string $targetPrincipalUri, int $targetCalendarId, string $tragetObjectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR): bool {
1511
-		$this->cachedObjects = [];
1512
-		return $this->atomic(function () use ($sourcePrincipalUri, $sourceObjectId, $targetPrincipalUri, $targetCalendarId, $tragetObjectUri, $calendarType) {
1513
-			$object = $this->getCalendarObjectById($sourcePrincipalUri, $sourceObjectId);
1514
-			if (empty($object)) {
1515
-				return false;
1516
-			}
1517
-
1518
-			$sourceCalendarId = $object['calendarid'];
1519
-			$sourceObjectUri = $object['uri'];
1520
-
1521
-			$query = $this->db->getQueryBuilder();
1522
-			$query->update('calendarobjects')
1523
-				->set('calendarid', $query->createNamedParameter($targetCalendarId, IQueryBuilder::PARAM_INT))
1524
-				->set('uri', $query->createNamedParameter($tragetObjectUri, IQueryBuilder::PARAM_STR))
1525
-				->where($query->expr()->eq('id', $query->createNamedParameter($sourceObjectId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
1526
-				->executeStatement();
1527
-
1528
-			$this->purgeProperties($sourceCalendarId, $sourceObjectId);
1529
-			$this->updateProperties($targetCalendarId, $tragetObjectUri, $object['calendardata'], $calendarType);
1530
-
1531
-			$this->addChanges($sourceCalendarId, [$sourceObjectUri], 3, $calendarType);
1532
-			$this->addChanges($targetCalendarId, [$tragetObjectUri], 1, $calendarType);
1533
-
1534
-			$object = $this->getCalendarObjectById($targetPrincipalUri, $sourceObjectId);
1535
-			// Calendar Object wasn't found - possibly because it was deleted in the meantime by a different client
1536
-			if (empty($object)) {
1537
-				return false;
1538
-			}
1539
-
1540
-			$targetCalendarRow = $this->getCalendarById($targetCalendarId);
1541
-			// the calendar this event is being moved to does not exist any longer
1542
-			if (empty($targetCalendarRow)) {
1543
-				return false;
1544
-			}
1545
-
1546
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1547
-				$sourceShares = $this->getShares($sourceCalendarId);
1548
-				$targetShares = $this->getShares($targetCalendarId);
1549
-				$sourceCalendarRow = $this->getCalendarById($sourceCalendarId);
1550
-				$this->dispatcher->dispatchTyped(new CalendarObjectMovedEvent($sourceCalendarId, $sourceCalendarRow, $targetCalendarId, $targetCalendarRow, $sourceShares, $targetShares, $object));
1551
-			}
1552
-			return true;
1553
-		}, $this->db);
1554
-	}
1555
-
1556
-	/**
1557
-	 * Deletes an existing calendar object.
1558
-	 *
1559
-	 * The object uri is only the basename, or filename and not a full path.
1560
-	 *
1561
-	 * @param mixed $calendarId
1562
-	 * @param string $objectUri
1563
-	 * @param int $calendarType
1564
-	 * @param bool $forceDeletePermanently
1565
-	 * @return void
1566
-	 */
1567
-	public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
1568
-		$this->cachedObjects = [];
1569
-		$this->atomic(function () use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently): void {
1570
-			$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1571
-
1572
-			if ($data === null) {
1573
-				// Nothing to delete
1574
-				return;
1575
-			}
1576
-
1577
-			if ($forceDeletePermanently || $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0') {
1578
-				$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1579
-				$stmt->execute([$calendarId, $objectUri, $calendarType]);
1580
-
1581
-				$this->purgeProperties($calendarId, $data['id']);
1582
-
1583
-				$this->purgeObjectInvitations($data['uid']);
1584
-
1585
-				if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1586
-					$calendarRow = $this->getCalendarById($calendarId);
1587
-					$shares = $this->getShares($calendarId);
1588
-
1589
-					$this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent($calendarId, $calendarRow, $shares, $data));
1590
-				} else {
1591
-					$subscriptionRow = $this->getSubscriptionById($calendarId);
1592
-
1593
-					$this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent($calendarId, $subscriptionRow, [], $data));
1594
-				}
1595
-			} else {
1596
-				$pathInfo = pathinfo($data['uri']);
1597
-				if (!empty($pathInfo['extension'])) {
1598
-					// Append a suffix to "free" the old URI for recreation
1599
-					$newUri = sprintf(
1600
-						'%s-deleted.%s',
1601
-						$pathInfo['filename'],
1602
-						$pathInfo['extension']
1603
-					);
1604
-				} else {
1605
-					$newUri = sprintf(
1606
-						'%s-deleted',
1607
-						$pathInfo['filename']
1608
-					);
1609
-				}
1610
-
1611
-				// Try to detect conflicts before the DB does
1612
-				// As unlikely as it seems, this can happen when the user imports, then deletes, imports and deletes again
1613
-				$newObject = $this->getCalendarObject($calendarId, $newUri, $calendarType);
1614
-				if ($newObject !== null) {
1615
-					throw new Forbidden("A calendar object with URI $newUri already exists in calendar $calendarId, therefore this object can't be moved into the trashbin");
1616
-				}
1617
-
1618
-				$qb = $this->db->getQueryBuilder();
1619
-				$markObjectDeletedQuery = $qb->update('calendarobjects')
1620
-					->set('deleted_at', $qb->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
1621
-					->set('uri', $qb->createNamedParameter($newUri))
1622
-					->where(
1623
-						$qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
1624
-						$qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
1625
-						$qb->expr()->eq('uri', $qb->createNamedParameter($objectUri))
1626
-					);
1627
-				$markObjectDeletedQuery->executeStatement();
1628
-
1629
-				$calendarData = $this->getCalendarById($calendarId);
1630
-				if ($calendarData !== null) {
1631
-					$this->dispatcher->dispatchTyped(
1632
-						new CalendarObjectMovedToTrashEvent(
1633
-							$calendarId,
1634
-							$calendarData,
1635
-							$this->getShares($calendarId),
1636
-							$data
1637
-						)
1638
-					);
1639
-				}
1640
-			}
1641
-
1642
-			$this->addChanges($calendarId, [$objectUri], 3, $calendarType);
1643
-		}, $this->db);
1644
-	}
1645
-
1646
-	/**
1647
-	 * @param mixed $objectData
1648
-	 *
1649
-	 * @throws Forbidden
1650
-	 */
1651
-	public function restoreCalendarObject(array $objectData): void {
1652
-		$this->cachedObjects = [];
1653
-		$this->atomic(function () use ($objectData): void {
1654
-			$id = (int)$objectData['id'];
1655
-			$restoreUri = str_replace('-deleted.ics', '.ics', $objectData['uri']);
1656
-			$targetObject = $this->getCalendarObject(
1657
-				$objectData['calendarid'],
1658
-				$restoreUri
1659
-			);
1660
-			if ($targetObject !== null) {
1661
-				throw new Forbidden("Can not restore calendar $id because a calendar object with the URI $restoreUri already exists");
1662
-			}
1663
-
1664
-			$qb = $this->db->getQueryBuilder();
1665
-			$update = $qb->update('calendarobjects')
1666
-				->set('uri', $qb->createNamedParameter($restoreUri))
1667
-				->set('deleted_at', $qb->createNamedParameter(null))
1668
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1669
-			$update->executeStatement();
1670
-
1671
-			// Make sure this change is tracked in the changes table
1672
-			$qb2 = $this->db->getQueryBuilder();
1673
-			$selectObject = $qb2->select('calendardata', 'uri', 'calendarid', 'calendartype')
1674
-				->selectAlias('componenttype', 'component')
1675
-				->from('calendarobjects')
1676
-				->where($qb2->expr()->eq('id', $qb2->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1677
-			$result = $selectObject->executeQuery();
1678
-			$row = $result->fetch();
1679
-			$result->closeCursor();
1680
-			if ($row === false) {
1681
-				// Welp, this should possibly not have happened, but let's ignore
1682
-				return;
1683
-			}
1684
-			$this->addChanges($row['calendarid'], [$row['uri']], 1, (int)$row['calendartype']);
1685
-
1686
-			$calendarRow = $this->getCalendarById((int)$row['calendarid']);
1687
-			if ($calendarRow === null) {
1688
-				throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
1689
-			}
1690
-			$this->dispatcher->dispatchTyped(
1691
-				new CalendarObjectRestoredEvent(
1692
-					(int)$objectData['calendarid'],
1693
-					$calendarRow,
1694
-					$this->getShares((int)$row['calendarid']),
1695
-					$row
1696
-				)
1697
-			);
1698
-		}, $this->db);
1699
-	}
1700
-
1701
-	/**
1702
-	 * Performs a calendar-query on the contents of this calendar.
1703
-	 *
1704
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1705
-	 * calendar-query it is possible for a client to request a specific set of
1706
-	 * object, based on contents of iCalendar properties, date-ranges and
1707
-	 * iCalendar component types (VTODO, VEVENT).
1708
-	 *
1709
-	 * This method should just return a list of (relative) urls that match this
1710
-	 * query.
1711
-	 *
1712
-	 * The list of filters are specified as an array. The exact array is
1713
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1714
-	 *
1715
-	 * Note that it is extremely likely that getCalendarObject for every path
1716
-	 * returned from this method will be called almost immediately after. You
1717
-	 * may want to anticipate this to speed up these requests.
1718
-	 *
1719
-	 * This method provides a default implementation, which parses *all* the
1720
-	 * iCalendar objects in the specified calendar.
1721
-	 *
1722
-	 * This default may well be good enough for personal use, and calendars
1723
-	 * that aren't very large. But if you anticipate high usage, big calendars
1724
-	 * or high loads, you are strongly advised to optimize certain paths.
1725
-	 *
1726
-	 * The best way to do so is override this method and to optimize
1727
-	 * specifically for 'common filters'.
1728
-	 *
1729
-	 * Requests that are extremely common are:
1730
-	 *   * requests for just VEVENTS
1731
-	 *   * requests for just VTODO
1732
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1733
-	 *
1734
-	 * ..and combinations of these requests. It may not be worth it to try to
1735
-	 * handle every possible situation and just rely on the (relatively
1736
-	 * easy to use) CalendarQueryValidator to handle the rest.
1737
-	 *
1738
-	 * Note that especially time-range-filters may be difficult to parse. A
1739
-	 * time-range filter specified on a VEVENT must for instance also handle
1740
-	 * recurrence rules correctly.
1741
-	 * A good example of how to interpret all these filters can also simply
1742
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1743
-	 * as possible, so it gives you a good idea on what type of stuff you need
1744
-	 * to think of.
1745
-	 *
1746
-	 * @param mixed $calendarId
1747
-	 * @param array $filters
1748
-	 * @param int $calendarType
1749
-	 * @return array
1750
-	 */
1751
-	public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1752
-		$componentType = null;
1753
-		$requirePostFilter = true;
1754
-		$timeRange = null;
1755
-
1756
-		// if no filters were specified, we don't need to filter after a query
1757
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1758
-			$requirePostFilter = false;
1759
-		}
1760
-
1761
-		// Figuring out if there's a component filter
1762
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1763
-			$componentType = $filters['comp-filters'][0]['name'];
1764
-
1765
-			// Checking if we need post-filters
1766
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1767
-				$requirePostFilter = false;
1768
-			}
1769
-			// There was a time-range filter
1770
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
1771
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1772
-
1773
-				// If start time OR the end time is not specified, we can do a
1774
-				// 100% accurate mysql query.
1775
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1776
-					$requirePostFilter = false;
1777
-				}
1778
-			}
1779
-		}
1780
-		$query = $this->db->getQueryBuilder();
1781
-		$query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1782
-			->from('calendarobjects')
1783
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1784
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1785
-			->andWhere($query->expr()->isNull('deleted_at'));
1786
-
1787
-		if ($componentType) {
1788
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1789
-		}
1790
-
1791
-		if ($timeRange && $timeRange['start']) {
1792
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1793
-		}
1794
-		if ($timeRange && $timeRange['end']) {
1795
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1796
-		}
1797
-
1798
-		$stmt = $query->executeQuery();
1799
-
1800
-		$result = [];
1801
-		while ($row = $stmt->fetch()) {
1802
-			// if we leave it as a blob we can't read it both from the post filter and the rowToCalendarObject
1803
-			if (isset($row['calendardata'])) {
1804
-				$row['calendardata'] = $this->readBlob($row['calendardata']);
1805
-			}
1806
-
1807
-			if ($requirePostFilter) {
1808
-				// validateFilterForObject will parse the calendar data
1809
-				// catch parsing errors
1810
-				try {
1811
-					$matches = $this->validateFilterForObject($row, $filters);
1812
-				} catch (ParseException $ex) {
1813
-					$this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1814
-						'app' => 'dav',
1815
-						'exception' => $ex,
1816
-					]);
1817
-					continue;
1818
-				} catch (InvalidDataException $ex) {
1819
-					$this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1820
-						'app' => 'dav',
1821
-						'exception' => $ex,
1822
-					]);
1823
-					continue;
1824
-				} catch (MaxInstancesExceededException $ex) {
1825
-					$this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
1826
-						'app' => 'dav',
1827
-						'exception' => $ex,
1828
-					]);
1829
-					continue;
1830
-				}
1831
-
1832
-				if (!$matches) {
1833
-					continue;
1834
-				}
1835
-			}
1836
-			$result[] = $row['uri'];
1837
-			$key = $calendarId . '::' . $row['uri'] . '::' . $calendarType;
1838
-			$this->cachedObjects[$key] = $this->rowToCalendarObject($row);
1839
-		}
1840
-
1841
-		return $result;
1842
-	}
1843
-
1844
-	/**
1845
-	 * custom Nextcloud search extension for CalDAV
1846
-	 *
1847
-	 * TODO - this should optionally cover cached calendar objects as well
1848
-	 *
1849
-	 * @param string $principalUri
1850
-	 * @param array $filters
1851
-	 * @param integer|null $limit
1852
-	 * @param integer|null $offset
1853
-	 * @return array
1854
-	 */
1855
-	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1856
-		return $this->atomic(function () use ($principalUri, $filters, $limit, $offset) {
1857
-			$calendars = $this->getCalendarsForUser($principalUri);
1858
-			$ownCalendars = [];
1859
-			$sharedCalendars = [];
1860
-
1861
-			$uriMapper = [];
1862
-
1863
-			foreach ($calendars as $calendar) {
1864
-				if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1865
-					$ownCalendars[] = $calendar['id'];
1866
-				} else {
1867
-					$sharedCalendars[] = $calendar['id'];
1868
-				}
1869
-				$uriMapper[$calendar['id']] = $calendar['uri'];
1870
-			}
1871
-			if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1872
-				return [];
1873
-			}
1874
-
1875
-			$query = $this->db->getQueryBuilder();
1876
-			// Calendar id expressions
1877
-			$calendarExpressions = [];
1878
-			foreach ($ownCalendars as $id) {
1879
-				$calendarExpressions[] = $query->expr()->andX(
1880
-					$query->expr()->eq('c.calendarid',
1881
-						$query->createNamedParameter($id)),
1882
-					$query->expr()->eq('c.calendartype',
1883
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1884
-			}
1885
-			foreach ($sharedCalendars as $id) {
1886
-				$calendarExpressions[] = $query->expr()->andX(
1887
-					$query->expr()->eq('c.calendarid',
1888
-						$query->createNamedParameter($id)),
1889
-					$query->expr()->eq('c.classification',
1890
-						$query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1891
-					$query->expr()->eq('c.calendartype',
1892
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1893
-			}
1894
-
1895
-			if (count($calendarExpressions) === 1) {
1896
-				$calExpr = $calendarExpressions[0];
1897
-			} else {
1898
-				$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1899
-			}
1900
-
1901
-			// Component expressions
1902
-			$compExpressions = [];
1903
-			foreach ($filters['comps'] as $comp) {
1904
-				$compExpressions[] = $query->expr()
1905
-					->eq('c.componenttype', $query->createNamedParameter($comp));
1906
-			}
1907
-
1908
-			if (count($compExpressions) === 1) {
1909
-				$compExpr = $compExpressions[0];
1910
-			} else {
1911
-				$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1912
-			}
1913
-
1914
-			if (!isset($filters['props'])) {
1915
-				$filters['props'] = [];
1916
-			}
1917
-			if (!isset($filters['params'])) {
1918
-				$filters['params'] = [];
1919
-			}
1920
-
1921
-			$propParamExpressions = [];
1922
-			foreach ($filters['props'] as $prop) {
1923
-				$propParamExpressions[] = $query->expr()->andX(
1924
-					$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1925
-					$query->expr()->isNull('i.parameter')
1926
-				);
1927
-			}
1928
-			foreach ($filters['params'] as $param) {
1929
-				$propParamExpressions[] = $query->expr()->andX(
1930
-					$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1931
-					$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1932
-				);
1933
-			}
1934
-
1935
-			if (count($propParamExpressions) === 1) {
1936
-				$propParamExpr = $propParamExpressions[0];
1937
-			} else {
1938
-				$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1939
-			}
1940
-
1941
-			$query->select(['c.calendarid', 'c.uri'])
1942
-				->from($this->dbObjectPropertiesTable, 'i')
1943
-				->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1944
-				->where($calExpr)
1945
-				->andWhere($compExpr)
1946
-				->andWhere($propParamExpr)
1947
-				->andWhere($query->expr()->iLike('i.value',
1948
-					$query->createNamedParameter('%' . $this->db->escapeLikeParameter($filters['search-term']) . '%')))
1949
-				->andWhere($query->expr()->isNull('deleted_at'));
1950
-
1951
-			if ($offset) {
1952
-				$query->setFirstResult($offset);
1953
-			}
1954
-			if ($limit) {
1955
-				$query->setMaxResults($limit);
1956
-			}
1957
-
1958
-			$stmt = $query->executeQuery();
1959
-
1960
-			$result = [];
1961
-			while ($row = $stmt->fetch()) {
1962
-				$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1963
-				if (!in_array($path, $result)) {
1964
-					$result[] = $path;
1965
-				}
1966
-			}
1967
-
1968
-			return $result;
1969
-		}, $this->db);
1970
-	}
1971
-
1972
-	/**
1973
-	 * used for Nextcloud's calendar API
1974
-	 *
1975
-	 * @param array $calendarInfo
1976
-	 * @param string $pattern
1977
-	 * @param array $searchProperties
1978
-	 * @param array $options
1979
-	 * @param integer|null $limit
1980
-	 * @param integer|null $offset
1981
-	 *
1982
-	 * @return array
1983
-	 */
1984
-	public function search(
1985
-		array $calendarInfo,
1986
-		$pattern,
1987
-		array $searchProperties,
1988
-		array $options,
1989
-		$limit,
1990
-		$offset,
1991
-	) {
1992
-		$outerQuery = $this->db->getQueryBuilder();
1993
-		$innerQuery = $this->db->getQueryBuilder();
1994
-
1995
-		if (isset($calendarInfo['source'])) {
1996
-			$calendarType = self::CALENDAR_TYPE_SUBSCRIPTION;
1997
-		} elseif (isset($calendarInfo['federated'])) {
1998
-			$calendarType = self::CALENDAR_TYPE_FEDERATED;
1999
-		} else {
2000
-			$calendarType = self::CALENDAR_TYPE_CALENDAR;
2001
-		}
2002
-
2003
-		$innerQuery->selectDistinct('op.objectid')
2004
-			->from($this->dbObjectPropertiesTable, 'op')
2005
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
2006
-				$outerQuery->createNamedParameter($calendarInfo['id'])))
2007
-			->andWhere($innerQuery->expr()->eq('op.calendartype',
2008
-				$outerQuery->createNamedParameter($calendarType)));
2009
-
2010
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
2011
-			->from('calendarobjects', 'c')
2012
-			->where($outerQuery->expr()->isNull('deleted_at'));
2013
-
2014
-		// only return public items for shared calendars for now
2015
-		if (isset($calendarInfo['{http://owncloud.org/ns}owner-principal']) === false || $calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
2016
-			$outerQuery->andWhere($outerQuery->expr()->eq('c.classification',
2017
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2018
-		}
2019
-
2020
-		if (!empty($searchProperties)) {
2021
-			$or = [];
2022
-			foreach ($searchProperties as $searchProperty) {
2023
-				$or[] = $innerQuery->expr()->eq('op.name',
2024
-					$outerQuery->createNamedParameter($searchProperty));
2025
-			}
2026
-			$innerQuery->andWhere($innerQuery->expr()->orX(...$or));
2027
-		}
2028
-
2029
-		if ($pattern !== '') {
2030
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
2031
-				$outerQuery->createNamedParameter('%'
2032
-					. $this->db->escapeLikeParameter($pattern) . '%')));
2033
-		}
2034
-
2035
-		$start = null;
2036
-		$end = null;
2037
-
2038
-		$hasLimit = is_int($limit);
2039
-		$hasTimeRange = false;
2040
-
2041
-		if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2042
-			/** @var DateTimeInterface $start */
2043
-			$start = $options['timerange']['start'];
2044
-			$outerQuery->andWhere(
2045
-				$outerQuery->expr()->gt(
2046
-					'lastoccurence',
2047
-					$outerQuery->createNamedParameter($start->getTimestamp())
2048
-				)
2049
-			);
2050
-			$hasTimeRange = true;
2051
-		}
2052
-
2053
-		if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2054
-			/** @var DateTimeInterface $end */
2055
-			$end = $options['timerange']['end'];
2056
-			$outerQuery->andWhere(
2057
-				$outerQuery->expr()->lt(
2058
-					'firstoccurence',
2059
-					$outerQuery->createNamedParameter($end->getTimestamp())
2060
-				)
2061
-			);
2062
-			$hasTimeRange = true;
2063
-		}
2064
-
2065
-		if (isset($options['uid'])) {
2066
-			$outerQuery->andWhere($outerQuery->expr()->eq('uid', $outerQuery->createNamedParameter($options['uid'])));
2067
-		}
2068
-
2069
-		if (!empty($options['types'])) {
2070
-			$or = [];
2071
-			foreach ($options['types'] as $type) {
2072
-				$or[] = $outerQuery->expr()->eq('componenttype',
2073
-					$outerQuery->createNamedParameter($type));
2074
-			}
2075
-			$outerQuery->andWhere($outerQuery->expr()->orX(...$or));
2076
-		}
2077
-
2078
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id', $outerQuery->createFunction($innerQuery->getSQL())));
2079
-
2080
-		// Without explicit order by its undefined in which order the SQL server returns the events.
2081
-		// For the pagination with hasLimit and hasTimeRange, a stable ordering is helpful.
2082
-		$outerQuery->addOrderBy('id');
2083
-
2084
-		$offset = (int)$offset;
2085
-		$outerQuery->setFirstResult($offset);
2086
-
2087
-		$calendarObjects = [];
2088
-
2089
-		if ($hasLimit && $hasTimeRange) {
2090
-			/**
2091
-			 * Event recurrences are evaluated at runtime because the database only knows the first and last occurrence.
2092
-			 *
2093
-			 * Given, a user created 8 events with a yearly reoccurrence and two for events tomorrow.
2094
-			 * The upcoming event widget asks the CalDAV backend for 7 events within the next 14 days.
2095
-			 *
2096
-			 * If limit 7 is applied to the SQL query, we find the 7 events with a yearly reoccurrence
2097
-			 * and discard the events after evaluating the reoccurrence rules because they are not due within
2098
-			 * the next 14 days and end up with an empty result even if there are two events to show.
2099
-			 *
2100
-			 * The workaround for search requests with a limit and time range is asking for more row than requested
2101
-			 * and retrying if we have not reached the limit.
2102
-			 *
2103
-			 * 25 rows and 3 retries is entirely arbitrary.
2104
-			 */
2105
-			$maxResults = (int)max($limit, 25);
2106
-			$outerQuery->setMaxResults($maxResults);
2107
-
2108
-			for ($attempt = $objectsCount = 0; $attempt < 3 && $objectsCount < $limit; $attempt++) {
2109
-				$objectsCount = array_push($calendarObjects, ...$this->searchCalendarObjects($outerQuery, $start, $end));
2110
-				$outerQuery->setFirstResult($offset += $maxResults);
2111
-			}
2112
-
2113
-			$calendarObjects = array_slice($calendarObjects, 0, $limit, false);
2114
-		} else {
2115
-			$outerQuery->setMaxResults($limit);
2116
-			$calendarObjects = $this->searchCalendarObjects($outerQuery, $start, $end);
2117
-		}
2118
-
2119
-		$calendarObjects = array_map(function ($o) use ($options) {
2120
-			$calendarData = Reader::read($o['calendardata']);
2121
-
2122
-			// Expand recurrences if an explicit time range is requested
2123
-			if ($calendarData instanceof VCalendar
2124
-				&& isset($options['timerange']['start'], $options['timerange']['end'])) {
2125
-				$calendarData = $calendarData->expand(
2126
-					$options['timerange']['start'],
2127
-					$options['timerange']['end'],
2128
-				);
2129
-			}
2130
-
2131
-			$comps = $calendarData->getComponents();
2132
-			$objects = [];
2133
-			$timezones = [];
2134
-			foreach ($comps as $comp) {
2135
-				if ($comp instanceof VTimeZone) {
2136
-					$timezones[] = $comp;
2137
-				} else {
2138
-					$objects[] = $comp;
2139
-				}
2140
-			}
2141
-
2142
-			return [
2143
-				'id' => $o['id'],
2144
-				'type' => $o['componenttype'],
2145
-				'uid' => $o['uid'],
2146
-				'uri' => $o['uri'],
2147
-				'objects' => array_map(function ($c) {
2148
-					return $this->transformSearchData($c);
2149
-				}, $objects),
2150
-				'timezones' => array_map(function ($c) {
2151
-					return $this->transformSearchData($c);
2152
-				}, $timezones),
2153
-			];
2154
-		}, $calendarObjects);
2155
-
2156
-		usort($calendarObjects, function (array $a, array $b) {
2157
-			/** @var DateTimeImmutable $startA */
2158
-			$startA = $a['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2159
-			/** @var DateTimeImmutable $startB */
2160
-			$startB = $b['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2161
-
2162
-			return $startA->getTimestamp() <=> $startB->getTimestamp();
2163
-		});
2164
-
2165
-		return $calendarObjects;
2166
-	}
2167
-
2168
-	private function searchCalendarObjects(IQueryBuilder $query, ?DateTimeInterface $start, ?DateTimeInterface $end): array {
2169
-		$calendarObjects = [];
2170
-		$filterByTimeRange = ($start instanceof DateTimeInterface) || ($end instanceof DateTimeInterface);
2171
-
2172
-		$result = $query->executeQuery();
2173
-
2174
-		while (($row = $result->fetch()) !== false) {
2175
-			if ($filterByTimeRange === false) {
2176
-				// No filter required
2177
-				$calendarObjects[] = $row;
2178
-				continue;
2179
-			}
2180
-
2181
-			try {
2182
-				$isValid = $this->validateFilterForObject($row, [
2183
-					'name' => 'VCALENDAR',
2184
-					'comp-filters' => [
2185
-						[
2186
-							'name' => 'VEVENT',
2187
-							'comp-filters' => [],
2188
-							'prop-filters' => [],
2189
-							'is-not-defined' => false,
2190
-							'time-range' => [
2191
-								'start' => $start,
2192
-								'end' => $end,
2193
-							],
2194
-						],
2195
-					],
2196
-					'prop-filters' => [],
2197
-					'is-not-defined' => false,
2198
-					'time-range' => null,
2199
-				]);
2200
-			} catch (MaxInstancesExceededException $ex) {
2201
-				$this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
2202
-					'app' => 'dav',
2203
-					'exception' => $ex,
2204
-				]);
2205
-				continue;
2206
-			}
2207
-
2208
-			if (is_resource($row['calendardata'])) {
2209
-				// Put the stream back to the beginning so it can be read another time
2210
-				rewind($row['calendardata']);
2211
-			}
2212
-
2213
-			if ($isValid) {
2214
-				$calendarObjects[] = $row;
2215
-			}
2216
-		}
2217
-
2218
-		$result->closeCursor();
2219
-
2220
-		return $calendarObjects;
2221
-	}
2222
-
2223
-	/**
2224
-	 * @param Component $comp
2225
-	 * @return array
2226
-	 */
2227
-	private function transformSearchData(Component $comp) {
2228
-		$data = [];
2229
-		/** @var Component[] $subComponents */
2230
-		$subComponents = $comp->getComponents();
2231
-		/** @var Property[] $properties */
2232
-		$properties = array_filter($comp->children(), function ($c) {
2233
-			return $c instanceof Property;
2234
-		});
2235
-		$validationRules = $comp->getValidationRules();
2236
-
2237
-		foreach ($subComponents as $subComponent) {
2238
-			$name = $subComponent->name;
2239
-			if (!isset($data[$name])) {
2240
-				$data[$name] = [];
2241
-			}
2242
-			$data[$name][] = $this->transformSearchData($subComponent);
2243
-		}
2244
-
2245
-		foreach ($properties as $property) {
2246
-			$name = $property->name;
2247
-			if (!isset($validationRules[$name])) {
2248
-				$validationRules[$name] = '*';
2249
-			}
2250
-
2251
-			$rule = $validationRules[$property->name];
2252
-			if ($rule === '+' || $rule === '*') { // multiple
2253
-				if (!isset($data[$name])) {
2254
-					$data[$name] = [];
2255
-				}
2256
-
2257
-				$data[$name][] = $this->transformSearchProperty($property);
2258
-			} else { // once
2259
-				$data[$name] = $this->transformSearchProperty($property);
2260
-			}
2261
-		}
2262
-
2263
-		return $data;
2264
-	}
2265
-
2266
-	/**
2267
-	 * @param Property $prop
2268
-	 * @return array
2269
-	 */
2270
-	private function transformSearchProperty(Property $prop) {
2271
-		// No need to check Date, as it extends DateTime
2272
-		if ($prop instanceof Property\ICalendar\DateTime) {
2273
-			$value = $prop->getDateTime();
2274
-		} else {
2275
-			$value = $prop->getValue();
2276
-		}
2277
-
2278
-		return [
2279
-			$value,
2280
-			$prop->parameters()
2281
-		];
2282
-	}
2283
-
2284
-	/**
2285
-	 * @param string $principalUri
2286
-	 * @param string $pattern
2287
-	 * @param array $componentTypes
2288
-	 * @param array $searchProperties
2289
-	 * @param array $searchParameters
2290
-	 * @param array $options
2291
-	 * @return array
2292
-	 */
2293
-	public function searchPrincipalUri(string $principalUri,
2294
-		string $pattern,
2295
-		array $componentTypes,
2296
-		array $searchProperties,
2297
-		array $searchParameters,
2298
-		array $options = [],
2299
-	): array {
2300
-		return $this->atomic(function () use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
2301
-			$escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
2302
-
2303
-			$calendarObjectIdQuery = $this->db->getQueryBuilder();
2304
-			$calendarOr = [];
2305
-			$searchOr = [];
2306
-
2307
-			// Fetch calendars and subscription
2308
-			$calendars = $this->getCalendarsForUser($principalUri);
2309
-			$subscriptions = $this->getSubscriptionsForUser($principalUri);
2310
-			foreach ($calendars as $calendar) {
2311
-				$calendarAnd = $calendarObjectIdQuery->expr()->andX(
2312
-					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])),
2313
-					$calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)),
2314
-				);
2315
-
2316
-				// If it's shared, limit search to public events
2317
-				if (isset($calendar['{http://owncloud.org/ns}owner-principal'])
2318
-					&& $calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
2319
-					$calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2320
-				}
2321
-
2322
-				$calendarOr[] = $calendarAnd;
2323
-			}
2324
-			foreach ($subscriptions as $subscription) {
2325
-				$subscriptionAnd = $calendarObjectIdQuery->expr()->andX(
2326
-					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])),
2327
-					$calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)),
2328
-				);
2329
-
2330
-				// If it's shared, limit search to public events
2331
-				if (isset($subscription['{http://owncloud.org/ns}owner-principal'])
2332
-					&& $subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
2333
-					$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2334
-				}
2335
-
2336
-				$calendarOr[] = $subscriptionAnd;
2337
-			}
2338
-
2339
-			foreach ($searchProperties as $property) {
2340
-				$propertyAnd = $calendarObjectIdQuery->expr()->andX(
2341
-					$calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2342
-					$calendarObjectIdQuery->expr()->isNull('cob.parameter'),
2343
-				);
2344
-
2345
-				$searchOr[] = $propertyAnd;
2346
-			}
2347
-			foreach ($searchParameters as $property => $parameter) {
2348
-				$parameterAnd = $calendarObjectIdQuery->expr()->andX(
2349
-					$calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2350
-					$calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)),
2351
-				);
2352
-
2353
-				$searchOr[] = $parameterAnd;
2354
-			}
2355
-
2356
-			if (empty($calendarOr)) {
2357
-				return [];
2358
-			}
2359
-			if (empty($searchOr)) {
2360
-				return [];
2361
-			}
2362
-
2363
-			$calendarObjectIdQuery->selectDistinct('cob.objectid')
2364
-				->from($this->dbObjectPropertiesTable, 'cob')
2365
-				->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
2366
-				->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
2367
-				->andWhere($calendarObjectIdQuery->expr()->orX(...$calendarOr))
2368
-				->andWhere($calendarObjectIdQuery->expr()->orX(...$searchOr))
2369
-				->andWhere($calendarObjectIdQuery->expr()->isNull('deleted_at'));
2370
-
2371
-			if ($pattern !== '') {
2372
-				if (!$escapePattern) {
2373
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
2374
-				} else {
2375
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
2376
-				}
2377
-			}
2378
-
2379
-			if (isset($options['limit'])) {
2380
-				$calendarObjectIdQuery->setMaxResults($options['limit']);
2381
-			}
2382
-			if (isset($options['offset'])) {
2383
-				$calendarObjectIdQuery->setFirstResult($options['offset']);
2384
-			}
2385
-			if (isset($options['timerange'])) {
2386
-				if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2387
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->gt(
2388
-						'lastoccurence',
2389
-						$calendarObjectIdQuery->createNamedParameter($options['timerange']['start']->getTimeStamp()),
2390
-					));
2391
-				}
2392
-				if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2393
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->lt(
2394
-						'firstoccurence',
2395
-						$calendarObjectIdQuery->createNamedParameter($options['timerange']['end']->getTimeStamp()),
2396
-					));
2397
-				}
2398
-			}
2399
-
2400
-			$result = $calendarObjectIdQuery->executeQuery();
2401
-			$matches = [];
2402
-			while (($row = $result->fetch()) !== false) {
2403
-				$matches[] = (int)$row['objectid'];
2404
-			}
2405
-			$result->closeCursor();
2406
-
2407
-			$query = $this->db->getQueryBuilder();
2408
-			$query->select('calendardata', 'uri', 'calendarid', 'calendartype')
2409
-				->from('calendarobjects')
2410
-				->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
2411
-
2412
-			$result = $query->executeQuery();
2413
-			$calendarObjects = [];
2414
-			while (($array = $result->fetch()) !== false) {
2415
-				$array['calendarid'] = (int)$array['calendarid'];
2416
-				$array['calendartype'] = (int)$array['calendartype'];
2417
-				$array['calendardata'] = $this->readBlob($array['calendardata']);
2418
-
2419
-				$calendarObjects[] = $array;
2420
-			}
2421
-			$result->closeCursor();
2422
-			return $calendarObjects;
2423
-		}, $this->db);
2424
-	}
2425
-
2426
-	/**
2427
-	 * Searches through all of a users calendars and calendar objects to find
2428
-	 * an object with a specific UID.
2429
-	 *
2430
-	 * This method should return the path to this object, relative to the
2431
-	 * calendar home, so this path usually only contains two parts:
2432
-	 *
2433
-	 * calendarpath/objectpath.ics
2434
-	 *
2435
-	 * If the uid is not found, return null.
2436
-	 *
2437
-	 * This method should only consider * objects that the principal owns, so
2438
-	 * any calendars owned by other principals that also appear in this
2439
-	 * collection should be ignored.
2440
-	 *
2441
-	 * @param string $principalUri
2442
-	 * @param string $uid
2443
-	 * @return string|null
2444
-	 */
2445
-	public function getCalendarObjectByUID($principalUri, $uid, $calendarUri = null) {
2446
-		$query = $this->db->getQueryBuilder();
2447
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
2448
-			->from('calendarobjects', 'co')
2449
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
2450
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2451
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
2452
-			->andWhere($query->expr()->isNull('co.deleted_at'));
2453
-
2454
-		if ($calendarUri !== null) {
2455
-			$query->andWhere($query->expr()->eq('c.uri', $query->createNamedParameter($calendarUri)));
2456
-		}
2457
-
2458
-		$stmt = $query->executeQuery();
2459
-		$row = $stmt->fetch();
2460
-		$stmt->closeCursor();
2461
-		if ($row) {
2462
-			return $row['calendaruri'] . '/' . $row['objecturi'];
2463
-		}
2464
-
2465
-		return null;
2466
-	}
2467
-
2468
-	public function getCalendarObjectById(string $principalUri, int $id): ?array {
2469
-		$query = $this->db->getQueryBuilder();
2470
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.calendardata', 'co.componenttype', 'co.classification', 'co.deleted_at'])
2471
-			->selectAlias('c.uri', 'calendaruri')
2472
-			->from('calendarobjects', 'co')
2473
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
2474
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2475
-			->andWhere($query->expr()->eq('co.id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
2476
-		$stmt = $query->executeQuery();
2477
-		$row = $stmt->fetch();
2478
-		$stmt->closeCursor();
2479
-
2480
-		if (!$row) {
2481
-			return null;
2482
-		}
2483
-
2484
-		return [
2485
-			'id' => $row['id'],
2486
-			'uri' => $row['uri'],
2487
-			'lastmodified' => $row['lastmodified'],
2488
-			'etag' => '"' . $row['etag'] . '"',
2489
-			'calendarid' => $row['calendarid'],
2490
-			'calendaruri' => $row['calendaruri'],
2491
-			'size' => (int)$row['size'],
2492
-			'calendardata' => $this->readBlob($row['calendardata']),
2493
-			'component' => strtolower($row['componenttype']),
2494
-			'classification' => (int)$row['classification'],
2495
-			'deleted_at' => isset($row['deleted_at']) ? ((int)$row['deleted_at']) : null,
2496
-		];
2497
-	}
2498
-
2499
-	/**
2500
-	 * The getChanges method returns all the changes that have happened, since
2501
-	 * the specified syncToken in the specified calendar.
2502
-	 *
2503
-	 * This function should return an array, such as the following:
2504
-	 *
2505
-	 * [
2506
-	 *   'syncToken' => 'The current synctoken',
2507
-	 *   'added'   => [
2508
-	 *      'new.txt',
2509
-	 *   ],
2510
-	 *   'modified'   => [
2511
-	 *      'modified.txt',
2512
-	 *   ],
2513
-	 *   'deleted' => [
2514
-	 *      'foo.php.bak',
2515
-	 *      'old.txt'
2516
-	 *   ]
2517
-	 * );
2518
-	 *
2519
-	 * The returned syncToken property should reflect the *current* syncToken
2520
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
2521
-	 * property This is * needed here too, to ensure the operation is atomic.
2522
-	 *
2523
-	 * If the $syncToken argument is specified as null, this is an initial
2524
-	 * sync, and all members should be reported.
2525
-	 *
2526
-	 * The modified property is an array of nodenames that have changed since
2527
-	 * the last token.
2528
-	 *
2529
-	 * The deleted property is an array with nodenames, that have been deleted
2530
-	 * from collection.
2531
-	 *
2532
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
2533
-	 * 1, you only have to report changes that happened only directly in
2534
-	 * immediate descendants. If it's 2, it should also include changes from
2535
-	 * the nodes below the child collections. (grandchildren)
2536
-	 *
2537
-	 * The $limit argument allows a client to specify how many results should
2538
-	 * be returned at most. If the limit is not specified, it should be treated
2539
-	 * as infinite.
2540
-	 *
2541
-	 * If the limit (infinite or not) is higher than you're willing to return,
2542
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
2543
-	 *
2544
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
2545
-	 * return null.
2546
-	 *
2547
-	 * The limit is 'suggestive'. You are free to ignore it.
2548
-	 *
2549
-	 * @param string $calendarId
2550
-	 * @param string $syncToken
2551
-	 * @param int $syncLevel
2552
-	 * @param int|null $limit
2553
-	 * @param int $calendarType
2554
-	 * @return ?array
2555
-	 */
2556
-	public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2557
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2558
-
2559
-		return $this->atomic(function () use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
2560
-			// Current synctoken
2561
-			$qb = $this->db->getQueryBuilder();
2562
-			$qb->select('synctoken')
2563
-				->from($table)
2564
-				->where(
2565
-					$qb->expr()->eq('id', $qb->createNamedParameter($calendarId))
2566
-				);
2567
-			$stmt = $qb->executeQuery();
2568
-			$currentToken = $stmt->fetchOne();
2569
-			$initialSync = !is_numeric($syncToken);
2570
-
2571
-			if ($currentToken === false) {
2572
-				return null;
2573
-			}
2574
-
2575
-			// evaluate if this is a initial sync and construct appropriate command
2576
-			if ($initialSync) {
2577
-				$qb = $this->db->getQueryBuilder();
2578
-				$qb->select('uri')
2579
-					->from('calendarobjects')
2580
-					->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2581
-					->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2582
-					->andWhere($qb->expr()->isNull('deleted_at'));
2583
-			} else {
2584
-				$qb = $this->db->getQueryBuilder();
2585
-				$qb->select('uri', $qb->func()->max('operation'))
2586
-					->from('calendarchanges')
2587
-					->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2588
-					->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2589
-					->andWhere($qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)))
2590
-					->andWhere($qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)))
2591
-					->groupBy('uri');
2592
-			}
2593
-			// evaluate if limit exists
2594
-			if (is_numeric($limit)) {
2595
-				$qb->setMaxResults($limit);
2596
-			}
2597
-			// execute command
2598
-			$stmt = $qb->executeQuery();
2599
-			// build results
2600
-			$result = ['syncToken' => $currentToken, 'added' => [], 'modified' => [], 'deleted' => []];
2601
-			// retrieve results
2602
-			if ($initialSync) {
2603
-				$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
2604
-			} else {
2605
-				// \PDO::FETCH_NUM is needed due to the inconsistent field names
2606
-				// produced by doctrine for MAX() with different databases
2607
-				while ($entry = $stmt->fetch(\PDO::FETCH_NUM)) {
2608
-					// assign uri (column 0) to appropriate mutation based on operation (column 1)
2609
-					// forced (int) is needed as doctrine with OCI returns the operation field as string not integer
2610
-					match ((int)$entry[1]) {
2611
-						1 => $result['added'][] = $entry[0],
2612
-						2 => $result['modified'][] = $entry[0],
2613
-						3 => $result['deleted'][] = $entry[0],
2614
-						default => $this->logger->debug('Unknown calendar change operation detected')
2615
-					};
2616
-				}
2617
-			}
2618
-			$stmt->closeCursor();
2619
-
2620
-			return $result;
2621
-		}, $this->db);
2622
-	}
2623
-
2624
-	/**
2625
-	 * Returns a list of subscriptions for a principal.
2626
-	 *
2627
-	 * Every subscription is an array with the following keys:
2628
-	 *  * id, a unique id that will be used by other functions to modify the
2629
-	 *    subscription. This can be the same as the uri or a database key.
2630
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
2631
-	 *  * principaluri. The owner of the subscription. Almost always the same as
2632
-	 *    principalUri passed to this method.
2633
-	 *
2634
-	 * Furthermore, all the subscription info must be returned too:
2635
-	 *
2636
-	 * 1. {DAV:}displayname
2637
-	 * 2. {http://apple.com/ns/ical/}refreshrate
2638
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
2639
-	 *    should not be stripped).
2640
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
2641
-	 *    should not be stripped).
2642
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
2643
-	 *    attachments should not be stripped).
2644
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
2645
-	 *     Sabre\DAV\Property\Href).
2646
-	 * 7. {http://apple.com/ns/ical/}calendar-color
2647
-	 * 8. {http://apple.com/ns/ical/}calendar-order
2648
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
2649
-	 *    (should just be an instance of
2650
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
2651
-	 *    default components).
2652
-	 *
2653
-	 * @param string $principalUri
2654
-	 * @return array
2655
-	 */
2656
-	public function getSubscriptionsForUser($principalUri) {
2657
-		$fields = array_column($this->subscriptionPropertyMap, 0);
2658
-		$fields[] = 'id';
2659
-		$fields[] = 'uri';
2660
-		$fields[] = 'source';
2661
-		$fields[] = 'principaluri';
2662
-		$fields[] = 'lastmodified';
2663
-		$fields[] = 'synctoken';
2664
-
2665
-		$query = $this->db->getQueryBuilder();
2666
-		$query->select($fields)
2667
-			->from('calendarsubscriptions')
2668
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2669
-			->orderBy('calendarorder', 'asc');
2670
-		$stmt = $query->executeQuery();
2671
-
2672
-		$subscriptions = [];
2673
-		while ($row = $stmt->fetch()) {
2674
-			$subscription = [
2675
-				'id' => $row['id'],
2676
-				'uri' => $row['uri'],
2677
-				'principaluri' => $row['principaluri'],
2678
-				'source' => $row['source'],
2679
-				'lastmodified' => $row['lastmodified'],
2680
-
2681
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2682
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
2683
-			];
2684
-
2685
-			$subscriptions[] = $this->rowToSubscription($row, $subscription);
2686
-		}
2687
-
2688
-		return $subscriptions;
2689
-	}
2690
-
2691
-	/**
2692
-	 * Creates a new subscription for a principal.
2693
-	 *
2694
-	 * If the creation was a success, an id must be returned that can be used to reference
2695
-	 * this subscription in other methods, such as updateSubscription.
2696
-	 *
2697
-	 * @param string $principalUri
2698
-	 * @param string $uri
2699
-	 * @param array $properties
2700
-	 * @return mixed
2701
-	 */
2702
-	public function createSubscription($principalUri, $uri, array $properties) {
2703
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2704
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2705
-		}
2706
-
2707
-		$values = [
2708
-			'principaluri' => $principalUri,
2709
-			'uri' => $uri,
2710
-			'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2711
-			'lastmodified' => time(),
2712
-		];
2713
-
2714
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2715
-
2716
-		foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
2717
-			if (array_key_exists($xmlName, $properties)) {
2718
-				$values[$dbName] = $properties[$xmlName];
2719
-				if (in_array($dbName, $propertiesBoolean)) {
2720
-					$values[$dbName] = true;
2721
-				}
2722
-			}
2723
-		}
2724
-
2725
-		[$subscriptionId, $subscriptionRow] = $this->atomic(function () use ($values) {
2726
-			$valuesToInsert = [];
2727
-			$query = $this->db->getQueryBuilder();
2728
-			foreach (array_keys($values) as $name) {
2729
-				$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2730
-			}
2731
-			$query->insert('calendarsubscriptions')
2732
-				->values($valuesToInsert)
2733
-				->executeStatement();
2734
-
2735
-			$subscriptionId = $query->getLastInsertId();
2736
-
2737
-			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2738
-			return [$subscriptionId, $subscriptionRow];
2739
-		}, $this->db);
2740
-
2741
-		$this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow));
2742
-
2743
-		return $subscriptionId;
2744
-	}
2745
-
2746
-	/**
2747
-	 * Updates a subscription
2748
-	 *
2749
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2750
-	 * To do the actual updates, you must tell this object which properties
2751
-	 * you're going to process with the handle() method.
2752
-	 *
2753
-	 * Calling the handle method is like telling the PropPatch object "I
2754
-	 * promise I can handle updating this property".
2755
-	 *
2756
-	 * Read the PropPatch documentation for more info and examples.
2757
-	 *
2758
-	 * @param mixed $subscriptionId
2759
-	 * @param PropPatch $propPatch
2760
-	 * @return void
2761
-	 */
2762
-	public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2763
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
2764
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
2765
-
2766
-		$propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2767
-			$newValues = [];
2768
-
2769
-			foreach ($mutations as $propertyName => $propertyValue) {
2770
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
2771
-					$newValues['source'] = $propertyValue->getHref();
2772
-				} else {
2773
-					$fieldName = $this->subscriptionPropertyMap[$propertyName][0];
2774
-					$newValues[$fieldName] = $propertyValue;
2775
-				}
2776
-			}
2777
-
2778
-			$subscriptionRow = $this->atomic(function () use ($subscriptionId, $newValues) {
2779
-				$query = $this->db->getQueryBuilder();
2780
-				$query->update('calendarsubscriptions')
2781
-					->set('lastmodified', $query->createNamedParameter(time()));
2782
-				foreach ($newValues as $fieldName => $value) {
2783
-					$query->set($fieldName, $query->createNamedParameter($value));
2784
-				}
2785
-				$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2786
-					->executeStatement();
2787
-
2788
-				return $this->getSubscriptionById($subscriptionId);
2789
-			}, $this->db);
2790
-
2791
-			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2792
-
2793
-			return true;
2794
-		});
2795
-	}
2796
-
2797
-	/**
2798
-	 * Deletes a subscription.
2799
-	 *
2800
-	 * @param mixed $subscriptionId
2801
-	 * @return void
2802
-	 */
2803
-	public function deleteSubscription($subscriptionId) {
2804
-		$this->atomic(function () use ($subscriptionId): void {
2805
-			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2806
-
2807
-			$query = $this->db->getQueryBuilder();
2808
-			$query->delete('calendarsubscriptions')
2809
-				->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2810
-				->executeStatement();
2811
-
2812
-			$query = $this->db->getQueryBuilder();
2813
-			$query->delete('calendarobjects')
2814
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2815
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2816
-				->executeStatement();
2817
-
2818
-			$query->delete('calendarchanges')
2819
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2820
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2821
-				->executeStatement();
2822
-
2823
-			$query->delete($this->dbObjectPropertiesTable)
2824
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2825
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2826
-				->executeStatement();
2827
-
2828
-			if ($subscriptionRow) {
2829
-				$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2830
-			}
2831
-		}, $this->db);
2832
-	}
2833
-
2834
-	/**
2835
-	 * Returns a single scheduling object for the inbox collection.
2836
-	 *
2837
-	 * The returned array should contain the following elements:
2838
-	 *   * uri - A unique basename for the object. This will be used to
2839
-	 *           construct a full uri.
2840
-	 *   * calendardata - The iCalendar object
2841
-	 *   * lastmodified - The last modification date. Can be an int for a unix
2842
-	 *                    timestamp, or a PHP DateTime object.
2843
-	 *   * etag - A unique token that must change if the object changed.
2844
-	 *   * size - The size of the object, in bytes.
2845
-	 *
2846
-	 * @param string $principalUri
2847
-	 * @param string $objectUri
2848
-	 * @return array
2849
-	 */
2850
-	public function getSchedulingObject($principalUri, $objectUri) {
2851
-		$query = $this->db->getQueryBuilder();
2852
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2853
-			->from('schedulingobjects')
2854
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2855
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2856
-			->executeQuery();
2857
-
2858
-		$row = $stmt->fetch();
2859
-
2860
-		if (!$row) {
2861
-			return null;
2862
-		}
2863
-
2864
-		return [
2865
-			'uri' => $row['uri'],
2866
-			'calendardata' => $row['calendardata'],
2867
-			'lastmodified' => $row['lastmodified'],
2868
-			'etag' => '"' . $row['etag'] . '"',
2869
-			'size' => (int)$row['size'],
2870
-		];
2871
-	}
2872
-
2873
-	/**
2874
-	 * Returns all scheduling objects for the inbox collection.
2875
-	 *
2876
-	 * These objects should be returned as an array. Every item in the array
2877
-	 * should follow the same structure as returned from getSchedulingObject.
2878
-	 *
2879
-	 * The main difference is that 'calendardata' is optional.
2880
-	 *
2881
-	 * @param string $principalUri
2882
-	 * @return array
2883
-	 */
2884
-	public function getSchedulingObjects($principalUri) {
2885
-		$query = $this->db->getQueryBuilder();
2886
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2887
-			->from('schedulingobjects')
2888
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2889
-			->executeQuery();
2890
-
2891
-		$results = [];
2892
-		while (($row = $stmt->fetch()) !== false) {
2893
-			$results[] = [
2894
-				'calendardata' => $row['calendardata'],
2895
-				'uri' => $row['uri'],
2896
-				'lastmodified' => $row['lastmodified'],
2897
-				'etag' => '"' . $row['etag'] . '"',
2898
-				'size' => (int)$row['size'],
2899
-			];
2900
-		}
2901
-		$stmt->closeCursor();
2902
-
2903
-		return $results;
2904
-	}
2905
-
2906
-	/**
2907
-	 * Deletes a scheduling object from the inbox collection.
2908
-	 *
2909
-	 * @param string $principalUri
2910
-	 * @param string $objectUri
2911
-	 * @return void
2912
-	 */
2913
-	public function deleteSchedulingObject($principalUri, $objectUri) {
2914
-		$this->cachedObjects = [];
2915
-		$query = $this->db->getQueryBuilder();
2916
-		$query->delete('schedulingobjects')
2917
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2918
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2919
-			->executeStatement();
2920
-	}
2921
-
2922
-	/**
2923
-	 * Deletes all scheduling objects last modified before $modifiedBefore from the inbox collection.
2924
-	 *
2925
-	 * @param int $modifiedBefore
2926
-	 * @param int $limit
2927
-	 * @return void
2928
-	 */
2929
-	public function deleteOutdatedSchedulingObjects(int $modifiedBefore, int $limit): void {
2930
-		$query = $this->db->getQueryBuilder();
2931
-		$query->select('id')
2932
-			->from('schedulingobjects')
2933
-			->where($query->expr()->lt('lastmodified', $query->createNamedParameter($modifiedBefore)))
2934
-			->setMaxResults($limit);
2935
-		$result = $query->executeQuery();
2936
-		$count = $result->rowCount();
2937
-		if ($count === 0) {
2938
-			return;
2939
-		}
2940
-		$ids = array_map(static function (array $id) {
2941
-			return (int)$id[0];
2942
-		}, $result->fetchAll(\PDO::FETCH_NUM));
2943
-		$result->closeCursor();
2944
-
2945
-		$numDeleted = 0;
2946
-		$deleteQuery = $this->db->getQueryBuilder();
2947
-		$deleteQuery->delete('schedulingobjects')
2948
-			->where($deleteQuery->expr()->in('id', $deleteQuery->createParameter('ids'), IQueryBuilder::PARAM_INT_ARRAY));
2949
-		foreach (array_chunk($ids, 1000) as $chunk) {
2950
-			$deleteQuery->setParameter('ids', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
2951
-			$numDeleted += $deleteQuery->executeStatement();
2952
-		}
2953
-
2954
-		if ($numDeleted === $limit) {
2955
-			$this->logger->info("Deleted $limit scheduling objects, continuing with next batch");
2956
-			$this->deleteOutdatedSchedulingObjects($modifiedBefore, $limit);
2957
-		}
2958
-	}
2959
-
2960
-	/**
2961
-	 * Creates a new scheduling object. This should land in a users' inbox.
2962
-	 *
2963
-	 * @param string $principalUri
2964
-	 * @param string $objectUri
2965
-	 * @param string $objectData
2966
-	 * @return void
2967
-	 */
2968
-	public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2969
-		$this->cachedObjects = [];
2970
-		$query = $this->db->getQueryBuilder();
2971
-		$query->insert('schedulingobjects')
2972
-			->values([
2973
-				'principaluri' => $query->createNamedParameter($principalUri),
2974
-				'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2975
-				'uri' => $query->createNamedParameter($objectUri),
2976
-				'lastmodified' => $query->createNamedParameter(time()),
2977
-				'etag' => $query->createNamedParameter(md5($objectData)),
2978
-				'size' => $query->createNamedParameter(strlen($objectData))
2979
-			])
2980
-			->executeStatement();
2981
-	}
2982
-
2983
-	/**
2984
-	 * Adds a change record to the calendarchanges table.
2985
-	 *
2986
-	 * @param mixed $calendarId
2987
-	 * @param string[] $objectUris
2988
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2989
-	 * @param int $calendarType
2990
-	 * @return void
2991
-	 */
2992
-	protected function addChanges(int $calendarId, array $objectUris, int $operation, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
2993
-		$this->cachedObjects = [];
2994
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2995
-
2996
-		$this->atomic(function () use ($calendarId, $objectUris, $operation, $calendarType, $table): void {
2997
-			$query = $this->db->getQueryBuilder();
2998
-			$query->select('synctoken')
2999
-				->from($table)
3000
-				->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
3001
-			$result = $query->executeQuery();
3002
-			$syncToken = (int)$result->fetchOne();
3003
-			$result->closeCursor();
3004
-
3005
-			$query = $this->db->getQueryBuilder();
3006
-			$query->insert('calendarchanges')
3007
-				->values([
3008
-					'uri' => $query->createParameter('uri'),
3009
-					'synctoken' => $query->createNamedParameter($syncToken),
3010
-					'calendarid' => $query->createNamedParameter($calendarId),
3011
-					'operation' => $query->createNamedParameter($operation),
3012
-					'calendartype' => $query->createNamedParameter($calendarType),
3013
-					'created_at' => $query->createNamedParameter(time()),
3014
-				]);
3015
-			foreach ($objectUris as $uri) {
3016
-				$query->setParameter('uri', $uri);
3017
-				$query->executeStatement();
3018
-			}
3019
-
3020
-			$query = $this->db->getQueryBuilder();
3021
-			$query->update($table)
3022
-				->set('synctoken', $query->createNamedParameter($syncToken + 1, IQueryBuilder::PARAM_INT))
3023
-				->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
3024
-				->executeStatement();
3025
-		}, $this->db);
3026
-	}
3027
-
3028
-	public function restoreChanges(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
3029
-		$this->cachedObjects = [];
3030
-
3031
-		$this->atomic(function () use ($calendarId, $calendarType): void {
3032
-			$qbAdded = $this->db->getQueryBuilder();
3033
-			$qbAdded->select('uri')
3034
-				->from('calendarobjects')
3035
-				->where(
3036
-					$qbAdded->expr()->andX(
3037
-						$qbAdded->expr()->eq('calendarid', $qbAdded->createNamedParameter($calendarId)),
3038
-						$qbAdded->expr()->eq('calendartype', $qbAdded->createNamedParameter($calendarType)),
3039
-						$qbAdded->expr()->isNull('deleted_at'),
3040
-					)
3041
-				);
3042
-			$resultAdded = $qbAdded->executeQuery();
3043
-			$addedUris = $resultAdded->fetchAll(\PDO::FETCH_COLUMN);
3044
-			$resultAdded->closeCursor();
3045
-			// Track everything as changed
3046
-			// Tracking the creation is not necessary because \OCA\DAV\CalDAV\CalDavBackend::getChangesForCalendar
3047
-			// only returns the last change per object.
3048
-			$this->addChanges($calendarId, $addedUris, 2, $calendarType);
3049
-
3050
-			$qbDeleted = $this->db->getQueryBuilder();
3051
-			$qbDeleted->select('uri')
3052
-				->from('calendarobjects')
3053
-				->where(
3054
-					$qbDeleted->expr()->andX(
3055
-						$qbDeleted->expr()->eq('calendarid', $qbDeleted->createNamedParameter($calendarId)),
3056
-						$qbDeleted->expr()->eq('calendartype', $qbDeleted->createNamedParameter($calendarType)),
3057
-						$qbDeleted->expr()->isNotNull('deleted_at'),
3058
-					)
3059
-				);
3060
-			$resultDeleted = $qbDeleted->executeQuery();
3061
-			$deletedUris = array_map(function (string $uri) {
3062
-				return str_replace('-deleted.ics', '.ics', $uri);
3063
-			}, $resultDeleted->fetchAll(\PDO::FETCH_COLUMN));
3064
-			$resultDeleted->closeCursor();
3065
-			$this->addChanges($calendarId, $deletedUris, 3, $calendarType);
3066
-		}, $this->db);
3067
-	}
3068
-
3069
-	/**
3070
-	 * Parses some information from calendar objects, used for optimized
3071
-	 * calendar-queries.
3072
-	 *
3073
-	 * Returns an array with the following keys:
3074
-	 *   * etag - An md5 checksum of the object without the quotes.
3075
-	 *   * size - Size of the object in bytes
3076
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
3077
-	 *   * firstOccurence
3078
-	 *   * lastOccurence
3079
-	 *   * uid - value of the UID property
3080
-	 *
3081
-	 * @param string $calendarData
3082
-	 * @return array
3083
-	 */
3084
-	public function getDenormalizedData(string $calendarData): array {
3085
-		$vObject = Reader::read($calendarData);
3086
-		$vEvents = [];
3087
-		$componentType = null;
3088
-		$component = null;
3089
-		$firstOccurrence = null;
3090
-		$lastOccurrence = null;
3091
-		$uid = null;
3092
-		$classification = self::CLASSIFICATION_PUBLIC;
3093
-		$hasDTSTART = false;
3094
-		foreach ($vObject->getComponents() as $component) {
3095
-			if ($component->name !== 'VTIMEZONE') {
3096
-				// Finding all VEVENTs, and track them
3097
-				if ($component->name === 'VEVENT') {
3098
-					$vEvents[] = $component;
3099
-					if ($component->DTSTART) {
3100
-						$hasDTSTART = true;
3101
-					}
3102
-				}
3103
-				// Track first component type and uid
3104
-				if ($uid === null) {
3105
-					$componentType = $component->name;
3106
-					$uid = (string)$component->UID;
3107
-				}
3108
-			}
3109
-		}
3110
-		if (!$componentType) {
3111
-			throw new BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
3112
-		}
3113
-
3114
-		if ($hasDTSTART) {
3115
-			$component = $vEvents[0];
3116
-
3117
-			// Finding the last occurrence is a bit harder
3118
-			if (!isset($component->RRULE) && count($vEvents) === 1) {
3119
-				$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
3120
-				if (isset($component->DTEND)) {
3121
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
3122
-				} elseif (isset($component->DURATION)) {
3123
-					$endDate = clone $component->DTSTART->getDateTime();
3124
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
3125
-					$lastOccurrence = $endDate->getTimeStamp();
3126
-				} elseif (!$component->DTSTART->hasTime()) {
3127
-					$endDate = clone $component->DTSTART->getDateTime();
3128
-					$endDate->modify('+1 day');
3129
-					$lastOccurrence = $endDate->getTimeStamp();
3130
-				} else {
3131
-					$lastOccurrence = $firstOccurrence;
3132
-				}
3133
-			} else {
3134
-				try {
3135
-					$it = new EventIterator($vEvents);
3136
-				} catch (NoInstancesException $e) {
3137
-					$this->logger->debug('Caught no instance exception for calendar data. This usually indicates invalid calendar data.', [
3138
-						'app' => 'dav',
3139
-						'exception' => $e,
3140
-					]);
3141
-					throw new Forbidden($e->getMessage());
3142
-				}
3143
-				$maxDate = new DateTime(self::MAX_DATE);
3144
-				$firstOccurrence = $it->getDtStart()->getTimestamp();
3145
-				if ($it->isInfinite()) {
3146
-					$lastOccurrence = $maxDate->getTimestamp();
3147
-				} else {
3148
-					$end = $it->getDtEnd();
3149
-					while ($it->valid() && $end < $maxDate) {
3150
-						$end = $it->getDtEnd();
3151
-						$it->next();
3152
-					}
3153
-					$lastOccurrence = $end->getTimestamp();
3154
-				}
3155
-			}
3156
-		}
3157
-
3158
-		if ($component->CLASS) {
3159
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
3160
-			switch ($component->CLASS->getValue()) {
3161
-				case 'PUBLIC':
3162
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
3163
-					break;
3164
-				case 'CONFIDENTIAL':
3165
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
3166
-					break;
3167
-			}
3168
-		}
3169
-		return [
3170
-			'etag' => md5($calendarData),
3171
-			'size' => strlen($calendarData),
3172
-			'componentType' => $componentType,
3173
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
3174
-			'lastOccurence' => is_null($lastOccurrence) ? null : max(0, $lastOccurrence),
3175
-			'uid' => $uid,
3176
-			'classification' => $classification
3177
-		];
3178
-	}
3179
-
3180
-	/**
3181
-	 * @param $cardData
3182
-	 * @return bool|string
3183
-	 */
3184
-	private function readBlob($cardData) {
3185
-		if (is_resource($cardData)) {
3186
-			return stream_get_contents($cardData);
3187
-		}
3188
-
3189
-		return $cardData;
3190
-	}
3191
-
3192
-	/**
3193
-	 * @param list<array{href: string, commonName: string, readOnly: bool}> $add
3194
-	 * @param list<string> $remove
3195
-	 */
3196
-	public function updateShares(IShareable $shareable, array $add, array $remove): void {
3197
-		$this->atomic(function () use ($shareable, $add, $remove): void {
3198
-			$calendarId = $shareable->getResourceId();
3199
-			$calendarRow = $this->getCalendarById($calendarId);
3200
-			if ($calendarRow === null) {
3201
-				throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $calendarId);
3202
-			}
3203
-			$oldShares = $this->getShares($calendarId);
3204
-
3205
-			$this->calendarSharingBackend->updateShares($shareable, $add, $remove, $oldShares);
3206
-
3207
-			$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent($calendarId, $calendarRow, $oldShares, $add, $remove));
3208
-		}, $this->db);
3209
-	}
3210
-
3211
-	/**
3212
-	 * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
3213
-	 */
3214
-	public function getShares(int $resourceId): array {
3215
-		return $this->calendarSharingBackend->getShares($resourceId);
3216
-	}
3217
-
3218
-	public function getSharesByShareePrincipal(string $principal): array {
3219
-		return $this->calendarSharingBackend->getSharesByShareePrincipal($principal);
3220
-	}
3221
-
3222
-	public function preloadShares(array $resourceIds): void {
3223
-		$this->calendarSharingBackend->preloadShares($resourceIds);
3224
-	}
3225
-
3226
-	/**
3227
-	 * @param boolean $value
3228
-	 * @param Calendar $calendar
3229
-	 * @return string|null
3230
-	 */
3231
-	public function setPublishStatus($value, $calendar) {
3232
-		$publishStatus = $this->atomic(function () use ($value, $calendar) {
3233
-			$calendarId = $calendar->getResourceId();
3234
-			$calendarData = $this->getCalendarById($calendarId);
3235
-
3236
-			$query = $this->db->getQueryBuilder();
3237
-			if ($value) {
3238
-				$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
3239
-				$query->insert('dav_shares')
3240
-					->values([
3241
-						'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
3242
-						'type' => $query->createNamedParameter('calendar'),
3243
-						'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
3244
-						'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
3245
-						'publicuri' => $query->createNamedParameter($publicUri)
3246
-					]);
3247
-				$query->executeStatement();
3248
-
3249
-				$this->dispatcher->dispatchTyped(new CalendarPublishedEvent($calendarId, $calendarData, $publicUri));
3250
-				return $publicUri;
3251
-			}
3252
-			$query->delete('dav_shares')
3253
-				->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3254
-				->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
3255
-			$query->executeStatement();
3256
-
3257
-			$this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent($calendarId, $calendarData));
3258
-			return null;
3259
-		}, $this->db);
3260
-
3261
-		$this->publishStatusCache->set((string)$calendar->getResourceId(), $publishStatus ?? false);
3262
-		return $publishStatus;
3263
-	}
3264
-
3265
-	/**
3266
-	 * @param Calendar $calendar
3267
-	 * @return string|false
3268
-	 */
3269
-	public function getPublishStatus($calendar) {
3270
-		$cached = $this->publishStatusCache->get((string)$calendar->getResourceId());
3271
-		if ($cached !== null) {
3272
-			return $cached;
3273
-		}
3274
-
3275
-		$query = $this->db->getQueryBuilder();
3276
-		$result = $query->select('publicuri')
3277
-			->from('dav_shares')
3278
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3279
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
3280
-			->executeQuery();
3281
-
3282
-		$publishStatus = $result->fetchOne();
3283
-		$result->closeCursor();
3284
-
3285
-		$this->publishStatusCache->set((string)$calendar->getResourceId(), $publishStatus);
3286
-		return $publishStatus;
3287
-	}
3288
-
3289
-	/**
3290
-	 * @param int[] $resourceIds
3291
-	 */
3292
-	public function preloadPublishStatuses(array $resourceIds): void {
3293
-		$query = $this->db->getQueryBuilder();
3294
-		$result = $query->select('resourceid', 'publicuri')
3295
-			->from('dav_shares')
3296
-			->where($query->expr()->in(
3297
-				'resourceid',
3298
-				$query->createNamedParameter($resourceIds, IQueryBuilder::PARAM_INT_ARRAY),
3299
-				IQueryBuilder::PARAM_INT_ARRAY,
3300
-			))
3301
-			->andWhere($query->expr()->eq(
3302
-				'access',
3303
-				$query->createNamedParameter(self::ACCESS_PUBLIC, IQueryBuilder::PARAM_INT),
3304
-				IQueryBuilder::PARAM_INT,
3305
-			))
3306
-			->executeQuery();
3307
-
3308
-		$hasPublishStatuses = [];
3309
-		while ($row = $result->fetch()) {
3310
-			$this->publishStatusCache->set((string)$row['resourceid'], $row['publicuri']);
3311
-			$hasPublishStatuses[(int)$row['resourceid']] = true;
3312
-		}
3313
-
3314
-		// Also remember resources with no publish status
3315
-		foreach ($resourceIds as $resourceId) {
3316
-			if (!isset($hasPublishStatuses[$resourceId])) {
3317
-				$this->publishStatusCache->set((string)$resourceId, false);
3318
-			}
3319
-		}
3320
-
3321
-		$result->closeCursor();
3322
-	}
3323
-
3324
-	/**
3325
-	 * @param int $resourceId
3326
-	 * @param list<array{privilege: string, principal: string, protected: bool}> $acl
3327
-	 * @return list<array{privilege: string, principal: string, protected: bool}>
3328
-	 */
3329
-	public function applyShareAcl(int $resourceId, array $acl): array {
3330
-		$shares = $this->calendarSharingBackend->getShares($resourceId);
3331
-		return $this->calendarSharingBackend->applyShareAcl($shares, $acl);
3332
-	}
3333
-
3334
-	/**
3335
-	 * update properties table
3336
-	 *
3337
-	 * @param int $calendarId
3338
-	 * @param string $objectUri
3339
-	 * @param string $calendarData
3340
-	 * @param int $calendarType
3341
-	 */
3342
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
3343
-		$this->cachedObjects = [];
3344
-		$this->atomic(function () use ($calendarId, $objectUri, $calendarData, $calendarType): void {
3345
-			$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
3346
-
3347
-			try {
3348
-				$vCalendar = $this->readCalendarData($calendarData);
3349
-			} catch (\Exception $ex) {
3350
-				return;
3351
-			}
3352
-
3353
-			$this->purgeProperties($calendarId, $objectId);
3354
-
3355
-			$query = $this->db->getQueryBuilder();
3356
-			$query->insert($this->dbObjectPropertiesTable)
3357
-				->values(
3358
-					[
3359
-						'calendarid' => $query->createNamedParameter($calendarId),
3360
-						'calendartype' => $query->createNamedParameter($calendarType),
3361
-						'objectid' => $query->createNamedParameter($objectId),
3362
-						'name' => $query->createParameter('name'),
3363
-						'parameter' => $query->createParameter('parameter'),
3364
-						'value' => $query->createParameter('value'),
3365
-					]
3366
-				);
3367
-
3368
-			$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
3369
-			foreach ($vCalendar->getComponents() as $component) {
3370
-				if (!in_array($component->name, $indexComponents)) {
3371
-					continue;
3372
-				}
3373
-
3374
-				foreach ($component->children() as $property) {
3375
-					if (in_array($property->name, self::INDEXED_PROPERTIES, true)) {
3376
-						$value = $property->getValue();
3377
-						// is this a shitty db?
3378
-						if (!$this->db->supports4ByteText()) {
3379
-							$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3380
-						}
3381
-						$value = mb_strcut($value, 0, 254);
3382
-
3383
-						$query->setParameter('name', $property->name);
3384
-						$query->setParameter('parameter', null);
3385
-						$query->setParameter('value', mb_strcut($value, 0, 254));
3386
-						$query->executeStatement();
3387
-					}
3388
-
3389
-					if (array_key_exists($property->name, self::$indexParameters)) {
3390
-						$parameters = $property->parameters();
3391
-						$indexedParametersForProperty = self::$indexParameters[$property->name];
3392
-
3393
-						foreach ($parameters as $key => $value) {
3394
-							if (in_array($key, $indexedParametersForProperty)) {
3395
-								// is this a shitty db?
3396
-								if ($this->db->supports4ByteText()) {
3397
-									$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3398
-								}
3399
-
3400
-								$query->setParameter('name', $property->name);
3401
-								$query->setParameter('parameter', mb_strcut($key, 0, 254));
3402
-								$query->setParameter('value', mb_strcut($value, 0, 254));
3403
-								$query->executeStatement();
3404
-							}
3405
-						}
3406
-					}
3407
-				}
3408
-			}
3409
-		}, $this->db);
3410
-	}
3411
-
3412
-	/**
3413
-	 * deletes all birthday calendars
3414
-	 */
3415
-	public function deleteAllBirthdayCalendars() {
3416
-		$this->atomic(function (): void {
3417
-			$query = $this->db->getQueryBuilder();
3418
-			$result = $query->select(['id'])->from('calendars')
3419
-				->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
3420
-				->executeQuery();
3421
-
3422
-			while (($row = $result->fetch()) !== false) {
3423
-				$this->deleteCalendar(
3424
-					$row['id'],
3425
-					true // No data to keep in the trashbin, if the user re-enables then we regenerate
3426
-				);
3427
-			}
3428
-			$result->closeCursor();
3429
-		}, $this->db);
3430
-	}
3431
-
3432
-	/**
3433
-	 * @param $subscriptionId
3434
-	 */
3435
-	public function purgeAllCachedEventsForSubscription($subscriptionId) {
3436
-		$this->atomic(function () use ($subscriptionId): void {
3437
-			$query = $this->db->getQueryBuilder();
3438
-			$query->select('uri')
3439
-				->from('calendarobjects')
3440
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3441
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
3442
-			$stmt = $query->executeQuery();
3443
-
3444
-			$uris = [];
3445
-			while (($row = $stmt->fetch()) !== false) {
3446
-				$uris[] = $row['uri'];
3447
-			}
3448
-			$stmt->closeCursor();
3449
-
3450
-			$query = $this->db->getQueryBuilder();
3451
-			$query->delete('calendarobjects')
3452
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3453
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3454
-				->executeStatement();
3455
-
3456
-			$query = $this->db->getQueryBuilder();
3457
-			$query->delete('calendarchanges')
3458
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3459
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3460
-				->executeStatement();
3461
-
3462
-			$query = $this->db->getQueryBuilder();
3463
-			$query->delete($this->dbObjectPropertiesTable)
3464
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3465
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3466
-				->executeStatement();
3467
-
3468
-			$this->addChanges($subscriptionId, $uris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3469
-		}, $this->db);
3470
-	}
3471
-
3472
-	/**
3473
-	 * @param int $subscriptionId
3474
-	 * @param array<int> $calendarObjectIds
3475
-	 * @param array<string> $calendarObjectUris
3476
-	 */
3477
-	public function purgeCachedEventsForSubscription(int $subscriptionId, array $calendarObjectIds, array $calendarObjectUris): void {
3478
-		if (empty($calendarObjectUris)) {
3479
-			return;
3480
-		}
3481
-
3482
-		$this->atomic(function () use ($subscriptionId, $calendarObjectIds, $calendarObjectUris): void {
3483
-			foreach (array_chunk($calendarObjectIds, 1000) as $chunk) {
3484
-				$query = $this->db->getQueryBuilder();
3485
-				$query->delete($this->dbObjectPropertiesTable)
3486
-					->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3487
-					->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3488
-					->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3489
-					->executeStatement();
3490
-
3491
-				$query = $this->db->getQueryBuilder();
3492
-				$query->delete('calendarobjects')
3493
-					->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3494
-					->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3495
-					->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3496
-					->executeStatement();
3497
-			}
3498
-
3499
-			foreach (array_chunk($calendarObjectUris, 1000) as $chunk) {
3500
-				$query = $this->db->getQueryBuilder();
3501
-				$query->delete('calendarchanges')
3502
-					->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3503
-					->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3504
-					->andWhere($query->expr()->in('uri', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
3505
-					->executeStatement();
3506
-			}
3507
-			$this->addChanges($subscriptionId, $calendarObjectUris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3508
-		}, $this->db);
3509
-	}
3510
-
3511
-	/**
3512
-	 * Move a calendar from one user to another
3513
-	 *
3514
-	 * @param string $uriName
3515
-	 * @param string $uriOrigin
3516
-	 * @param string $uriDestination
3517
-	 * @param string $newUriName (optional) the new uriName
3518
-	 */
3519
-	public function moveCalendar($uriName, $uriOrigin, $uriDestination, $newUriName = null) {
3520
-		$query = $this->db->getQueryBuilder();
3521
-		$query->update('calendars')
3522
-			->set('principaluri', $query->createNamedParameter($uriDestination))
3523
-			->set('uri', $query->createNamedParameter($newUriName ?: $uriName))
3524
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
3525
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
3526
-			->executeStatement();
3527
-	}
3528
-
3529
-	/**
3530
-	 * read VCalendar data into a VCalendar object
3531
-	 *
3532
-	 * @param string $objectData
3533
-	 * @return VCalendar
3534
-	 */
3535
-	protected function readCalendarData($objectData) {
3536
-		return Reader::read($objectData);
3537
-	}
3538
-
3539
-	/**
3540
-	 * delete all properties from a given calendar object
3541
-	 *
3542
-	 * @param int $calendarId
3543
-	 * @param int $objectId
3544
-	 */
3545
-	protected function purgeProperties($calendarId, $objectId) {
3546
-		$this->cachedObjects = [];
3547
-		$query = $this->db->getQueryBuilder();
3548
-		$query->delete($this->dbObjectPropertiesTable)
3549
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
3550
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
3551
-		$query->executeStatement();
3552
-	}
3553
-
3554
-	/**
3555
-	 * get ID from a given calendar object
3556
-	 *
3557
-	 * @param int $calendarId
3558
-	 * @param string $uri
3559
-	 * @param int $calendarType
3560
-	 * @return int
3561
-	 */
3562
-	protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
3563
-		$query = $this->db->getQueryBuilder();
3564
-		$query->select('id')
3565
-			->from('calendarobjects')
3566
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
3567
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
3568
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
3569
-
3570
-		$result = $query->executeQuery();
3571
-		$objectIds = $result->fetch();
3572
-		$result->closeCursor();
3573
-
3574
-		if (!isset($objectIds['id'])) {
3575
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
3576
-		}
3577
-
3578
-		return (int)$objectIds['id'];
3579
-	}
3580
-
3581
-	/**
3582
-	 * @throws \InvalidArgumentException
3583
-	 */
3584
-	public function pruneOutdatedSyncTokens(int $keep, int $retention): int {
3585
-		if ($keep < 0) {
3586
-			throw new \InvalidArgumentException();
3587
-		}
3588
-
3589
-		$query = $this->db->getQueryBuilder();
3590
-		$query->select($query->func()->max('id'))
3591
-			->from('calendarchanges');
3592
-
3593
-		$result = $query->executeQuery();
3594
-		$maxId = (int)$result->fetchOne();
3595
-		$result->closeCursor();
3596
-		if (!$maxId || $maxId < $keep) {
3597
-			return 0;
3598
-		}
3599
-
3600
-		$query = $this->db->getQueryBuilder();
3601
-		$query->delete('calendarchanges')
3602
-			->where(
3603
-				$query->expr()->lte('id', $query->createNamedParameter($maxId - $keep, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
3604
-				$query->expr()->lte('created_at', $query->createNamedParameter($retention)),
3605
-			);
3606
-		return $query->executeStatement();
3607
-	}
3608
-
3609
-	/**
3610
-	 * return legacy endpoint principal name to new principal name
3611
-	 *
3612
-	 * @param $principalUri
3613
-	 * @param $toV2
3614
-	 * @return string
3615
-	 */
3616
-	private function convertPrincipal($principalUri, $toV2) {
3617
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
3618
-			[, $name] = Uri\split($principalUri);
3619
-			if ($toV2 === true) {
3620
-				return "principals/users/$name";
3621
-			}
3622
-			return "principals/$name";
3623
-		}
3624
-		return $principalUri;
3625
-	}
3626
-
3627
-	/**
3628
-	 * adds information about an owner to the calendar data
3629
-	 *
3630
-	 */
3631
-	private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
3632
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
3633
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
3634
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
3635
-			$uri = $calendarInfo[$ownerPrincipalKey];
3636
-		} else {
3637
-			$uri = $calendarInfo['principaluri'];
3638
-		}
3639
-
3640
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
3641
-		if (isset($principalInformation['{DAV:}displayname'])) {
3642
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
3643
-		}
3644
-		return $calendarInfo;
3645
-	}
3646
-
3647
-	private function addResourceTypeToCalendar(array $row, array $calendar): array {
3648
-		if (isset($row['deleted_at'])) {
3649
-			// Columns is set and not null -> this is a deleted calendar
3650
-			// we send a custom resourcetype to hide the deleted calendar
3651
-			// from ordinary DAV clients, but the Calendar app will know
3652
-			// how to handle this special resource.
3653
-			$calendar['{DAV:}resourcetype'] = new DAV\Xml\Property\ResourceType([
3654
-				'{DAV:}collection',
3655
-				sprintf('{%s}deleted-calendar', \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD),
3656
-			]);
3657
-		}
3658
-		return $calendar;
3659
-	}
3660
-
3661
-	/**
3662
-	 * Amend the calendar info with database row data
3663
-	 *
3664
-	 * @param array $row
3665
-	 * @param array $calendar
3666
-	 *
3667
-	 * @return array
3668
-	 */
3669
-	private function rowToCalendar($row, array $calendar): array {
3670
-		foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
3671
-			$value = $row[$dbName];
3672
-			if ($value !== null) {
3673
-				settype($value, $type);
3674
-			}
3675
-			$calendar[$xmlName] = $value;
3676
-		}
3677
-		return $calendar;
3678
-	}
3679
-
3680
-	/**
3681
-	 * Amend the subscription info with database row data
3682
-	 *
3683
-	 * @param array $row
3684
-	 * @param array $subscription
3685
-	 *
3686
-	 * @return array
3687
-	 */
3688
-	private function rowToSubscription($row, array $subscription): array {
3689
-		foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
3690
-			$value = $row[$dbName];
3691
-			if ($value !== null) {
3692
-				settype($value, $type);
3693
-			}
3694
-			$subscription[$xmlName] = $value;
3695
-		}
3696
-		return $subscription;
3697
-	}
3698
-
3699
-	/**
3700
-	 * delete all invitations from a given calendar
3701
-	 *
3702
-	 * @since 31.0.0
3703
-	 *
3704
-	 * @param int $calendarId
3705
-	 *
3706
-	 * @return void
3707
-	 */
3708
-	protected function purgeCalendarInvitations(int $calendarId): void {
3709
-		// select all calendar object uid's
3710
-		$cmd = $this->db->getQueryBuilder();
3711
-		$cmd->select('uid')
3712
-			->from($this->dbObjectsTable)
3713
-			->where($cmd->expr()->eq('calendarid', $cmd->createNamedParameter($calendarId)));
3714
-		$allIds = $cmd->executeQuery()->fetchAll(\PDO::FETCH_COLUMN);
3715
-		// delete all links that match object uid's
3716
-		$cmd = $this->db->getQueryBuilder();
3717
-		$cmd->delete($this->dbObjectInvitationsTable)
3718
-			->where($cmd->expr()->in('uid', $cmd->createParameter('uids'), IQueryBuilder::PARAM_STR_ARRAY));
3719
-		foreach (array_chunk($allIds, 1000) as $chunkIds) {
3720
-			$cmd->setParameter('uids', $chunkIds, IQueryBuilder::PARAM_STR_ARRAY);
3721
-			$cmd->executeStatement();
3722
-		}
3723
-	}
3724
-
3725
-	/**
3726
-	 * Delete all invitations from a given calendar event
3727
-	 *
3728
-	 * @since 31.0.0
3729
-	 *
3730
-	 * @param string $eventId UID of the event
3731
-	 *
3732
-	 * @return void
3733
-	 */
3734
-	protected function purgeObjectInvitations(string $eventId): void {
3735
-		$cmd = $this->db->getQueryBuilder();
3736
-		$cmd->delete($this->dbObjectInvitationsTable)
3737
-			->where($cmd->expr()->eq('uid', $cmd->createNamedParameter($eventId, IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR));
3738
-		$cmd->executeStatement();
3739
-	}
3740
-
3741
-	public function unshare(IShareable $shareable, string $principal): void {
3742
-		$this->atomic(function () use ($shareable, $principal): void {
3743
-			$calendarData = $this->getCalendarById($shareable->getResourceId());
3744
-			if ($calendarData === null) {
3745
-				throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $shareable->getResourceId());
3746
-			}
3747
-
3748
-			$oldShares = $this->getShares($shareable->getResourceId());
3749
-			$unshare = $this->calendarSharingBackend->unshare($shareable, $principal);
3750
-
3751
-			if ($unshare) {
3752
-				$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent(
3753
-					$shareable->getResourceId(),
3754
-					$calendarData,
3755
-					$oldShares,
3756
-					[],
3757
-					[$principal]
3758
-				));
3759
-			}
3760
-		}, $this->db);
3761
-	}
3762
-
3763
-	/**
3764
-	 * @return array<string, mixed>[]
3765
-	 */
3766
-	public function getFederatedCalendarsForUser(string $principalUri): array {
3767
-		$federatedCalendars = $this->federatedCalendarMapper->findByPrincipalUri($principalUri);
3768
-		return array_map(
3769
-			static fn (FederatedCalendarEntity $entity) => $entity->toCalendarInfo(),
3770
-			$federatedCalendars,
3771
-		);
3772
-	}
3773
-
3774
-	public function getFederatedCalendarByUri(string $principalUri, string $uri): ?array {
3775
-		$federatedCalendar = $this->federatedCalendarMapper->findByUri($principalUri, $uri);
3776
-		return $federatedCalendar?->toCalendarInfo();
3777
-	}
113
+    use TTransactional;
114
+
115
+    public const CALENDAR_TYPE_CALENDAR = 0;
116
+    public const CALENDAR_TYPE_SUBSCRIPTION = 1;
117
+    public const CALENDAR_TYPE_FEDERATED = 2;
118
+
119
+    public const PERSONAL_CALENDAR_URI = 'personal';
120
+    public const PERSONAL_CALENDAR_NAME = 'Personal';
121
+
122
+    public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
123
+    public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
124
+
125
+    /**
126
+     * We need to specify a max date, because we need to stop *somewhere*
127
+     *
128
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
129
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
130
+     * in 2038-01-19 to avoid problems when the date is converted
131
+     * to a unix timestamp.
132
+     */
133
+    public const MAX_DATE = '2038-01-01';
134
+
135
+    public const ACCESS_PUBLIC = 4;
136
+    public const CLASSIFICATION_PUBLIC = 0;
137
+    public const CLASSIFICATION_PRIVATE = 1;
138
+    public const CLASSIFICATION_CONFIDENTIAL = 2;
139
+
140
+    /**
141
+     * List of CalDAV properties, and how they map to database field names and their type
142
+     * Add your own properties by simply adding on to this array.
143
+     *
144
+     * @var array
145
+     * @psalm-var array<string, string[]>
146
+     */
147
+    public array $propertyMap = [
148
+        '{DAV:}displayname' => ['displayname', 'string'],
149
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => ['description', 'string'],
150
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => ['timezone', 'string'],
151
+        '{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
152
+        '{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
153
+        '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => ['deleted_at', 'int'],
154
+    ];
155
+
156
+    /**
157
+     * List of subscription properties, and how they map to database field names.
158
+     *
159
+     * @var array
160
+     */
161
+    public array $subscriptionPropertyMap = [
162
+        '{DAV:}displayname' => ['displayname', 'string'],
163
+        '{http://apple.com/ns/ical/}refreshrate' => ['refreshrate', 'string'],
164
+        '{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
165
+        '{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
166
+        '{http://calendarserver.org/ns/}subscribed-strip-todos' => ['striptodos', 'bool'],
167
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms' => ['stripalarms', 'string'],
168
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => ['stripattachments', 'string'],
169
+    ];
170
+
171
+    /**
172
+     * properties to index
173
+     *
174
+     * This list has to be kept in sync with ICalendarQuery::SEARCH_PROPERTY_*
175
+     *
176
+     * @see \OCP\Calendar\ICalendarQuery
177
+     */
178
+    private const INDEXED_PROPERTIES = [
179
+        'CATEGORIES',
180
+        'COMMENT',
181
+        'DESCRIPTION',
182
+        'LOCATION',
183
+        'RESOURCES',
184
+        'STATUS',
185
+        'SUMMARY',
186
+        'ATTENDEE',
187
+        'CONTACT',
188
+        'ORGANIZER'
189
+    ];
190
+
191
+    /** @var array parameters to index */
192
+    public static array $indexParameters = [
193
+        'ATTENDEE' => ['CN'],
194
+        'ORGANIZER' => ['CN'],
195
+    ];
196
+
197
+    /**
198
+     * @var string[] Map of uid => display name
199
+     */
200
+    protected array $userDisplayNames;
201
+
202
+    private string $dbObjectsTable = 'calendarobjects';
203
+    private string $dbObjectPropertiesTable = 'calendarobjects_props';
204
+    private string $dbObjectInvitationsTable = 'calendar_invitations';
205
+    private array $cachedObjects = [];
206
+
207
+    private readonly ICache $publishStatusCache;
208
+
209
+    public function __construct(
210
+        private IDBConnection $db,
211
+        private Principal $principalBackend,
212
+        private IUserManager $userManager,
213
+        private ISecureRandom $random,
214
+        private LoggerInterface $logger,
215
+        private IEventDispatcher $dispatcher,
216
+        private IConfig $config,
217
+        private Sharing\Backend $calendarSharingBackend,
218
+        private FederatedCalendarMapper $federatedCalendarMapper,
219
+        ICacheFactory $cacheFactory,
220
+        private bool $legacyEndpoint = false,
221
+    ) {
222
+        $this->publishStatusCache = $cacheFactory->createInMemory();
223
+    }
224
+
225
+    /**
226
+     * Return the number of calendars owned by the given principal.
227
+     *
228
+     * Calendars shared with the given principal are not counted!
229
+     *
230
+     * By default, this excludes the automatically generated birthday calendar.
231
+     */
232
+    public function getCalendarsForUserCount(string $principalUri, bool $excludeBirthday = true): int {
233
+        $principalUri = $this->convertPrincipal($principalUri, true);
234
+        $query = $this->db->getQueryBuilder();
235
+        $query->select($query->func()->count('*'))
236
+            ->from('calendars');
237
+
238
+        if ($principalUri === '') {
239
+            $query->where($query->expr()->emptyString('principaluri'));
240
+        } else {
241
+            $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
242
+        }
243
+
244
+        if ($excludeBirthday) {
245
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
246
+        }
247
+
248
+        $result = $query->executeQuery();
249
+        $column = (int)$result->fetchOne();
250
+        $result->closeCursor();
251
+        return $column;
252
+    }
253
+
254
+    /**
255
+     * Return the number of subscriptions for a principal
256
+     */
257
+    public function getSubscriptionsForUserCount(string $principalUri): int {
258
+        $principalUri = $this->convertPrincipal($principalUri, true);
259
+        $query = $this->db->getQueryBuilder();
260
+        $query->select($query->func()->count('*'))
261
+            ->from('calendarsubscriptions');
262
+
263
+        if ($principalUri === '') {
264
+            $query->where($query->expr()->emptyString('principaluri'));
265
+        } else {
266
+            $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
267
+        }
268
+
269
+        $result = $query->executeQuery();
270
+        $column = (int)$result->fetchOne();
271
+        $result->closeCursor();
272
+        return $column;
273
+    }
274
+
275
+    /**
276
+     * @return array{id: int, deleted_at: int}[]
277
+     */
278
+    public function getDeletedCalendars(int $deletedBefore): array {
279
+        $qb = $this->db->getQueryBuilder();
280
+        $qb->select(['id', 'deleted_at'])
281
+            ->from('calendars')
282
+            ->where($qb->expr()->isNotNull('deleted_at'))
283
+            ->andWhere($qb->expr()->lt('deleted_at', $qb->createNamedParameter($deletedBefore)));
284
+        $result = $qb->executeQuery();
285
+        $calendars = [];
286
+        while (($row = $result->fetch()) !== false) {
287
+            $calendars[] = [
288
+                'id' => (int)$row['id'],
289
+                'deleted_at' => (int)$row['deleted_at'],
290
+            ];
291
+        }
292
+        $result->closeCursor();
293
+        return $calendars;
294
+    }
295
+
296
+    /**
297
+     * Returns a list of calendars for a principal.
298
+     *
299
+     * Every project is an array with the following keys:
300
+     *  * id, a unique id that will be used by other functions to modify the
301
+     *    calendar. This can be the same as the uri or a database key.
302
+     *  * uri, which the basename of the uri with which the calendar is
303
+     *    accessed.
304
+     *  * principaluri. The owner of the calendar. Almost always the same as
305
+     *    principalUri passed to this method.
306
+     *
307
+     * Furthermore it can contain webdav properties in clark notation. A very
308
+     * common one is '{DAV:}displayname'.
309
+     *
310
+     * Many clients also require:
311
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
312
+     * For this property, you can just return an instance of
313
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
314
+     *
315
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
316
+     * ACL will automatically be put in read-only mode.
317
+     *
318
+     * @param string $principalUri
319
+     * @return array
320
+     */
321
+    public function getCalendarsForUser($principalUri) {
322
+        return $this->atomic(function () use ($principalUri) {
323
+            $principalUriOriginal = $principalUri;
324
+            $principalUri = $this->convertPrincipal($principalUri, true);
325
+            $fields = array_column($this->propertyMap, 0);
326
+            $fields[] = 'id';
327
+            $fields[] = 'uri';
328
+            $fields[] = 'synctoken';
329
+            $fields[] = 'components';
330
+            $fields[] = 'principaluri';
331
+            $fields[] = 'transparent';
332
+
333
+            // Making fields a comma-delimited list
334
+            $query = $this->db->getQueryBuilder();
335
+            $query->select($fields)
336
+                ->from('calendars')
337
+                ->orderBy('calendarorder', 'ASC');
338
+
339
+            if ($principalUri === '') {
340
+                $query->where($query->expr()->emptyString('principaluri'));
341
+            } else {
342
+                $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
343
+            }
344
+
345
+            $result = $query->executeQuery();
346
+
347
+            $calendars = [];
348
+            while ($row = $result->fetch()) {
349
+                $row['principaluri'] = (string)$row['principaluri'];
350
+                $components = [];
351
+                if ($row['components']) {
352
+                    $components = explode(',', $row['components']);
353
+                }
354
+
355
+                $calendar = [
356
+                    'id' => $row['id'],
357
+                    'uri' => $row['uri'],
358
+                    'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
359
+                    '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
360
+                    '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
361
+                    '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
362
+                    '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
363
+                    '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
364
+                ];
365
+
366
+                $calendar = $this->rowToCalendar($row, $calendar);
367
+                $calendar = $this->addOwnerPrincipalToCalendar($calendar);
368
+                $calendar = $this->addResourceTypeToCalendar($row, $calendar);
369
+
370
+                if (!isset($calendars[$calendar['id']])) {
371
+                    $calendars[$calendar['id']] = $calendar;
372
+                }
373
+            }
374
+            $result->closeCursor();
375
+
376
+            // query for shared calendars
377
+            $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
378
+            $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
379
+            $principals[] = $principalUri;
380
+
381
+            $fields = array_column($this->propertyMap, 0);
382
+            $fields = array_map(function (string $field) {
383
+                return 'a.' . $field;
384
+            }, $fields);
385
+            $fields[] = 'a.id';
386
+            $fields[] = 'a.uri';
387
+            $fields[] = 'a.synctoken';
388
+            $fields[] = 'a.components';
389
+            $fields[] = 'a.principaluri';
390
+            $fields[] = 'a.transparent';
391
+            $fields[] = 's.access';
392
+
393
+            $select = $this->db->getQueryBuilder();
394
+            $subSelect = $this->db->getQueryBuilder();
395
+
396
+            $subSelect->select('resourceid')
397
+                ->from('dav_shares', 'd')
398
+                ->where($subSelect->expr()->eq('d.access', $select->createNamedParameter(Backend::ACCESS_UNSHARED, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
399
+                ->andWhere($subSelect->expr()->in('d.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY));
400
+
401
+            $select->select($fields)
402
+                ->from('dav_shares', 's')
403
+                ->join('s', 'calendars', 'a', $select->expr()->eq('s.resourceid', 'a.id', IQueryBuilder::PARAM_INT))
404
+                ->where($select->expr()->in('s.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
405
+                ->andWhere($select->expr()->eq('s.type', $select->createNamedParameter('calendar', IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR))
406
+                ->andWhere($select->expr()->notIn('a.id', $select->createFunction($subSelect->getSQL()), IQueryBuilder::PARAM_INT_ARRAY));
407
+
408
+            $results = $select->executeQuery();
409
+
410
+            $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
411
+            while ($row = $results->fetch()) {
412
+                $row['principaluri'] = (string)$row['principaluri'];
413
+                if ($row['principaluri'] === $principalUri) {
414
+                    continue;
415
+                }
416
+
417
+                $readOnly = (int)$row['access'] === Backend::ACCESS_READ;
418
+                if (isset($calendars[$row['id']])) {
419
+                    if ($readOnly) {
420
+                        // New share can not have more permissions than the old one.
421
+                        continue;
422
+                    }
423
+                    if (isset($calendars[$row['id']][$readOnlyPropertyName])
424
+                        && $calendars[$row['id']][$readOnlyPropertyName] === 0) {
425
+                        // Old share is already read-write, no more permissions can be gained
426
+                        continue;
427
+                    }
428
+                }
429
+
430
+                [, $name] = Uri\split($row['principaluri']);
431
+                $uri = $row['uri'] . '_shared_by_' . $name;
432
+                $row['displayname'] = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? ($name ?? '')) . ')';
433
+                $components = [];
434
+                if ($row['components']) {
435
+                    $components = explode(',', $row['components']);
436
+                }
437
+                $calendar = [
438
+                    'id' => $row['id'],
439
+                    'uri' => $uri,
440
+                    'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
441
+                    '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
442
+                    '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
443
+                    '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
444
+                    '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
445
+                    '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
446
+                    $readOnlyPropertyName => $readOnly,
447
+                ];
448
+
449
+                $calendar = $this->rowToCalendar($row, $calendar);
450
+                $calendar = $this->addOwnerPrincipalToCalendar($calendar);
451
+                $calendar = $this->addResourceTypeToCalendar($row, $calendar);
452
+
453
+                $calendars[$calendar['id']] = $calendar;
454
+            }
455
+            $result->closeCursor();
456
+
457
+            return array_values($calendars);
458
+        }, $this->db);
459
+    }
460
+
461
+    /**
462
+     * @param $principalUri
463
+     * @return array
464
+     */
465
+    public function getUsersOwnCalendars($principalUri) {
466
+        $principalUri = $this->convertPrincipal($principalUri, true);
467
+        $fields = array_column($this->propertyMap, 0);
468
+        $fields[] = 'id';
469
+        $fields[] = 'uri';
470
+        $fields[] = 'synctoken';
471
+        $fields[] = 'components';
472
+        $fields[] = 'principaluri';
473
+        $fields[] = 'transparent';
474
+        // Making fields a comma-delimited list
475
+        $query = $this->db->getQueryBuilder();
476
+        $query->select($fields)->from('calendars')
477
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
478
+            ->orderBy('calendarorder', 'ASC');
479
+        $stmt = $query->executeQuery();
480
+        $calendars = [];
481
+        while ($row = $stmt->fetch()) {
482
+            $row['principaluri'] = (string)$row['principaluri'];
483
+            $components = [];
484
+            if ($row['components']) {
485
+                $components = explode(',', $row['components']);
486
+            }
487
+            $calendar = [
488
+                'id' => $row['id'],
489
+                'uri' => $row['uri'],
490
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
491
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
492
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
493
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
494
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
495
+            ];
496
+
497
+            $calendar = $this->rowToCalendar($row, $calendar);
498
+            $calendar = $this->addOwnerPrincipalToCalendar($calendar);
499
+            $calendar = $this->addResourceTypeToCalendar($row, $calendar);
500
+
501
+            if (!isset($calendars[$calendar['id']])) {
502
+                $calendars[$calendar['id']] = $calendar;
503
+            }
504
+        }
505
+        $stmt->closeCursor();
506
+        return array_values($calendars);
507
+    }
508
+
509
+    /**
510
+     * @return array
511
+     */
512
+    public function getPublicCalendars() {
513
+        $fields = array_column($this->propertyMap, 0);
514
+        $fields[] = 'a.id';
515
+        $fields[] = 'a.uri';
516
+        $fields[] = 'a.synctoken';
517
+        $fields[] = 'a.components';
518
+        $fields[] = 'a.principaluri';
519
+        $fields[] = 'a.transparent';
520
+        $fields[] = 's.access';
521
+        $fields[] = 's.publicuri';
522
+        $calendars = [];
523
+        $query = $this->db->getQueryBuilder();
524
+        $result = $query->select($fields)
525
+            ->from('dav_shares', 's')
526
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
527
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
528
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
529
+            ->executeQuery();
530
+
531
+        while ($row = $result->fetch()) {
532
+            $row['principaluri'] = (string)$row['principaluri'];
533
+            [, $name] = Uri\split($row['principaluri']);
534
+            $row['displayname'] = $row['displayname'] . "($name)";
535
+            $components = [];
536
+            if ($row['components']) {
537
+                $components = explode(',', $row['components']);
538
+            }
539
+            $calendar = [
540
+                'id' => $row['id'],
541
+                'uri' => $row['publicuri'],
542
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
543
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
544
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
545
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
546
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
547
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
548
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => true,
549
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
550
+            ];
551
+
552
+            $calendar = $this->rowToCalendar($row, $calendar);
553
+            $calendar = $this->addOwnerPrincipalToCalendar($calendar);
554
+            $calendar = $this->addResourceTypeToCalendar($row, $calendar);
555
+
556
+            if (!isset($calendars[$calendar['id']])) {
557
+                $calendars[$calendar['id']] = $calendar;
558
+            }
559
+        }
560
+        $result->closeCursor();
561
+
562
+        return array_values($calendars);
563
+    }
564
+
565
+    /**
566
+     * @param string $uri
567
+     * @return array
568
+     * @throws NotFound
569
+     */
570
+    public function getPublicCalendar($uri) {
571
+        $fields = array_column($this->propertyMap, 0);
572
+        $fields[] = 'a.id';
573
+        $fields[] = 'a.uri';
574
+        $fields[] = 'a.synctoken';
575
+        $fields[] = 'a.components';
576
+        $fields[] = 'a.principaluri';
577
+        $fields[] = 'a.transparent';
578
+        $fields[] = 's.access';
579
+        $fields[] = 's.publicuri';
580
+        $query = $this->db->getQueryBuilder();
581
+        $result = $query->select($fields)
582
+            ->from('dav_shares', 's')
583
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
584
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
585
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
586
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
587
+            ->executeQuery();
588
+
589
+        $row = $result->fetch();
590
+
591
+        $result->closeCursor();
592
+
593
+        if ($row === false) {
594
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
595
+        }
596
+
597
+        $row['principaluri'] = (string)$row['principaluri'];
598
+        [, $name] = Uri\split($row['principaluri']);
599
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
600
+        $components = [];
601
+        if ($row['components']) {
602
+            $components = explode(',', $row['components']);
603
+        }
604
+        $calendar = [
605
+            'id' => $row['id'],
606
+            'uri' => $row['publicuri'],
607
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
608
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
609
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
610
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
611
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
612
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
613
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => true,
614
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
615
+        ];
616
+
617
+        $calendar = $this->rowToCalendar($row, $calendar);
618
+        $calendar = $this->addOwnerPrincipalToCalendar($calendar);
619
+        $calendar = $this->addResourceTypeToCalendar($row, $calendar);
620
+
621
+        return $calendar;
622
+    }
623
+
624
+    /**
625
+     * @param string $principal
626
+     * @param string $uri
627
+     * @return array|null
628
+     */
629
+    public function getCalendarByUri($principal, $uri) {
630
+        $fields = array_column($this->propertyMap, 0);
631
+        $fields[] = 'id';
632
+        $fields[] = 'uri';
633
+        $fields[] = 'synctoken';
634
+        $fields[] = 'components';
635
+        $fields[] = 'principaluri';
636
+        $fields[] = 'transparent';
637
+
638
+        // Making fields a comma-delimited list
639
+        $query = $this->db->getQueryBuilder();
640
+        $query->select($fields)->from('calendars')
641
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
642
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
643
+            ->setMaxResults(1);
644
+        $stmt = $query->executeQuery();
645
+
646
+        $row = $stmt->fetch();
647
+        $stmt->closeCursor();
648
+        if ($row === false) {
649
+            return null;
650
+        }
651
+
652
+        $row['principaluri'] = (string)$row['principaluri'];
653
+        $components = [];
654
+        if ($row['components']) {
655
+            $components = explode(',', $row['components']);
656
+        }
657
+
658
+        $calendar = [
659
+            'id' => $row['id'],
660
+            'uri' => $row['uri'],
661
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
662
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
663
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
664
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
665
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
666
+        ];
667
+
668
+        $calendar = $this->rowToCalendar($row, $calendar);
669
+        $calendar = $this->addOwnerPrincipalToCalendar($calendar);
670
+        $calendar = $this->addResourceTypeToCalendar($row, $calendar);
671
+
672
+        return $calendar;
673
+    }
674
+
675
+    /**
676
+     * @psalm-return CalendarInfo|null
677
+     * @return array|null
678
+     */
679
+    public function getCalendarById(int $calendarId): ?array {
680
+        $fields = array_column($this->propertyMap, 0);
681
+        $fields[] = 'id';
682
+        $fields[] = 'uri';
683
+        $fields[] = 'synctoken';
684
+        $fields[] = 'components';
685
+        $fields[] = 'principaluri';
686
+        $fields[] = 'transparent';
687
+
688
+        // Making fields a comma-delimited list
689
+        $query = $this->db->getQueryBuilder();
690
+        $query->select($fields)->from('calendars')
691
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
692
+            ->setMaxResults(1);
693
+        $stmt = $query->executeQuery();
694
+
695
+        $row = $stmt->fetch();
696
+        $stmt->closeCursor();
697
+        if ($row === false) {
698
+            return null;
699
+        }
700
+
701
+        $row['principaluri'] = (string)$row['principaluri'];
702
+        $components = [];
703
+        if ($row['components']) {
704
+            $components = explode(',', $row['components']);
705
+        }
706
+
707
+        $calendar = [
708
+            'id' => $row['id'],
709
+            'uri' => $row['uri'],
710
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
711
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
712
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?? 0,
713
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
714
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
715
+        ];
716
+
717
+        $calendar = $this->rowToCalendar($row, $calendar);
718
+        $calendar = $this->addOwnerPrincipalToCalendar($calendar);
719
+        $calendar = $this->addResourceTypeToCalendar($row, $calendar);
720
+
721
+        return $calendar;
722
+    }
723
+
724
+    /**
725
+     * @param $subscriptionId
726
+     */
727
+    public function getSubscriptionById($subscriptionId) {
728
+        $fields = array_column($this->subscriptionPropertyMap, 0);
729
+        $fields[] = 'id';
730
+        $fields[] = 'uri';
731
+        $fields[] = 'source';
732
+        $fields[] = 'synctoken';
733
+        $fields[] = 'principaluri';
734
+        $fields[] = 'lastmodified';
735
+
736
+        $query = $this->db->getQueryBuilder();
737
+        $query->select($fields)
738
+            ->from('calendarsubscriptions')
739
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
740
+            ->orderBy('calendarorder', 'asc');
741
+        $stmt = $query->executeQuery();
742
+
743
+        $row = $stmt->fetch();
744
+        $stmt->closeCursor();
745
+        if ($row === false) {
746
+            return null;
747
+        }
748
+
749
+        $row['principaluri'] = (string)$row['principaluri'];
750
+        $subscription = [
751
+            'id' => $row['id'],
752
+            'uri' => $row['uri'],
753
+            'principaluri' => $row['principaluri'],
754
+            'source' => $row['source'],
755
+            'lastmodified' => $row['lastmodified'],
756
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
757
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
758
+        ];
759
+
760
+        return $this->rowToSubscription($row, $subscription);
761
+    }
762
+
763
+    public function getSubscriptionByUri(string $principal, string $uri): ?array {
764
+        $fields = array_column($this->subscriptionPropertyMap, 0);
765
+        $fields[] = 'id';
766
+        $fields[] = 'uri';
767
+        $fields[] = 'source';
768
+        $fields[] = 'synctoken';
769
+        $fields[] = 'principaluri';
770
+        $fields[] = 'lastmodified';
771
+
772
+        $query = $this->db->getQueryBuilder();
773
+        $query->select($fields)
774
+            ->from('calendarsubscriptions')
775
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
776
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
777
+            ->setMaxResults(1);
778
+        $stmt = $query->executeQuery();
779
+
780
+        $row = $stmt->fetch();
781
+        $stmt->closeCursor();
782
+        if ($row === false) {
783
+            return null;
784
+        }
785
+
786
+        $row['principaluri'] = (string)$row['principaluri'];
787
+        $subscription = [
788
+            'id' => $row['id'],
789
+            'uri' => $row['uri'],
790
+            'principaluri' => $row['principaluri'],
791
+            'source' => $row['source'],
792
+            'lastmodified' => $row['lastmodified'],
793
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
794
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
795
+        ];
796
+
797
+        return $this->rowToSubscription($row, $subscription);
798
+    }
799
+
800
+    /**
801
+     * Creates a new calendar for a principal.
802
+     *
803
+     * If the creation was a success, an id must be returned that can be used to reference
804
+     * this calendar in other methods, such as updateCalendar.
805
+     *
806
+     * @param string $principalUri
807
+     * @param string $calendarUri
808
+     * @param array $properties
809
+     * @return int
810
+     *
811
+     * @throws CalendarException
812
+     */
813
+    public function createCalendar($principalUri, $calendarUri, array $properties) {
814
+        if (strlen($calendarUri) > 255) {
815
+            throw new CalendarException('URI too long. Calendar not created');
816
+        }
817
+
818
+        $values = [
819
+            'principaluri' => $this->convertPrincipal($principalUri, true),
820
+            'uri' => $calendarUri,
821
+            'synctoken' => 1,
822
+            'transparent' => 0,
823
+            'components' => 'VEVENT,VTODO,VJOURNAL',
824
+            'displayname' => $calendarUri
825
+        ];
826
+
827
+        // Default value
828
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
829
+        if (isset($properties[$sccs])) {
830
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
831
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
832
+            }
833
+            $values['components'] = implode(',', $properties[$sccs]->getValue());
834
+        } elseif (isset($properties['components'])) {
835
+            // Allow to provide components internally without having
836
+            // to create a SupportedCalendarComponentSet object
837
+            $values['components'] = $properties['components'];
838
+        }
839
+
840
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
841
+        if (isset($properties[$transp])) {
842
+            $values['transparent'] = (int)($properties[$transp]->getValue() === 'transparent');
843
+        }
844
+
845
+        foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
846
+            if (isset($properties[$xmlName])) {
847
+                $values[$dbName] = $properties[$xmlName];
848
+            }
849
+        }
850
+
851
+        [$calendarId, $calendarData] = $this->atomic(function () use ($values) {
852
+            $query = $this->db->getQueryBuilder();
853
+            $query->insert('calendars');
854
+            foreach ($values as $column => $value) {
855
+                $query->setValue($column, $query->createNamedParameter($value));
856
+            }
857
+            $query->executeStatement();
858
+            $calendarId = $query->getLastInsertId();
859
+
860
+            $calendarData = $this->getCalendarById($calendarId);
861
+            return [$calendarId, $calendarData];
862
+        }, $this->db);
863
+
864
+        $this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
865
+
866
+        return $calendarId;
867
+    }
868
+
869
+    /**
870
+     * Updates properties for a calendar.
871
+     *
872
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
873
+     * To do the actual updates, you must tell this object which properties
874
+     * you're going to process with the handle() method.
875
+     *
876
+     * Calling the handle method is like telling the PropPatch object "I
877
+     * promise I can handle updating this property".
878
+     *
879
+     * Read the PropPatch documentation for more info and examples.
880
+     *
881
+     * @param mixed $calendarId
882
+     * @param PropPatch $propPatch
883
+     * @return void
884
+     */
885
+    public function updateCalendar($calendarId, PropPatch $propPatch) {
886
+        $supportedProperties = array_keys($this->propertyMap);
887
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
888
+
889
+        $propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
890
+            $newValues = [];
891
+            foreach ($mutations as $propertyName => $propertyValue) {
892
+                switch ($propertyName) {
893
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
894
+                        $fieldName = 'transparent';
895
+                        $newValues[$fieldName] = (int)($propertyValue->getValue() === 'transparent');
896
+                        break;
897
+                    default:
898
+                        $fieldName = $this->propertyMap[$propertyName][0];
899
+                        $newValues[$fieldName] = $propertyValue;
900
+                        break;
901
+                }
902
+            }
903
+            [$calendarData, $shares] = $this->atomic(function () use ($calendarId, $newValues) {
904
+                $query = $this->db->getQueryBuilder();
905
+                $query->update('calendars');
906
+                foreach ($newValues as $fieldName => $value) {
907
+                    $query->set($fieldName, $query->createNamedParameter($value));
908
+                }
909
+                $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
910
+                $query->executeStatement();
911
+
912
+                $this->addChanges($calendarId, [''], 2);
913
+
914
+                $calendarData = $this->getCalendarById($calendarId);
915
+                $shares = $this->getShares($calendarId);
916
+                return [$calendarData, $shares];
917
+            }, $this->db);
918
+
919
+            $this->dispatcher->dispatchTyped(new CalendarUpdatedEvent($calendarId, $calendarData, $shares, $mutations));
920
+
921
+            return true;
922
+        });
923
+    }
924
+
925
+    /**
926
+     * Delete a calendar and all it's objects
927
+     *
928
+     * @param mixed $calendarId
929
+     * @return void
930
+     */
931
+    public function deleteCalendar($calendarId, bool $forceDeletePermanently = false) {
932
+        $this->publishStatusCache->remove((string)$calendarId);
933
+
934
+        $this->atomic(function () use ($calendarId, $forceDeletePermanently): void {
935
+            // The calendar is deleted right away if this is either enforced by the caller
936
+            // or the special contacts birthday calendar or when the preference of an empty
937
+            // retention (0 seconds) is set, which signals a disabled trashbin.
938
+            $calendarData = $this->getCalendarById($calendarId);
939
+            $isBirthdayCalendar = isset($calendarData['uri']) && $calendarData['uri'] === BirthdayService::BIRTHDAY_CALENDAR_URI;
940
+            $trashbinDisabled = $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0';
941
+            if ($forceDeletePermanently || $isBirthdayCalendar || $trashbinDisabled) {
942
+                $calendarData = $this->getCalendarById($calendarId);
943
+                $shares = $this->getShares($calendarId);
944
+
945
+                $this->purgeCalendarInvitations($calendarId);
946
+
947
+                $qbDeleteCalendarObjectProps = $this->db->getQueryBuilder();
948
+                $qbDeleteCalendarObjectProps->delete($this->dbObjectPropertiesTable)
949
+                    ->where($qbDeleteCalendarObjectProps->expr()->eq('calendarid', $qbDeleteCalendarObjectProps->createNamedParameter($calendarId)))
950
+                    ->andWhere($qbDeleteCalendarObjectProps->expr()->eq('calendartype', $qbDeleteCalendarObjectProps->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
951
+                    ->executeStatement();
952
+
953
+                $qbDeleteCalendarObjects = $this->db->getQueryBuilder();
954
+                $qbDeleteCalendarObjects->delete('calendarobjects')
955
+                    ->where($qbDeleteCalendarObjects->expr()->eq('calendarid', $qbDeleteCalendarObjects->createNamedParameter($calendarId)))
956
+                    ->andWhere($qbDeleteCalendarObjects->expr()->eq('calendartype', $qbDeleteCalendarObjects->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
957
+                    ->executeStatement();
958
+
959
+                $qbDeleteCalendarChanges = $this->db->getQueryBuilder();
960
+                $qbDeleteCalendarChanges->delete('calendarchanges')
961
+                    ->where($qbDeleteCalendarChanges->expr()->eq('calendarid', $qbDeleteCalendarChanges->createNamedParameter($calendarId)))
962
+                    ->andWhere($qbDeleteCalendarChanges->expr()->eq('calendartype', $qbDeleteCalendarChanges->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
963
+                    ->executeStatement();
964
+
965
+                $this->calendarSharingBackend->deleteAllShares($calendarId);
966
+
967
+                $qbDeleteCalendar = $this->db->getQueryBuilder();
968
+                $qbDeleteCalendar->delete('calendars')
969
+                    ->where($qbDeleteCalendar->expr()->eq('id', $qbDeleteCalendar->createNamedParameter($calendarId)))
970
+                    ->executeStatement();
971
+
972
+                // Only dispatch if we actually deleted anything
973
+                if ($calendarData) {
974
+                    $this->dispatcher->dispatchTyped(new CalendarDeletedEvent($calendarId, $calendarData, $shares));
975
+                }
976
+            } else {
977
+                $qbMarkCalendarDeleted = $this->db->getQueryBuilder();
978
+                $qbMarkCalendarDeleted->update('calendars')
979
+                    ->set('deleted_at', $qbMarkCalendarDeleted->createNamedParameter(time()))
980
+                    ->where($qbMarkCalendarDeleted->expr()->eq('id', $qbMarkCalendarDeleted->createNamedParameter($calendarId)))
981
+                    ->executeStatement();
982
+
983
+                $calendarData = $this->getCalendarById($calendarId);
984
+                $shares = $this->getShares($calendarId);
985
+                if ($calendarData) {
986
+                    $this->dispatcher->dispatchTyped(new CalendarMovedToTrashEvent(
987
+                        $calendarId,
988
+                        $calendarData,
989
+                        $shares
990
+                    ));
991
+                }
992
+            }
993
+        }, $this->db);
994
+    }
995
+
996
+    public function restoreCalendar(int $id): void {
997
+        $this->atomic(function () use ($id): void {
998
+            $qb = $this->db->getQueryBuilder();
999
+            $update = $qb->update('calendars')
1000
+                ->set('deleted_at', $qb->createNamedParameter(null))
1001
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1002
+            $update->executeStatement();
1003
+
1004
+            $calendarData = $this->getCalendarById($id);
1005
+            $shares = $this->getShares($id);
1006
+            if ($calendarData === null) {
1007
+                throw new RuntimeException('Calendar data that was just written can\'t be read back. Check your database configuration.');
1008
+            }
1009
+            $this->dispatcher->dispatchTyped(new CalendarRestoredEvent(
1010
+                $id,
1011
+                $calendarData,
1012
+                $shares
1013
+            ));
1014
+        }, $this->db);
1015
+    }
1016
+
1017
+    /**
1018
+     * Returns all calendar entries as a stream of data
1019
+     *
1020
+     * @since 32.0.0
1021
+     *
1022
+     * @return Generator<array>
1023
+     */
1024
+    public function exportCalendar(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR, ?CalendarExportOptions $options = null): Generator {
1025
+        // extract options
1026
+        $rangeStart = $options?->getRangeStart();
1027
+        $rangeCount = $options?->getRangeCount();
1028
+        // construct query
1029
+        $qb = $this->db->getQueryBuilder();
1030
+        $qb->select('*')
1031
+            ->from('calendarobjects')
1032
+            ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1033
+            ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1034
+            ->andWhere($qb->expr()->isNull('deleted_at'));
1035
+        if ($rangeStart !== null) {
1036
+            $qb->andWhere($qb->expr()->gt('uid', $qb->createNamedParameter($rangeStart)));
1037
+        }
1038
+        if ($rangeCount !== null) {
1039
+            $qb->setMaxResults($rangeCount);
1040
+        }
1041
+        if ($rangeStart !== null || $rangeCount !== null) {
1042
+            $qb->orderBy('uid', 'ASC');
1043
+        }
1044
+        $rs = $qb->executeQuery();
1045
+        // iterate through results
1046
+        try {
1047
+            while (($row = $rs->fetch()) !== false) {
1048
+                yield $row;
1049
+            }
1050
+        } finally {
1051
+            $rs->closeCursor();
1052
+        }
1053
+    }
1054
+
1055
+    /**
1056
+     * Returns all calendar objects with limited metadata for a calendar
1057
+     *
1058
+     * Every item contains an array with the following keys:
1059
+     *   * id - the table row id
1060
+     *   * etag - An arbitrary string
1061
+     *   * uri - a unique key which will be used to construct the uri. This can
1062
+     *     be any arbitrary string.
1063
+     *   * calendardata - The iCalendar-compatible calendar data
1064
+     *
1065
+     * @param mixed $calendarId
1066
+     * @param int $calendarType
1067
+     * @return array
1068
+     */
1069
+    public function getLimitedCalendarObjects(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1070
+        $query = $this->db->getQueryBuilder();
1071
+        $query->select(['id','uid', 'etag', 'uri', 'calendardata'])
1072
+            ->from('calendarobjects')
1073
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1074
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1075
+            ->andWhere($query->expr()->isNull('deleted_at'));
1076
+        $stmt = $query->executeQuery();
1077
+
1078
+        $result = [];
1079
+        while (($row = $stmt->fetch()) !== false) {
1080
+            $result[$row['uid']] = [
1081
+                'id' => $row['id'],
1082
+                'etag' => $row['etag'],
1083
+                'uri' => $row['uri'],
1084
+                'calendardata' => $row['calendardata'],
1085
+            ];
1086
+        }
1087
+        $stmt->closeCursor();
1088
+
1089
+        return $result;
1090
+    }
1091
+
1092
+    /**
1093
+     * Delete all of an user's shares
1094
+     *
1095
+     * @param string $principaluri
1096
+     * @return void
1097
+     */
1098
+    public function deleteAllSharesByUser($principaluri) {
1099
+        $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
1100
+    }
1101
+
1102
+    /**
1103
+     * Returns all calendar objects within a calendar.
1104
+     *
1105
+     * Every item contains an array with the following keys:
1106
+     *   * calendardata - The iCalendar-compatible calendar data
1107
+     *   * uri - a unique key which will be used to construct the uri. This can
1108
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
1109
+     *     good idea. This is only the basename, or filename, not the full
1110
+     *     path.
1111
+     *   * lastmodified - a timestamp of the last modification time
1112
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
1113
+     *   '"abcdef"')
1114
+     *   * size - The size of the calendar objects, in bytes.
1115
+     *   * component - optional, a string containing the type of object, such
1116
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
1117
+     *     the Content-Type header.
1118
+     *
1119
+     * Note that the etag is optional, but it's highly encouraged to return for
1120
+     * speed reasons.
1121
+     *
1122
+     * The calendardata is also optional. If it's not returned
1123
+     * 'getCalendarObject' will be called later, which *is* expected to return
1124
+     * calendardata.
1125
+     *
1126
+     * If neither etag or size are specified, the calendardata will be
1127
+     * used/fetched to determine these numbers. If both are specified the
1128
+     * amount of times this is needed is reduced by a great degree.
1129
+     *
1130
+     * @param mixed $calendarId
1131
+     * @param int $calendarType
1132
+     * @return array
1133
+     */
1134
+    public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1135
+        $query = $this->db->getQueryBuilder();
1136
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
1137
+            ->from('calendarobjects')
1138
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1139
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1140
+            ->andWhere($query->expr()->isNull('deleted_at'));
1141
+        $stmt = $query->executeQuery();
1142
+
1143
+        $result = [];
1144
+        while (($row = $stmt->fetch()) !== false) {
1145
+            $result[] = [
1146
+                'id' => $row['id'],
1147
+                'uri' => $row['uri'],
1148
+                'lastmodified' => $row['lastmodified'],
1149
+                'etag' => '"' . $row['etag'] . '"',
1150
+                'calendarid' => $row['calendarid'],
1151
+                'size' => (int)$row['size'],
1152
+                'component' => strtolower($row['componenttype']),
1153
+                'classification' => (int)$row['classification']
1154
+            ];
1155
+        }
1156
+        $stmt->closeCursor();
1157
+
1158
+        return $result;
1159
+    }
1160
+
1161
+    public function getDeletedCalendarObjects(int $deletedBefore): array {
1162
+        $query = $this->db->getQueryBuilder();
1163
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.calendartype', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1164
+            ->from('calendarobjects', 'co')
1165
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1166
+            ->where($query->expr()->isNotNull('co.deleted_at'))
1167
+            ->andWhere($query->expr()->lt('co.deleted_at', $query->createNamedParameter($deletedBefore)));
1168
+        $stmt = $query->executeQuery();
1169
+
1170
+        $result = [];
1171
+        while (($row = $stmt->fetch()) !== false) {
1172
+            $result[] = [
1173
+                'id' => $row['id'],
1174
+                'uri' => $row['uri'],
1175
+                'lastmodified' => $row['lastmodified'],
1176
+                'etag' => '"' . $row['etag'] . '"',
1177
+                'calendarid' => (int)$row['calendarid'],
1178
+                'calendartype' => (int)$row['calendartype'],
1179
+                'size' => (int)$row['size'],
1180
+                'component' => strtolower($row['componenttype']),
1181
+                'classification' => (int)$row['classification'],
1182
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1183
+            ];
1184
+        }
1185
+        $stmt->closeCursor();
1186
+
1187
+        return $result;
1188
+    }
1189
+
1190
+    /**
1191
+     * Return all deleted calendar objects by the given principal that are not
1192
+     * in deleted calendars.
1193
+     *
1194
+     * @param string $principalUri
1195
+     * @return array
1196
+     * @throws Exception
1197
+     */
1198
+    public function getDeletedCalendarObjectsByPrincipal(string $principalUri): array {
1199
+        $query = $this->db->getQueryBuilder();
1200
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1201
+            ->selectAlias('c.uri', 'calendaruri')
1202
+            ->from('calendarobjects', 'co')
1203
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1204
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1205
+            ->andWhere($query->expr()->isNotNull('co.deleted_at'))
1206
+            ->andWhere($query->expr()->isNull('c.deleted_at'));
1207
+        $stmt = $query->executeQuery();
1208
+
1209
+        $result = [];
1210
+        while ($row = $stmt->fetch()) {
1211
+            $result[] = [
1212
+                'id' => $row['id'],
1213
+                'uri' => $row['uri'],
1214
+                'lastmodified' => $row['lastmodified'],
1215
+                'etag' => '"' . $row['etag'] . '"',
1216
+                'calendarid' => $row['calendarid'],
1217
+                'calendaruri' => $row['calendaruri'],
1218
+                'size' => (int)$row['size'],
1219
+                'component' => strtolower($row['componenttype']),
1220
+                'classification' => (int)$row['classification'],
1221
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1222
+            ];
1223
+        }
1224
+        $stmt->closeCursor();
1225
+
1226
+        return $result;
1227
+    }
1228
+
1229
+    /**
1230
+     * Returns information from a single calendar object, based on it's object
1231
+     * uri.
1232
+     *
1233
+     * The object uri is only the basename, or filename and not a full path.
1234
+     *
1235
+     * The returned array must have the same keys as getCalendarObjects. The
1236
+     * 'calendardata' object is required here though, while it's not required
1237
+     * for getCalendarObjects.
1238
+     *
1239
+     * This method must return null if the object did not exist.
1240
+     *
1241
+     * @param mixed $calendarId
1242
+     * @param string $objectUri
1243
+     * @param int $calendarType
1244
+     * @return array|null
1245
+     */
1246
+    public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1247
+        $key = $calendarId . '::' . $objectUri . '::' . $calendarType;
1248
+        if (isset($this->cachedObjects[$key])) {
1249
+            return $this->cachedObjects[$key];
1250
+        }
1251
+        $query = $this->db->getQueryBuilder();
1252
+        $query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1253
+            ->from('calendarobjects')
1254
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1255
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1256
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1257
+        $stmt = $query->executeQuery();
1258
+        $row = $stmt->fetch();
1259
+        $stmt->closeCursor();
1260
+
1261
+        if (!$row) {
1262
+            return null;
1263
+        }
1264
+
1265
+        $object = $this->rowToCalendarObject($row);
1266
+        $this->cachedObjects[$key] = $object;
1267
+        return $object;
1268
+    }
1269
+
1270
+    private function rowToCalendarObject(array $row): array {
1271
+        return [
1272
+            'id' => $row['id'],
1273
+            'uri' => $row['uri'],
1274
+            'uid' => $row['uid'],
1275
+            'lastmodified' => $row['lastmodified'],
1276
+            'etag' => '"' . $row['etag'] . '"',
1277
+            'calendarid' => $row['calendarid'],
1278
+            'size' => (int)$row['size'],
1279
+            'calendardata' => $this->readBlob($row['calendardata']),
1280
+            'component' => strtolower($row['componenttype']),
1281
+            'classification' => (int)$row['classification'],
1282
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1283
+        ];
1284
+    }
1285
+
1286
+    /**
1287
+     * Returns a list of calendar objects.
1288
+     *
1289
+     * This method should work identical to getCalendarObject, but instead
1290
+     * return all the calendar objects in the list as an array.
1291
+     *
1292
+     * If the backend supports this, it may allow for some speed-ups.
1293
+     *
1294
+     * @param mixed $calendarId
1295
+     * @param string[] $uris
1296
+     * @param int $calendarType
1297
+     * @return array
1298
+     */
1299
+    public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1300
+        if (empty($uris)) {
1301
+            return [];
1302
+        }
1303
+
1304
+        $chunks = array_chunk($uris, 100);
1305
+        $objects = [];
1306
+
1307
+        $query = $this->db->getQueryBuilder();
1308
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1309
+            ->from('calendarobjects')
1310
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1311
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1312
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1313
+            ->andWhere($query->expr()->isNull('deleted_at'));
1314
+
1315
+        foreach ($chunks as $uris) {
1316
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1317
+            $result = $query->executeQuery();
1318
+
1319
+            while ($row = $result->fetch()) {
1320
+                $objects[] = [
1321
+                    'id' => $row['id'],
1322
+                    'uri' => $row['uri'],
1323
+                    'lastmodified' => $row['lastmodified'],
1324
+                    'etag' => '"' . $row['etag'] . '"',
1325
+                    'calendarid' => $row['calendarid'],
1326
+                    'size' => (int)$row['size'],
1327
+                    'calendardata' => $this->readBlob($row['calendardata']),
1328
+                    'component' => strtolower($row['componenttype']),
1329
+                    'classification' => (int)$row['classification']
1330
+                ];
1331
+            }
1332
+            $result->closeCursor();
1333
+        }
1334
+
1335
+        return $objects;
1336
+    }
1337
+
1338
+    /**
1339
+     * Creates a new calendar object.
1340
+     *
1341
+     * The object uri is only the basename, or filename and not a full path.
1342
+     *
1343
+     * It is possible return an etag from this function, which will be used in
1344
+     * the response to this PUT request. Note that the ETag must be surrounded
1345
+     * by double-quotes.
1346
+     *
1347
+     * However, you should only really return this ETag if you don't mangle the
1348
+     * calendar-data. If the result of a subsequent GET to this object is not
1349
+     * the exact same as this request body, you should omit the ETag.
1350
+     *
1351
+     * @param mixed $calendarId
1352
+     * @param string $objectUri
1353
+     * @param string $calendarData
1354
+     * @param int $calendarType
1355
+     * @return string
1356
+     */
1357
+    public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1358
+        $this->cachedObjects = [];
1359
+        $extraData = $this->getDenormalizedData($calendarData);
1360
+
1361
+        return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1362
+            // Try to detect duplicates
1363
+            $qb = $this->db->getQueryBuilder();
1364
+            $qb->select($qb->func()->count('*'))
1365
+                ->from('calendarobjects')
1366
+                ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1367
+                ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($extraData['uid'])))
1368
+                ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1369
+                ->andWhere($qb->expr()->isNull('deleted_at'));
1370
+            $result = $qb->executeQuery();
1371
+            $count = (int)$result->fetchOne();
1372
+            $result->closeCursor();
1373
+
1374
+            if ($count !== 0) {
1375
+                throw new BadRequest('Calendar object with uid already exists in this calendar collection.');
1376
+            }
1377
+            // For a more specific error message we also try to explicitly look up the UID but as a deleted entry
1378
+            $qbDel = $this->db->getQueryBuilder();
1379
+            $qbDel->select('*')
1380
+                ->from('calendarobjects')
1381
+                ->where($qbDel->expr()->eq('calendarid', $qbDel->createNamedParameter($calendarId)))
1382
+                ->andWhere($qbDel->expr()->eq('uid', $qbDel->createNamedParameter($extraData['uid'])))
1383
+                ->andWhere($qbDel->expr()->eq('calendartype', $qbDel->createNamedParameter($calendarType)))
1384
+                ->andWhere($qbDel->expr()->isNotNull('deleted_at'));
1385
+            $result = $qbDel->executeQuery();
1386
+            $found = $result->fetch();
1387
+            $result->closeCursor();
1388
+            if ($found !== false) {
1389
+                // the object existed previously but has been deleted
1390
+                // remove the trashbin entry and continue as if it was a new object
1391
+                $this->deleteCalendarObject($calendarId, $found['uri']);
1392
+            }
1393
+
1394
+            $query = $this->db->getQueryBuilder();
1395
+            $query->insert('calendarobjects')
1396
+                ->values([
1397
+                    'calendarid' => $query->createNamedParameter($calendarId),
1398
+                    'uri' => $query->createNamedParameter($objectUri),
1399
+                    'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1400
+                    'lastmodified' => $query->createNamedParameter(time()),
1401
+                    'etag' => $query->createNamedParameter($extraData['etag']),
1402
+                    'size' => $query->createNamedParameter($extraData['size']),
1403
+                    'componenttype' => $query->createNamedParameter($extraData['componentType']),
1404
+                    'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1405
+                    'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1406
+                    'classification' => $query->createNamedParameter($extraData['classification']),
1407
+                    'uid' => $query->createNamedParameter($extraData['uid']),
1408
+                    'calendartype' => $query->createNamedParameter($calendarType),
1409
+                ])
1410
+                ->executeStatement();
1411
+
1412
+            $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1413
+            $this->addChanges($calendarId, [$objectUri], 1, $calendarType);
1414
+
1415
+            $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1416
+            assert($objectRow !== null);
1417
+
1418
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1419
+                $calendarRow = $this->getCalendarById($calendarId);
1420
+                $shares = $this->getShares($calendarId);
1421
+
1422
+                $this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1423
+            } elseif ($calendarType === self::CALENDAR_TYPE_SUBSCRIPTION) {
1424
+                $subscriptionRow = $this->getSubscriptionById($calendarId);
1425
+
1426
+                $this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1427
+            } elseif ($calendarType === self::CALENDAR_TYPE_FEDERATED) {
1428
+                // TODO: implement custom event for federated calendars
1429
+            }
1430
+
1431
+            return '"' . $extraData['etag'] . '"';
1432
+        }, $this->db);
1433
+    }
1434
+
1435
+    /**
1436
+     * Updates an existing calendarobject, based on it's uri.
1437
+     *
1438
+     * The object uri is only the basename, or filename and not a full path.
1439
+     *
1440
+     * It is possible return an etag from this function, which will be used in
1441
+     * the response to this PUT request. Note that the ETag must be surrounded
1442
+     * by double-quotes.
1443
+     *
1444
+     * However, you should only really return this ETag if you don't mangle the
1445
+     * calendar-data. If the result of a subsequent GET to this object is not
1446
+     * the exact same as this request body, you should omit the ETag.
1447
+     *
1448
+     * @param mixed $calendarId
1449
+     * @param string $objectUri
1450
+     * @param string $calendarData
1451
+     * @param int $calendarType
1452
+     * @return string
1453
+     */
1454
+    public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1455
+        $this->cachedObjects = [];
1456
+        $extraData = $this->getDenormalizedData($calendarData);
1457
+
1458
+        return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1459
+            $query = $this->db->getQueryBuilder();
1460
+            $query->update('calendarobjects')
1461
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1462
+                ->set('lastmodified', $query->createNamedParameter(time()))
1463
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1464
+                ->set('size', $query->createNamedParameter($extraData['size']))
1465
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1466
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1467
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1468
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1469
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1470
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1471
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1472
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1473
+                ->executeStatement();
1474
+
1475
+            $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1476
+            $this->addChanges($calendarId, [$objectUri], 2, $calendarType);
1477
+
1478
+            $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1479
+            if (is_array($objectRow)) {
1480
+                if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1481
+                    $calendarRow = $this->getCalendarById($calendarId);
1482
+                    $shares = $this->getShares($calendarId);
1483
+
1484
+                    $this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1485
+                } elseif ($calendarType === self::CALENDAR_TYPE_SUBSCRIPTION) {
1486
+                    $subscriptionRow = $this->getSubscriptionById($calendarId);
1487
+
1488
+                    $this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1489
+                } elseif ($calendarType === self::CALENDAR_TYPE_FEDERATED) {
1490
+                    // TODO: implement custom event for federated calendars
1491
+                }
1492
+            }
1493
+
1494
+            return '"' . $extraData['etag'] . '"';
1495
+        }, $this->db);
1496
+    }
1497
+
1498
+    /**
1499
+     * Moves a calendar object from calendar to calendar.
1500
+     *
1501
+     * @param string $sourcePrincipalUri
1502
+     * @param int $sourceObjectId
1503
+     * @param string $targetPrincipalUri
1504
+     * @param int $targetCalendarId
1505
+     * @param string $tragetObjectUri
1506
+     * @param int $calendarType
1507
+     * @return bool
1508
+     * @throws Exception
1509
+     */
1510
+    public function moveCalendarObject(string $sourcePrincipalUri, int $sourceObjectId, string $targetPrincipalUri, int $targetCalendarId, string $tragetObjectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR): bool {
1511
+        $this->cachedObjects = [];
1512
+        return $this->atomic(function () use ($sourcePrincipalUri, $sourceObjectId, $targetPrincipalUri, $targetCalendarId, $tragetObjectUri, $calendarType) {
1513
+            $object = $this->getCalendarObjectById($sourcePrincipalUri, $sourceObjectId);
1514
+            if (empty($object)) {
1515
+                return false;
1516
+            }
1517
+
1518
+            $sourceCalendarId = $object['calendarid'];
1519
+            $sourceObjectUri = $object['uri'];
1520
+
1521
+            $query = $this->db->getQueryBuilder();
1522
+            $query->update('calendarobjects')
1523
+                ->set('calendarid', $query->createNamedParameter($targetCalendarId, IQueryBuilder::PARAM_INT))
1524
+                ->set('uri', $query->createNamedParameter($tragetObjectUri, IQueryBuilder::PARAM_STR))
1525
+                ->where($query->expr()->eq('id', $query->createNamedParameter($sourceObjectId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
1526
+                ->executeStatement();
1527
+
1528
+            $this->purgeProperties($sourceCalendarId, $sourceObjectId);
1529
+            $this->updateProperties($targetCalendarId, $tragetObjectUri, $object['calendardata'], $calendarType);
1530
+
1531
+            $this->addChanges($sourceCalendarId, [$sourceObjectUri], 3, $calendarType);
1532
+            $this->addChanges($targetCalendarId, [$tragetObjectUri], 1, $calendarType);
1533
+
1534
+            $object = $this->getCalendarObjectById($targetPrincipalUri, $sourceObjectId);
1535
+            // Calendar Object wasn't found - possibly because it was deleted in the meantime by a different client
1536
+            if (empty($object)) {
1537
+                return false;
1538
+            }
1539
+
1540
+            $targetCalendarRow = $this->getCalendarById($targetCalendarId);
1541
+            // the calendar this event is being moved to does not exist any longer
1542
+            if (empty($targetCalendarRow)) {
1543
+                return false;
1544
+            }
1545
+
1546
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1547
+                $sourceShares = $this->getShares($sourceCalendarId);
1548
+                $targetShares = $this->getShares($targetCalendarId);
1549
+                $sourceCalendarRow = $this->getCalendarById($sourceCalendarId);
1550
+                $this->dispatcher->dispatchTyped(new CalendarObjectMovedEvent($sourceCalendarId, $sourceCalendarRow, $targetCalendarId, $targetCalendarRow, $sourceShares, $targetShares, $object));
1551
+            }
1552
+            return true;
1553
+        }, $this->db);
1554
+    }
1555
+
1556
+    /**
1557
+     * Deletes an existing calendar object.
1558
+     *
1559
+     * The object uri is only the basename, or filename and not a full path.
1560
+     *
1561
+     * @param mixed $calendarId
1562
+     * @param string $objectUri
1563
+     * @param int $calendarType
1564
+     * @param bool $forceDeletePermanently
1565
+     * @return void
1566
+     */
1567
+    public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
1568
+        $this->cachedObjects = [];
1569
+        $this->atomic(function () use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently): void {
1570
+            $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1571
+
1572
+            if ($data === null) {
1573
+                // Nothing to delete
1574
+                return;
1575
+            }
1576
+
1577
+            if ($forceDeletePermanently || $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0') {
1578
+                $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1579
+                $stmt->execute([$calendarId, $objectUri, $calendarType]);
1580
+
1581
+                $this->purgeProperties($calendarId, $data['id']);
1582
+
1583
+                $this->purgeObjectInvitations($data['uid']);
1584
+
1585
+                if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1586
+                    $calendarRow = $this->getCalendarById($calendarId);
1587
+                    $shares = $this->getShares($calendarId);
1588
+
1589
+                    $this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent($calendarId, $calendarRow, $shares, $data));
1590
+                } else {
1591
+                    $subscriptionRow = $this->getSubscriptionById($calendarId);
1592
+
1593
+                    $this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent($calendarId, $subscriptionRow, [], $data));
1594
+                }
1595
+            } else {
1596
+                $pathInfo = pathinfo($data['uri']);
1597
+                if (!empty($pathInfo['extension'])) {
1598
+                    // Append a suffix to "free" the old URI for recreation
1599
+                    $newUri = sprintf(
1600
+                        '%s-deleted.%s',
1601
+                        $pathInfo['filename'],
1602
+                        $pathInfo['extension']
1603
+                    );
1604
+                } else {
1605
+                    $newUri = sprintf(
1606
+                        '%s-deleted',
1607
+                        $pathInfo['filename']
1608
+                    );
1609
+                }
1610
+
1611
+                // Try to detect conflicts before the DB does
1612
+                // As unlikely as it seems, this can happen when the user imports, then deletes, imports and deletes again
1613
+                $newObject = $this->getCalendarObject($calendarId, $newUri, $calendarType);
1614
+                if ($newObject !== null) {
1615
+                    throw new Forbidden("A calendar object with URI $newUri already exists in calendar $calendarId, therefore this object can't be moved into the trashbin");
1616
+                }
1617
+
1618
+                $qb = $this->db->getQueryBuilder();
1619
+                $markObjectDeletedQuery = $qb->update('calendarobjects')
1620
+                    ->set('deleted_at', $qb->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
1621
+                    ->set('uri', $qb->createNamedParameter($newUri))
1622
+                    ->where(
1623
+                        $qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
1624
+                        $qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
1625
+                        $qb->expr()->eq('uri', $qb->createNamedParameter($objectUri))
1626
+                    );
1627
+                $markObjectDeletedQuery->executeStatement();
1628
+
1629
+                $calendarData = $this->getCalendarById($calendarId);
1630
+                if ($calendarData !== null) {
1631
+                    $this->dispatcher->dispatchTyped(
1632
+                        new CalendarObjectMovedToTrashEvent(
1633
+                            $calendarId,
1634
+                            $calendarData,
1635
+                            $this->getShares($calendarId),
1636
+                            $data
1637
+                        )
1638
+                    );
1639
+                }
1640
+            }
1641
+
1642
+            $this->addChanges($calendarId, [$objectUri], 3, $calendarType);
1643
+        }, $this->db);
1644
+    }
1645
+
1646
+    /**
1647
+     * @param mixed $objectData
1648
+     *
1649
+     * @throws Forbidden
1650
+     */
1651
+    public function restoreCalendarObject(array $objectData): void {
1652
+        $this->cachedObjects = [];
1653
+        $this->atomic(function () use ($objectData): void {
1654
+            $id = (int)$objectData['id'];
1655
+            $restoreUri = str_replace('-deleted.ics', '.ics', $objectData['uri']);
1656
+            $targetObject = $this->getCalendarObject(
1657
+                $objectData['calendarid'],
1658
+                $restoreUri
1659
+            );
1660
+            if ($targetObject !== null) {
1661
+                throw new Forbidden("Can not restore calendar $id because a calendar object with the URI $restoreUri already exists");
1662
+            }
1663
+
1664
+            $qb = $this->db->getQueryBuilder();
1665
+            $update = $qb->update('calendarobjects')
1666
+                ->set('uri', $qb->createNamedParameter($restoreUri))
1667
+                ->set('deleted_at', $qb->createNamedParameter(null))
1668
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1669
+            $update->executeStatement();
1670
+
1671
+            // Make sure this change is tracked in the changes table
1672
+            $qb2 = $this->db->getQueryBuilder();
1673
+            $selectObject = $qb2->select('calendardata', 'uri', 'calendarid', 'calendartype')
1674
+                ->selectAlias('componenttype', 'component')
1675
+                ->from('calendarobjects')
1676
+                ->where($qb2->expr()->eq('id', $qb2->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1677
+            $result = $selectObject->executeQuery();
1678
+            $row = $result->fetch();
1679
+            $result->closeCursor();
1680
+            if ($row === false) {
1681
+                // Welp, this should possibly not have happened, but let's ignore
1682
+                return;
1683
+            }
1684
+            $this->addChanges($row['calendarid'], [$row['uri']], 1, (int)$row['calendartype']);
1685
+
1686
+            $calendarRow = $this->getCalendarById((int)$row['calendarid']);
1687
+            if ($calendarRow === null) {
1688
+                throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
1689
+            }
1690
+            $this->dispatcher->dispatchTyped(
1691
+                new CalendarObjectRestoredEvent(
1692
+                    (int)$objectData['calendarid'],
1693
+                    $calendarRow,
1694
+                    $this->getShares((int)$row['calendarid']),
1695
+                    $row
1696
+                )
1697
+            );
1698
+        }, $this->db);
1699
+    }
1700
+
1701
+    /**
1702
+     * Performs a calendar-query on the contents of this calendar.
1703
+     *
1704
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1705
+     * calendar-query it is possible for a client to request a specific set of
1706
+     * object, based on contents of iCalendar properties, date-ranges and
1707
+     * iCalendar component types (VTODO, VEVENT).
1708
+     *
1709
+     * This method should just return a list of (relative) urls that match this
1710
+     * query.
1711
+     *
1712
+     * The list of filters are specified as an array. The exact array is
1713
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1714
+     *
1715
+     * Note that it is extremely likely that getCalendarObject for every path
1716
+     * returned from this method will be called almost immediately after. You
1717
+     * may want to anticipate this to speed up these requests.
1718
+     *
1719
+     * This method provides a default implementation, which parses *all* the
1720
+     * iCalendar objects in the specified calendar.
1721
+     *
1722
+     * This default may well be good enough for personal use, and calendars
1723
+     * that aren't very large. But if you anticipate high usage, big calendars
1724
+     * or high loads, you are strongly advised to optimize certain paths.
1725
+     *
1726
+     * The best way to do so is override this method and to optimize
1727
+     * specifically for 'common filters'.
1728
+     *
1729
+     * Requests that are extremely common are:
1730
+     *   * requests for just VEVENTS
1731
+     *   * requests for just VTODO
1732
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1733
+     *
1734
+     * ..and combinations of these requests. It may not be worth it to try to
1735
+     * handle every possible situation and just rely on the (relatively
1736
+     * easy to use) CalendarQueryValidator to handle the rest.
1737
+     *
1738
+     * Note that especially time-range-filters may be difficult to parse. A
1739
+     * time-range filter specified on a VEVENT must for instance also handle
1740
+     * recurrence rules correctly.
1741
+     * A good example of how to interpret all these filters can also simply
1742
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1743
+     * as possible, so it gives you a good idea on what type of stuff you need
1744
+     * to think of.
1745
+     *
1746
+     * @param mixed $calendarId
1747
+     * @param array $filters
1748
+     * @param int $calendarType
1749
+     * @return array
1750
+     */
1751
+    public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1752
+        $componentType = null;
1753
+        $requirePostFilter = true;
1754
+        $timeRange = null;
1755
+
1756
+        // if no filters were specified, we don't need to filter after a query
1757
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1758
+            $requirePostFilter = false;
1759
+        }
1760
+
1761
+        // Figuring out if there's a component filter
1762
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1763
+            $componentType = $filters['comp-filters'][0]['name'];
1764
+
1765
+            // Checking if we need post-filters
1766
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1767
+                $requirePostFilter = false;
1768
+            }
1769
+            // There was a time-range filter
1770
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
1771
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1772
+
1773
+                // If start time OR the end time is not specified, we can do a
1774
+                // 100% accurate mysql query.
1775
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1776
+                    $requirePostFilter = false;
1777
+                }
1778
+            }
1779
+        }
1780
+        $query = $this->db->getQueryBuilder();
1781
+        $query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1782
+            ->from('calendarobjects')
1783
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1784
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1785
+            ->andWhere($query->expr()->isNull('deleted_at'));
1786
+
1787
+        if ($componentType) {
1788
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1789
+        }
1790
+
1791
+        if ($timeRange && $timeRange['start']) {
1792
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1793
+        }
1794
+        if ($timeRange && $timeRange['end']) {
1795
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1796
+        }
1797
+
1798
+        $stmt = $query->executeQuery();
1799
+
1800
+        $result = [];
1801
+        while ($row = $stmt->fetch()) {
1802
+            // if we leave it as a blob we can't read it both from the post filter and the rowToCalendarObject
1803
+            if (isset($row['calendardata'])) {
1804
+                $row['calendardata'] = $this->readBlob($row['calendardata']);
1805
+            }
1806
+
1807
+            if ($requirePostFilter) {
1808
+                // validateFilterForObject will parse the calendar data
1809
+                // catch parsing errors
1810
+                try {
1811
+                    $matches = $this->validateFilterForObject($row, $filters);
1812
+                } catch (ParseException $ex) {
1813
+                    $this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1814
+                        'app' => 'dav',
1815
+                        'exception' => $ex,
1816
+                    ]);
1817
+                    continue;
1818
+                } catch (InvalidDataException $ex) {
1819
+                    $this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1820
+                        'app' => 'dav',
1821
+                        'exception' => $ex,
1822
+                    ]);
1823
+                    continue;
1824
+                } catch (MaxInstancesExceededException $ex) {
1825
+                    $this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
1826
+                        'app' => 'dav',
1827
+                        'exception' => $ex,
1828
+                    ]);
1829
+                    continue;
1830
+                }
1831
+
1832
+                if (!$matches) {
1833
+                    continue;
1834
+                }
1835
+            }
1836
+            $result[] = $row['uri'];
1837
+            $key = $calendarId . '::' . $row['uri'] . '::' . $calendarType;
1838
+            $this->cachedObjects[$key] = $this->rowToCalendarObject($row);
1839
+        }
1840
+
1841
+        return $result;
1842
+    }
1843
+
1844
+    /**
1845
+     * custom Nextcloud search extension for CalDAV
1846
+     *
1847
+     * TODO - this should optionally cover cached calendar objects as well
1848
+     *
1849
+     * @param string $principalUri
1850
+     * @param array $filters
1851
+     * @param integer|null $limit
1852
+     * @param integer|null $offset
1853
+     * @return array
1854
+     */
1855
+    public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1856
+        return $this->atomic(function () use ($principalUri, $filters, $limit, $offset) {
1857
+            $calendars = $this->getCalendarsForUser($principalUri);
1858
+            $ownCalendars = [];
1859
+            $sharedCalendars = [];
1860
+
1861
+            $uriMapper = [];
1862
+
1863
+            foreach ($calendars as $calendar) {
1864
+                if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1865
+                    $ownCalendars[] = $calendar['id'];
1866
+                } else {
1867
+                    $sharedCalendars[] = $calendar['id'];
1868
+                }
1869
+                $uriMapper[$calendar['id']] = $calendar['uri'];
1870
+            }
1871
+            if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1872
+                return [];
1873
+            }
1874
+
1875
+            $query = $this->db->getQueryBuilder();
1876
+            // Calendar id expressions
1877
+            $calendarExpressions = [];
1878
+            foreach ($ownCalendars as $id) {
1879
+                $calendarExpressions[] = $query->expr()->andX(
1880
+                    $query->expr()->eq('c.calendarid',
1881
+                        $query->createNamedParameter($id)),
1882
+                    $query->expr()->eq('c.calendartype',
1883
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1884
+            }
1885
+            foreach ($sharedCalendars as $id) {
1886
+                $calendarExpressions[] = $query->expr()->andX(
1887
+                    $query->expr()->eq('c.calendarid',
1888
+                        $query->createNamedParameter($id)),
1889
+                    $query->expr()->eq('c.classification',
1890
+                        $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1891
+                    $query->expr()->eq('c.calendartype',
1892
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1893
+            }
1894
+
1895
+            if (count($calendarExpressions) === 1) {
1896
+                $calExpr = $calendarExpressions[0];
1897
+            } else {
1898
+                $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1899
+            }
1900
+
1901
+            // Component expressions
1902
+            $compExpressions = [];
1903
+            foreach ($filters['comps'] as $comp) {
1904
+                $compExpressions[] = $query->expr()
1905
+                    ->eq('c.componenttype', $query->createNamedParameter($comp));
1906
+            }
1907
+
1908
+            if (count($compExpressions) === 1) {
1909
+                $compExpr = $compExpressions[0];
1910
+            } else {
1911
+                $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1912
+            }
1913
+
1914
+            if (!isset($filters['props'])) {
1915
+                $filters['props'] = [];
1916
+            }
1917
+            if (!isset($filters['params'])) {
1918
+                $filters['params'] = [];
1919
+            }
1920
+
1921
+            $propParamExpressions = [];
1922
+            foreach ($filters['props'] as $prop) {
1923
+                $propParamExpressions[] = $query->expr()->andX(
1924
+                    $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1925
+                    $query->expr()->isNull('i.parameter')
1926
+                );
1927
+            }
1928
+            foreach ($filters['params'] as $param) {
1929
+                $propParamExpressions[] = $query->expr()->andX(
1930
+                    $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1931
+                    $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1932
+                );
1933
+            }
1934
+
1935
+            if (count($propParamExpressions) === 1) {
1936
+                $propParamExpr = $propParamExpressions[0];
1937
+            } else {
1938
+                $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1939
+            }
1940
+
1941
+            $query->select(['c.calendarid', 'c.uri'])
1942
+                ->from($this->dbObjectPropertiesTable, 'i')
1943
+                ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1944
+                ->where($calExpr)
1945
+                ->andWhere($compExpr)
1946
+                ->andWhere($propParamExpr)
1947
+                ->andWhere($query->expr()->iLike('i.value',
1948
+                    $query->createNamedParameter('%' . $this->db->escapeLikeParameter($filters['search-term']) . '%')))
1949
+                ->andWhere($query->expr()->isNull('deleted_at'));
1950
+
1951
+            if ($offset) {
1952
+                $query->setFirstResult($offset);
1953
+            }
1954
+            if ($limit) {
1955
+                $query->setMaxResults($limit);
1956
+            }
1957
+
1958
+            $stmt = $query->executeQuery();
1959
+
1960
+            $result = [];
1961
+            while ($row = $stmt->fetch()) {
1962
+                $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1963
+                if (!in_array($path, $result)) {
1964
+                    $result[] = $path;
1965
+                }
1966
+            }
1967
+
1968
+            return $result;
1969
+        }, $this->db);
1970
+    }
1971
+
1972
+    /**
1973
+     * used for Nextcloud's calendar API
1974
+     *
1975
+     * @param array $calendarInfo
1976
+     * @param string $pattern
1977
+     * @param array $searchProperties
1978
+     * @param array $options
1979
+     * @param integer|null $limit
1980
+     * @param integer|null $offset
1981
+     *
1982
+     * @return array
1983
+     */
1984
+    public function search(
1985
+        array $calendarInfo,
1986
+        $pattern,
1987
+        array $searchProperties,
1988
+        array $options,
1989
+        $limit,
1990
+        $offset,
1991
+    ) {
1992
+        $outerQuery = $this->db->getQueryBuilder();
1993
+        $innerQuery = $this->db->getQueryBuilder();
1994
+
1995
+        if (isset($calendarInfo['source'])) {
1996
+            $calendarType = self::CALENDAR_TYPE_SUBSCRIPTION;
1997
+        } elseif (isset($calendarInfo['federated'])) {
1998
+            $calendarType = self::CALENDAR_TYPE_FEDERATED;
1999
+        } else {
2000
+            $calendarType = self::CALENDAR_TYPE_CALENDAR;
2001
+        }
2002
+
2003
+        $innerQuery->selectDistinct('op.objectid')
2004
+            ->from($this->dbObjectPropertiesTable, 'op')
2005
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
2006
+                $outerQuery->createNamedParameter($calendarInfo['id'])))
2007
+            ->andWhere($innerQuery->expr()->eq('op.calendartype',
2008
+                $outerQuery->createNamedParameter($calendarType)));
2009
+
2010
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
2011
+            ->from('calendarobjects', 'c')
2012
+            ->where($outerQuery->expr()->isNull('deleted_at'));
2013
+
2014
+        // only return public items for shared calendars for now
2015
+        if (isset($calendarInfo['{http://owncloud.org/ns}owner-principal']) === false || $calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
2016
+            $outerQuery->andWhere($outerQuery->expr()->eq('c.classification',
2017
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2018
+        }
2019
+
2020
+        if (!empty($searchProperties)) {
2021
+            $or = [];
2022
+            foreach ($searchProperties as $searchProperty) {
2023
+                $or[] = $innerQuery->expr()->eq('op.name',
2024
+                    $outerQuery->createNamedParameter($searchProperty));
2025
+            }
2026
+            $innerQuery->andWhere($innerQuery->expr()->orX(...$or));
2027
+        }
2028
+
2029
+        if ($pattern !== '') {
2030
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
2031
+                $outerQuery->createNamedParameter('%'
2032
+                    . $this->db->escapeLikeParameter($pattern) . '%')));
2033
+        }
2034
+
2035
+        $start = null;
2036
+        $end = null;
2037
+
2038
+        $hasLimit = is_int($limit);
2039
+        $hasTimeRange = false;
2040
+
2041
+        if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2042
+            /** @var DateTimeInterface $start */
2043
+            $start = $options['timerange']['start'];
2044
+            $outerQuery->andWhere(
2045
+                $outerQuery->expr()->gt(
2046
+                    'lastoccurence',
2047
+                    $outerQuery->createNamedParameter($start->getTimestamp())
2048
+                )
2049
+            );
2050
+            $hasTimeRange = true;
2051
+        }
2052
+
2053
+        if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2054
+            /** @var DateTimeInterface $end */
2055
+            $end = $options['timerange']['end'];
2056
+            $outerQuery->andWhere(
2057
+                $outerQuery->expr()->lt(
2058
+                    'firstoccurence',
2059
+                    $outerQuery->createNamedParameter($end->getTimestamp())
2060
+                )
2061
+            );
2062
+            $hasTimeRange = true;
2063
+        }
2064
+
2065
+        if (isset($options['uid'])) {
2066
+            $outerQuery->andWhere($outerQuery->expr()->eq('uid', $outerQuery->createNamedParameter($options['uid'])));
2067
+        }
2068
+
2069
+        if (!empty($options['types'])) {
2070
+            $or = [];
2071
+            foreach ($options['types'] as $type) {
2072
+                $or[] = $outerQuery->expr()->eq('componenttype',
2073
+                    $outerQuery->createNamedParameter($type));
2074
+            }
2075
+            $outerQuery->andWhere($outerQuery->expr()->orX(...$or));
2076
+        }
2077
+
2078
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id', $outerQuery->createFunction($innerQuery->getSQL())));
2079
+
2080
+        // Without explicit order by its undefined in which order the SQL server returns the events.
2081
+        // For the pagination with hasLimit and hasTimeRange, a stable ordering is helpful.
2082
+        $outerQuery->addOrderBy('id');
2083
+
2084
+        $offset = (int)$offset;
2085
+        $outerQuery->setFirstResult($offset);
2086
+
2087
+        $calendarObjects = [];
2088
+
2089
+        if ($hasLimit && $hasTimeRange) {
2090
+            /**
2091
+             * Event recurrences are evaluated at runtime because the database only knows the first and last occurrence.
2092
+             *
2093
+             * Given, a user created 8 events with a yearly reoccurrence and two for events tomorrow.
2094
+             * The upcoming event widget asks the CalDAV backend for 7 events within the next 14 days.
2095
+             *
2096
+             * If limit 7 is applied to the SQL query, we find the 7 events with a yearly reoccurrence
2097
+             * and discard the events after evaluating the reoccurrence rules because they are not due within
2098
+             * the next 14 days and end up with an empty result even if there are two events to show.
2099
+             *
2100
+             * The workaround for search requests with a limit and time range is asking for more row than requested
2101
+             * and retrying if we have not reached the limit.
2102
+             *
2103
+             * 25 rows and 3 retries is entirely arbitrary.
2104
+             */
2105
+            $maxResults = (int)max($limit, 25);
2106
+            $outerQuery->setMaxResults($maxResults);
2107
+
2108
+            for ($attempt = $objectsCount = 0; $attempt < 3 && $objectsCount < $limit; $attempt++) {
2109
+                $objectsCount = array_push($calendarObjects, ...$this->searchCalendarObjects($outerQuery, $start, $end));
2110
+                $outerQuery->setFirstResult($offset += $maxResults);
2111
+            }
2112
+
2113
+            $calendarObjects = array_slice($calendarObjects, 0, $limit, false);
2114
+        } else {
2115
+            $outerQuery->setMaxResults($limit);
2116
+            $calendarObjects = $this->searchCalendarObjects($outerQuery, $start, $end);
2117
+        }
2118
+
2119
+        $calendarObjects = array_map(function ($o) use ($options) {
2120
+            $calendarData = Reader::read($o['calendardata']);
2121
+
2122
+            // Expand recurrences if an explicit time range is requested
2123
+            if ($calendarData instanceof VCalendar
2124
+                && isset($options['timerange']['start'], $options['timerange']['end'])) {
2125
+                $calendarData = $calendarData->expand(
2126
+                    $options['timerange']['start'],
2127
+                    $options['timerange']['end'],
2128
+                );
2129
+            }
2130
+
2131
+            $comps = $calendarData->getComponents();
2132
+            $objects = [];
2133
+            $timezones = [];
2134
+            foreach ($comps as $comp) {
2135
+                if ($comp instanceof VTimeZone) {
2136
+                    $timezones[] = $comp;
2137
+                } else {
2138
+                    $objects[] = $comp;
2139
+                }
2140
+            }
2141
+
2142
+            return [
2143
+                'id' => $o['id'],
2144
+                'type' => $o['componenttype'],
2145
+                'uid' => $o['uid'],
2146
+                'uri' => $o['uri'],
2147
+                'objects' => array_map(function ($c) {
2148
+                    return $this->transformSearchData($c);
2149
+                }, $objects),
2150
+                'timezones' => array_map(function ($c) {
2151
+                    return $this->transformSearchData($c);
2152
+                }, $timezones),
2153
+            ];
2154
+        }, $calendarObjects);
2155
+
2156
+        usort($calendarObjects, function (array $a, array $b) {
2157
+            /** @var DateTimeImmutable $startA */
2158
+            $startA = $a['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2159
+            /** @var DateTimeImmutable $startB */
2160
+            $startB = $b['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2161
+
2162
+            return $startA->getTimestamp() <=> $startB->getTimestamp();
2163
+        });
2164
+
2165
+        return $calendarObjects;
2166
+    }
2167
+
2168
+    private function searchCalendarObjects(IQueryBuilder $query, ?DateTimeInterface $start, ?DateTimeInterface $end): array {
2169
+        $calendarObjects = [];
2170
+        $filterByTimeRange = ($start instanceof DateTimeInterface) || ($end instanceof DateTimeInterface);
2171
+
2172
+        $result = $query->executeQuery();
2173
+
2174
+        while (($row = $result->fetch()) !== false) {
2175
+            if ($filterByTimeRange === false) {
2176
+                // No filter required
2177
+                $calendarObjects[] = $row;
2178
+                continue;
2179
+            }
2180
+
2181
+            try {
2182
+                $isValid = $this->validateFilterForObject($row, [
2183
+                    'name' => 'VCALENDAR',
2184
+                    'comp-filters' => [
2185
+                        [
2186
+                            'name' => 'VEVENT',
2187
+                            'comp-filters' => [],
2188
+                            'prop-filters' => [],
2189
+                            'is-not-defined' => false,
2190
+                            'time-range' => [
2191
+                                'start' => $start,
2192
+                                'end' => $end,
2193
+                            ],
2194
+                        ],
2195
+                    ],
2196
+                    'prop-filters' => [],
2197
+                    'is-not-defined' => false,
2198
+                    'time-range' => null,
2199
+                ]);
2200
+            } catch (MaxInstancesExceededException $ex) {
2201
+                $this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
2202
+                    'app' => 'dav',
2203
+                    'exception' => $ex,
2204
+                ]);
2205
+                continue;
2206
+            }
2207
+
2208
+            if (is_resource($row['calendardata'])) {
2209
+                // Put the stream back to the beginning so it can be read another time
2210
+                rewind($row['calendardata']);
2211
+            }
2212
+
2213
+            if ($isValid) {
2214
+                $calendarObjects[] = $row;
2215
+            }
2216
+        }
2217
+
2218
+        $result->closeCursor();
2219
+
2220
+        return $calendarObjects;
2221
+    }
2222
+
2223
+    /**
2224
+     * @param Component $comp
2225
+     * @return array
2226
+     */
2227
+    private function transformSearchData(Component $comp) {
2228
+        $data = [];
2229
+        /** @var Component[] $subComponents */
2230
+        $subComponents = $comp->getComponents();
2231
+        /** @var Property[] $properties */
2232
+        $properties = array_filter($comp->children(), function ($c) {
2233
+            return $c instanceof Property;
2234
+        });
2235
+        $validationRules = $comp->getValidationRules();
2236
+
2237
+        foreach ($subComponents as $subComponent) {
2238
+            $name = $subComponent->name;
2239
+            if (!isset($data[$name])) {
2240
+                $data[$name] = [];
2241
+            }
2242
+            $data[$name][] = $this->transformSearchData($subComponent);
2243
+        }
2244
+
2245
+        foreach ($properties as $property) {
2246
+            $name = $property->name;
2247
+            if (!isset($validationRules[$name])) {
2248
+                $validationRules[$name] = '*';
2249
+            }
2250
+
2251
+            $rule = $validationRules[$property->name];
2252
+            if ($rule === '+' || $rule === '*') { // multiple
2253
+                if (!isset($data[$name])) {
2254
+                    $data[$name] = [];
2255
+                }
2256
+
2257
+                $data[$name][] = $this->transformSearchProperty($property);
2258
+            } else { // once
2259
+                $data[$name] = $this->transformSearchProperty($property);
2260
+            }
2261
+        }
2262
+
2263
+        return $data;
2264
+    }
2265
+
2266
+    /**
2267
+     * @param Property $prop
2268
+     * @return array
2269
+     */
2270
+    private function transformSearchProperty(Property $prop) {
2271
+        // No need to check Date, as it extends DateTime
2272
+        if ($prop instanceof Property\ICalendar\DateTime) {
2273
+            $value = $prop->getDateTime();
2274
+        } else {
2275
+            $value = $prop->getValue();
2276
+        }
2277
+
2278
+        return [
2279
+            $value,
2280
+            $prop->parameters()
2281
+        ];
2282
+    }
2283
+
2284
+    /**
2285
+     * @param string $principalUri
2286
+     * @param string $pattern
2287
+     * @param array $componentTypes
2288
+     * @param array $searchProperties
2289
+     * @param array $searchParameters
2290
+     * @param array $options
2291
+     * @return array
2292
+     */
2293
+    public function searchPrincipalUri(string $principalUri,
2294
+        string $pattern,
2295
+        array $componentTypes,
2296
+        array $searchProperties,
2297
+        array $searchParameters,
2298
+        array $options = [],
2299
+    ): array {
2300
+        return $this->atomic(function () use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
2301
+            $escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
2302
+
2303
+            $calendarObjectIdQuery = $this->db->getQueryBuilder();
2304
+            $calendarOr = [];
2305
+            $searchOr = [];
2306
+
2307
+            // Fetch calendars and subscription
2308
+            $calendars = $this->getCalendarsForUser($principalUri);
2309
+            $subscriptions = $this->getSubscriptionsForUser($principalUri);
2310
+            foreach ($calendars as $calendar) {
2311
+                $calendarAnd = $calendarObjectIdQuery->expr()->andX(
2312
+                    $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])),
2313
+                    $calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)),
2314
+                );
2315
+
2316
+                // If it's shared, limit search to public events
2317
+                if (isset($calendar['{http://owncloud.org/ns}owner-principal'])
2318
+                    && $calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
2319
+                    $calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2320
+                }
2321
+
2322
+                $calendarOr[] = $calendarAnd;
2323
+            }
2324
+            foreach ($subscriptions as $subscription) {
2325
+                $subscriptionAnd = $calendarObjectIdQuery->expr()->andX(
2326
+                    $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])),
2327
+                    $calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)),
2328
+                );
2329
+
2330
+                // If it's shared, limit search to public events
2331
+                if (isset($subscription['{http://owncloud.org/ns}owner-principal'])
2332
+                    && $subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
2333
+                    $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2334
+                }
2335
+
2336
+                $calendarOr[] = $subscriptionAnd;
2337
+            }
2338
+
2339
+            foreach ($searchProperties as $property) {
2340
+                $propertyAnd = $calendarObjectIdQuery->expr()->andX(
2341
+                    $calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2342
+                    $calendarObjectIdQuery->expr()->isNull('cob.parameter'),
2343
+                );
2344
+
2345
+                $searchOr[] = $propertyAnd;
2346
+            }
2347
+            foreach ($searchParameters as $property => $parameter) {
2348
+                $parameterAnd = $calendarObjectIdQuery->expr()->andX(
2349
+                    $calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2350
+                    $calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)),
2351
+                );
2352
+
2353
+                $searchOr[] = $parameterAnd;
2354
+            }
2355
+
2356
+            if (empty($calendarOr)) {
2357
+                return [];
2358
+            }
2359
+            if (empty($searchOr)) {
2360
+                return [];
2361
+            }
2362
+
2363
+            $calendarObjectIdQuery->selectDistinct('cob.objectid')
2364
+                ->from($this->dbObjectPropertiesTable, 'cob')
2365
+                ->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
2366
+                ->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
2367
+                ->andWhere($calendarObjectIdQuery->expr()->orX(...$calendarOr))
2368
+                ->andWhere($calendarObjectIdQuery->expr()->orX(...$searchOr))
2369
+                ->andWhere($calendarObjectIdQuery->expr()->isNull('deleted_at'));
2370
+
2371
+            if ($pattern !== '') {
2372
+                if (!$escapePattern) {
2373
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
2374
+                } else {
2375
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
2376
+                }
2377
+            }
2378
+
2379
+            if (isset($options['limit'])) {
2380
+                $calendarObjectIdQuery->setMaxResults($options['limit']);
2381
+            }
2382
+            if (isset($options['offset'])) {
2383
+                $calendarObjectIdQuery->setFirstResult($options['offset']);
2384
+            }
2385
+            if (isset($options['timerange'])) {
2386
+                if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2387
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->gt(
2388
+                        'lastoccurence',
2389
+                        $calendarObjectIdQuery->createNamedParameter($options['timerange']['start']->getTimeStamp()),
2390
+                    ));
2391
+                }
2392
+                if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2393
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->lt(
2394
+                        'firstoccurence',
2395
+                        $calendarObjectIdQuery->createNamedParameter($options['timerange']['end']->getTimeStamp()),
2396
+                    ));
2397
+                }
2398
+            }
2399
+
2400
+            $result = $calendarObjectIdQuery->executeQuery();
2401
+            $matches = [];
2402
+            while (($row = $result->fetch()) !== false) {
2403
+                $matches[] = (int)$row['objectid'];
2404
+            }
2405
+            $result->closeCursor();
2406
+
2407
+            $query = $this->db->getQueryBuilder();
2408
+            $query->select('calendardata', 'uri', 'calendarid', 'calendartype')
2409
+                ->from('calendarobjects')
2410
+                ->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
2411
+
2412
+            $result = $query->executeQuery();
2413
+            $calendarObjects = [];
2414
+            while (($array = $result->fetch()) !== false) {
2415
+                $array['calendarid'] = (int)$array['calendarid'];
2416
+                $array['calendartype'] = (int)$array['calendartype'];
2417
+                $array['calendardata'] = $this->readBlob($array['calendardata']);
2418
+
2419
+                $calendarObjects[] = $array;
2420
+            }
2421
+            $result->closeCursor();
2422
+            return $calendarObjects;
2423
+        }, $this->db);
2424
+    }
2425
+
2426
+    /**
2427
+     * Searches through all of a users calendars and calendar objects to find
2428
+     * an object with a specific UID.
2429
+     *
2430
+     * This method should return the path to this object, relative to the
2431
+     * calendar home, so this path usually only contains two parts:
2432
+     *
2433
+     * calendarpath/objectpath.ics
2434
+     *
2435
+     * If the uid is not found, return null.
2436
+     *
2437
+     * This method should only consider * objects that the principal owns, so
2438
+     * any calendars owned by other principals that also appear in this
2439
+     * collection should be ignored.
2440
+     *
2441
+     * @param string $principalUri
2442
+     * @param string $uid
2443
+     * @return string|null
2444
+     */
2445
+    public function getCalendarObjectByUID($principalUri, $uid, $calendarUri = null) {
2446
+        $query = $this->db->getQueryBuilder();
2447
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
2448
+            ->from('calendarobjects', 'co')
2449
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
2450
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2451
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
2452
+            ->andWhere($query->expr()->isNull('co.deleted_at'));
2453
+
2454
+        if ($calendarUri !== null) {
2455
+            $query->andWhere($query->expr()->eq('c.uri', $query->createNamedParameter($calendarUri)));
2456
+        }
2457
+
2458
+        $stmt = $query->executeQuery();
2459
+        $row = $stmt->fetch();
2460
+        $stmt->closeCursor();
2461
+        if ($row) {
2462
+            return $row['calendaruri'] . '/' . $row['objecturi'];
2463
+        }
2464
+
2465
+        return null;
2466
+    }
2467
+
2468
+    public function getCalendarObjectById(string $principalUri, int $id): ?array {
2469
+        $query = $this->db->getQueryBuilder();
2470
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.calendardata', 'co.componenttype', 'co.classification', 'co.deleted_at'])
2471
+            ->selectAlias('c.uri', 'calendaruri')
2472
+            ->from('calendarobjects', 'co')
2473
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
2474
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2475
+            ->andWhere($query->expr()->eq('co.id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
2476
+        $stmt = $query->executeQuery();
2477
+        $row = $stmt->fetch();
2478
+        $stmt->closeCursor();
2479
+
2480
+        if (!$row) {
2481
+            return null;
2482
+        }
2483
+
2484
+        return [
2485
+            'id' => $row['id'],
2486
+            'uri' => $row['uri'],
2487
+            'lastmodified' => $row['lastmodified'],
2488
+            'etag' => '"' . $row['etag'] . '"',
2489
+            'calendarid' => $row['calendarid'],
2490
+            'calendaruri' => $row['calendaruri'],
2491
+            'size' => (int)$row['size'],
2492
+            'calendardata' => $this->readBlob($row['calendardata']),
2493
+            'component' => strtolower($row['componenttype']),
2494
+            'classification' => (int)$row['classification'],
2495
+            'deleted_at' => isset($row['deleted_at']) ? ((int)$row['deleted_at']) : null,
2496
+        ];
2497
+    }
2498
+
2499
+    /**
2500
+     * The getChanges method returns all the changes that have happened, since
2501
+     * the specified syncToken in the specified calendar.
2502
+     *
2503
+     * This function should return an array, such as the following:
2504
+     *
2505
+     * [
2506
+     *   'syncToken' => 'The current synctoken',
2507
+     *   'added'   => [
2508
+     *      'new.txt',
2509
+     *   ],
2510
+     *   'modified'   => [
2511
+     *      'modified.txt',
2512
+     *   ],
2513
+     *   'deleted' => [
2514
+     *      'foo.php.bak',
2515
+     *      'old.txt'
2516
+     *   ]
2517
+     * );
2518
+     *
2519
+     * The returned syncToken property should reflect the *current* syncToken
2520
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
2521
+     * property This is * needed here too, to ensure the operation is atomic.
2522
+     *
2523
+     * If the $syncToken argument is specified as null, this is an initial
2524
+     * sync, and all members should be reported.
2525
+     *
2526
+     * The modified property is an array of nodenames that have changed since
2527
+     * the last token.
2528
+     *
2529
+     * The deleted property is an array with nodenames, that have been deleted
2530
+     * from collection.
2531
+     *
2532
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
2533
+     * 1, you only have to report changes that happened only directly in
2534
+     * immediate descendants. If it's 2, it should also include changes from
2535
+     * the nodes below the child collections. (grandchildren)
2536
+     *
2537
+     * The $limit argument allows a client to specify how many results should
2538
+     * be returned at most. If the limit is not specified, it should be treated
2539
+     * as infinite.
2540
+     *
2541
+     * If the limit (infinite or not) is higher than you're willing to return,
2542
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
2543
+     *
2544
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
2545
+     * return null.
2546
+     *
2547
+     * The limit is 'suggestive'. You are free to ignore it.
2548
+     *
2549
+     * @param string $calendarId
2550
+     * @param string $syncToken
2551
+     * @param int $syncLevel
2552
+     * @param int|null $limit
2553
+     * @param int $calendarType
2554
+     * @return ?array
2555
+     */
2556
+    public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2557
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2558
+
2559
+        return $this->atomic(function () use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
2560
+            // Current synctoken
2561
+            $qb = $this->db->getQueryBuilder();
2562
+            $qb->select('synctoken')
2563
+                ->from($table)
2564
+                ->where(
2565
+                    $qb->expr()->eq('id', $qb->createNamedParameter($calendarId))
2566
+                );
2567
+            $stmt = $qb->executeQuery();
2568
+            $currentToken = $stmt->fetchOne();
2569
+            $initialSync = !is_numeric($syncToken);
2570
+
2571
+            if ($currentToken === false) {
2572
+                return null;
2573
+            }
2574
+
2575
+            // evaluate if this is a initial sync and construct appropriate command
2576
+            if ($initialSync) {
2577
+                $qb = $this->db->getQueryBuilder();
2578
+                $qb->select('uri')
2579
+                    ->from('calendarobjects')
2580
+                    ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2581
+                    ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2582
+                    ->andWhere($qb->expr()->isNull('deleted_at'));
2583
+            } else {
2584
+                $qb = $this->db->getQueryBuilder();
2585
+                $qb->select('uri', $qb->func()->max('operation'))
2586
+                    ->from('calendarchanges')
2587
+                    ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2588
+                    ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2589
+                    ->andWhere($qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)))
2590
+                    ->andWhere($qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)))
2591
+                    ->groupBy('uri');
2592
+            }
2593
+            // evaluate if limit exists
2594
+            if (is_numeric($limit)) {
2595
+                $qb->setMaxResults($limit);
2596
+            }
2597
+            // execute command
2598
+            $stmt = $qb->executeQuery();
2599
+            // build results
2600
+            $result = ['syncToken' => $currentToken, 'added' => [], 'modified' => [], 'deleted' => []];
2601
+            // retrieve results
2602
+            if ($initialSync) {
2603
+                $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
2604
+            } else {
2605
+                // \PDO::FETCH_NUM is needed due to the inconsistent field names
2606
+                // produced by doctrine for MAX() with different databases
2607
+                while ($entry = $stmt->fetch(\PDO::FETCH_NUM)) {
2608
+                    // assign uri (column 0) to appropriate mutation based on operation (column 1)
2609
+                    // forced (int) is needed as doctrine with OCI returns the operation field as string not integer
2610
+                    match ((int)$entry[1]) {
2611
+                        1 => $result['added'][] = $entry[0],
2612
+                        2 => $result['modified'][] = $entry[0],
2613
+                        3 => $result['deleted'][] = $entry[0],
2614
+                        default => $this->logger->debug('Unknown calendar change operation detected')
2615
+                    };
2616
+                }
2617
+            }
2618
+            $stmt->closeCursor();
2619
+
2620
+            return $result;
2621
+        }, $this->db);
2622
+    }
2623
+
2624
+    /**
2625
+     * Returns a list of subscriptions for a principal.
2626
+     *
2627
+     * Every subscription is an array with the following keys:
2628
+     *  * id, a unique id that will be used by other functions to modify the
2629
+     *    subscription. This can be the same as the uri or a database key.
2630
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
2631
+     *  * principaluri. The owner of the subscription. Almost always the same as
2632
+     *    principalUri passed to this method.
2633
+     *
2634
+     * Furthermore, all the subscription info must be returned too:
2635
+     *
2636
+     * 1. {DAV:}displayname
2637
+     * 2. {http://apple.com/ns/ical/}refreshrate
2638
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
2639
+     *    should not be stripped).
2640
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
2641
+     *    should not be stripped).
2642
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
2643
+     *    attachments should not be stripped).
2644
+     * 6. {http://calendarserver.org/ns/}source (Must be a
2645
+     *     Sabre\DAV\Property\Href).
2646
+     * 7. {http://apple.com/ns/ical/}calendar-color
2647
+     * 8. {http://apple.com/ns/ical/}calendar-order
2648
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
2649
+     *    (should just be an instance of
2650
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
2651
+     *    default components).
2652
+     *
2653
+     * @param string $principalUri
2654
+     * @return array
2655
+     */
2656
+    public function getSubscriptionsForUser($principalUri) {
2657
+        $fields = array_column($this->subscriptionPropertyMap, 0);
2658
+        $fields[] = 'id';
2659
+        $fields[] = 'uri';
2660
+        $fields[] = 'source';
2661
+        $fields[] = 'principaluri';
2662
+        $fields[] = 'lastmodified';
2663
+        $fields[] = 'synctoken';
2664
+
2665
+        $query = $this->db->getQueryBuilder();
2666
+        $query->select($fields)
2667
+            ->from('calendarsubscriptions')
2668
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2669
+            ->orderBy('calendarorder', 'asc');
2670
+        $stmt = $query->executeQuery();
2671
+
2672
+        $subscriptions = [];
2673
+        while ($row = $stmt->fetch()) {
2674
+            $subscription = [
2675
+                'id' => $row['id'],
2676
+                'uri' => $row['uri'],
2677
+                'principaluri' => $row['principaluri'],
2678
+                'source' => $row['source'],
2679
+                'lastmodified' => $row['lastmodified'],
2680
+
2681
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2682
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
2683
+            ];
2684
+
2685
+            $subscriptions[] = $this->rowToSubscription($row, $subscription);
2686
+        }
2687
+
2688
+        return $subscriptions;
2689
+    }
2690
+
2691
+    /**
2692
+     * Creates a new subscription for a principal.
2693
+     *
2694
+     * If the creation was a success, an id must be returned that can be used to reference
2695
+     * this subscription in other methods, such as updateSubscription.
2696
+     *
2697
+     * @param string $principalUri
2698
+     * @param string $uri
2699
+     * @param array $properties
2700
+     * @return mixed
2701
+     */
2702
+    public function createSubscription($principalUri, $uri, array $properties) {
2703
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2704
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2705
+        }
2706
+
2707
+        $values = [
2708
+            'principaluri' => $principalUri,
2709
+            'uri' => $uri,
2710
+            'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2711
+            'lastmodified' => time(),
2712
+        ];
2713
+
2714
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2715
+
2716
+        foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
2717
+            if (array_key_exists($xmlName, $properties)) {
2718
+                $values[$dbName] = $properties[$xmlName];
2719
+                if (in_array($dbName, $propertiesBoolean)) {
2720
+                    $values[$dbName] = true;
2721
+                }
2722
+            }
2723
+        }
2724
+
2725
+        [$subscriptionId, $subscriptionRow] = $this->atomic(function () use ($values) {
2726
+            $valuesToInsert = [];
2727
+            $query = $this->db->getQueryBuilder();
2728
+            foreach (array_keys($values) as $name) {
2729
+                $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2730
+            }
2731
+            $query->insert('calendarsubscriptions')
2732
+                ->values($valuesToInsert)
2733
+                ->executeStatement();
2734
+
2735
+            $subscriptionId = $query->getLastInsertId();
2736
+
2737
+            $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2738
+            return [$subscriptionId, $subscriptionRow];
2739
+        }, $this->db);
2740
+
2741
+        $this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow));
2742
+
2743
+        return $subscriptionId;
2744
+    }
2745
+
2746
+    /**
2747
+     * Updates a subscription
2748
+     *
2749
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2750
+     * To do the actual updates, you must tell this object which properties
2751
+     * you're going to process with the handle() method.
2752
+     *
2753
+     * Calling the handle method is like telling the PropPatch object "I
2754
+     * promise I can handle updating this property".
2755
+     *
2756
+     * Read the PropPatch documentation for more info and examples.
2757
+     *
2758
+     * @param mixed $subscriptionId
2759
+     * @param PropPatch $propPatch
2760
+     * @return void
2761
+     */
2762
+    public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2763
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
2764
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
2765
+
2766
+        $propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2767
+            $newValues = [];
2768
+
2769
+            foreach ($mutations as $propertyName => $propertyValue) {
2770
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
2771
+                    $newValues['source'] = $propertyValue->getHref();
2772
+                } else {
2773
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName][0];
2774
+                    $newValues[$fieldName] = $propertyValue;
2775
+                }
2776
+            }
2777
+
2778
+            $subscriptionRow = $this->atomic(function () use ($subscriptionId, $newValues) {
2779
+                $query = $this->db->getQueryBuilder();
2780
+                $query->update('calendarsubscriptions')
2781
+                    ->set('lastmodified', $query->createNamedParameter(time()));
2782
+                foreach ($newValues as $fieldName => $value) {
2783
+                    $query->set($fieldName, $query->createNamedParameter($value));
2784
+                }
2785
+                $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2786
+                    ->executeStatement();
2787
+
2788
+                return $this->getSubscriptionById($subscriptionId);
2789
+            }, $this->db);
2790
+
2791
+            $this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2792
+
2793
+            return true;
2794
+        });
2795
+    }
2796
+
2797
+    /**
2798
+     * Deletes a subscription.
2799
+     *
2800
+     * @param mixed $subscriptionId
2801
+     * @return void
2802
+     */
2803
+    public function deleteSubscription($subscriptionId) {
2804
+        $this->atomic(function () use ($subscriptionId): void {
2805
+            $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2806
+
2807
+            $query = $this->db->getQueryBuilder();
2808
+            $query->delete('calendarsubscriptions')
2809
+                ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2810
+                ->executeStatement();
2811
+
2812
+            $query = $this->db->getQueryBuilder();
2813
+            $query->delete('calendarobjects')
2814
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2815
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2816
+                ->executeStatement();
2817
+
2818
+            $query->delete('calendarchanges')
2819
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2820
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2821
+                ->executeStatement();
2822
+
2823
+            $query->delete($this->dbObjectPropertiesTable)
2824
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2825
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2826
+                ->executeStatement();
2827
+
2828
+            if ($subscriptionRow) {
2829
+                $this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2830
+            }
2831
+        }, $this->db);
2832
+    }
2833
+
2834
+    /**
2835
+     * Returns a single scheduling object for the inbox collection.
2836
+     *
2837
+     * The returned array should contain the following elements:
2838
+     *   * uri - A unique basename for the object. This will be used to
2839
+     *           construct a full uri.
2840
+     *   * calendardata - The iCalendar object
2841
+     *   * lastmodified - The last modification date. Can be an int for a unix
2842
+     *                    timestamp, or a PHP DateTime object.
2843
+     *   * etag - A unique token that must change if the object changed.
2844
+     *   * size - The size of the object, in bytes.
2845
+     *
2846
+     * @param string $principalUri
2847
+     * @param string $objectUri
2848
+     * @return array
2849
+     */
2850
+    public function getSchedulingObject($principalUri, $objectUri) {
2851
+        $query = $this->db->getQueryBuilder();
2852
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2853
+            ->from('schedulingobjects')
2854
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2855
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2856
+            ->executeQuery();
2857
+
2858
+        $row = $stmt->fetch();
2859
+
2860
+        if (!$row) {
2861
+            return null;
2862
+        }
2863
+
2864
+        return [
2865
+            'uri' => $row['uri'],
2866
+            'calendardata' => $row['calendardata'],
2867
+            'lastmodified' => $row['lastmodified'],
2868
+            'etag' => '"' . $row['etag'] . '"',
2869
+            'size' => (int)$row['size'],
2870
+        ];
2871
+    }
2872
+
2873
+    /**
2874
+     * Returns all scheduling objects for the inbox collection.
2875
+     *
2876
+     * These objects should be returned as an array. Every item in the array
2877
+     * should follow the same structure as returned from getSchedulingObject.
2878
+     *
2879
+     * The main difference is that 'calendardata' is optional.
2880
+     *
2881
+     * @param string $principalUri
2882
+     * @return array
2883
+     */
2884
+    public function getSchedulingObjects($principalUri) {
2885
+        $query = $this->db->getQueryBuilder();
2886
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2887
+            ->from('schedulingobjects')
2888
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2889
+            ->executeQuery();
2890
+
2891
+        $results = [];
2892
+        while (($row = $stmt->fetch()) !== false) {
2893
+            $results[] = [
2894
+                'calendardata' => $row['calendardata'],
2895
+                'uri' => $row['uri'],
2896
+                'lastmodified' => $row['lastmodified'],
2897
+                'etag' => '"' . $row['etag'] . '"',
2898
+                'size' => (int)$row['size'],
2899
+            ];
2900
+        }
2901
+        $stmt->closeCursor();
2902
+
2903
+        return $results;
2904
+    }
2905
+
2906
+    /**
2907
+     * Deletes a scheduling object from the inbox collection.
2908
+     *
2909
+     * @param string $principalUri
2910
+     * @param string $objectUri
2911
+     * @return void
2912
+     */
2913
+    public function deleteSchedulingObject($principalUri, $objectUri) {
2914
+        $this->cachedObjects = [];
2915
+        $query = $this->db->getQueryBuilder();
2916
+        $query->delete('schedulingobjects')
2917
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2918
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2919
+            ->executeStatement();
2920
+    }
2921
+
2922
+    /**
2923
+     * Deletes all scheduling objects last modified before $modifiedBefore from the inbox collection.
2924
+     *
2925
+     * @param int $modifiedBefore
2926
+     * @param int $limit
2927
+     * @return void
2928
+     */
2929
+    public function deleteOutdatedSchedulingObjects(int $modifiedBefore, int $limit): void {
2930
+        $query = $this->db->getQueryBuilder();
2931
+        $query->select('id')
2932
+            ->from('schedulingobjects')
2933
+            ->where($query->expr()->lt('lastmodified', $query->createNamedParameter($modifiedBefore)))
2934
+            ->setMaxResults($limit);
2935
+        $result = $query->executeQuery();
2936
+        $count = $result->rowCount();
2937
+        if ($count === 0) {
2938
+            return;
2939
+        }
2940
+        $ids = array_map(static function (array $id) {
2941
+            return (int)$id[0];
2942
+        }, $result->fetchAll(\PDO::FETCH_NUM));
2943
+        $result->closeCursor();
2944
+
2945
+        $numDeleted = 0;
2946
+        $deleteQuery = $this->db->getQueryBuilder();
2947
+        $deleteQuery->delete('schedulingobjects')
2948
+            ->where($deleteQuery->expr()->in('id', $deleteQuery->createParameter('ids'), IQueryBuilder::PARAM_INT_ARRAY));
2949
+        foreach (array_chunk($ids, 1000) as $chunk) {
2950
+            $deleteQuery->setParameter('ids', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
2951
+            $numDeleted += $deleteQuery->executeStatement();
2952
+        }
2953
+
2954
+        if ($numDeleted === $limit) {
2955
+            $this->logger->info("Deleted $limit scheduling objects, continuing with next batch");
2956
+            $this->deleteOutdatedSchedulingObjects($modifiedBefore, $limit);
2957
+        }
2958
+    }
2959
+
2960
+    /**
2961
+     * Creates a new scheduling object. This should land in a users' inbox.
2962
+     *
2963
+     * @param string $principalUri
2964
+     * @param string $objectUri
2965
+     * @param string $objectData
2966
+     * @return void
2967
+     */
2968
+    public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2969
+        $this->cachedObjects = [];
2970
+        $query = $this->db->getQueryBuilder();
2971
+        $query->insert('schedulingobjects')
2972
+            ->values([
2973
+                'principaluri' => $query->createNamedParameter($principalUri),
2974
+                'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2975
+                'uri' => $query->createNamedParameter($objectUri),
2976
+                'lastmodified' => $query->createNamedParameter(time()),
2977
+                'etag' => $query->createNamedParameter(md5($objectData)),
2978
+                'size' => $query->createNamedParameter(strlen($objectData))
2979
+            ])
2980
+            ->executeStatement();
2981
+    }
2982
+
2983
+    /**
2984
+     * Adds a change record to the calendarchanges table.
2985
+     *
2986
+     * @param mixed $calendarId
2987
+     * @param string[] $objectUris
2988
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2989
+     * @param int $calendarType
2990
+     * @return void
2991
+     */
2992
+    protected function addChanges(int $calendarId, array $objectUris, int $operation, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
2993
+        $this->cachedObjects = [];
2994
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2995
+
2996
+        $this->atomic(function () use ($calendarId, $objectUris, $operation, $calendarType, $table): void {
2997
+            $query = $this->db->getQueryBuilder();
2998
+            $query->select('synctoken')
2999
+                ->from($table)
3000
+                ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
3001
+            $result = $query->executeQuery();
3002
+            $syncToken = (int)$result->fetchOne();
3003
+            $result->closeCursor();
3004
+
3005
+            $query = $this->db->getQueryBuilder();
3006
+            $query->insert('calendarchanges')
3007
+                ->values([
3008
+                    'uri' => $query->createParameter('uri'),
3009
+                    'synctoken' => $query->createNamedParameter($syncToken),
3010
+                    'calendarid' => $query->createNamedParameter($calendarId),
3011
+                    'operation' => $query->createNamedParameter($operation),
3012
+                    'calendartype' => $query->createNamedParameter($calendarType),
3013
+                    'created_at' => $query->createNamedParameter(time()),
3014
+                ]);
3015
+            foreach ($objectUris as $uri) {
3016
+                $query->setParameter('uri', $uri);
3017
+                $query->executeStatement();
3018
+            }
3019
+
3020
+            $query = $this->db->getQueryBuilder();
3021
+            $query->update($table)
3022
+                ->set('synctoken', $query->createNamedParameter($syncToken + 1, IQueryBuilder::PARAM_INT))
3023
+                ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
3024
+                ->executeStatement();
3025
+        }, $this->db);
3026
+    }
3027
+
3028
+    public function restoreChanges(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
3029
+        $this->cachedObjects = [];
3030
+
3031
+        $this->atomic(function () use ($calendarId, $calendarType): void {
3032
+            $qbAdded = $this->db->getQueryBuilder();
3033
+            $qbAdded->select('uri')
3034
+                ->from('calendarobjects')
3035
+                ->where(
3036
+                    $qbAdded->expr()->andX(
3037
+                        $qbAdded->expr()->eq('calendarid', $qbAdded->createNamedParameter($calendarId)),
3038
+                        $qbAdded->expr()->eq('calendartype', $qbAdded->createNamedParameter($calendarType)),
3039
+                        $qbAdded->expr()->isNull('deleted_at'),
3040
+                    )
3041
+                );
3042
+            $resultAdded = $qbAdded->executeQuery();
3043
+            $addedUris = $resultAdded->fetchAll(\PDO::FETCH_COLUMN);
3044
+            $resultAdded->closeCursor();
3045
+            // Track everything as changed
3046
+            // Tracking the creation is not necessary because \OCA\DAV\CalDAV\CalDavBackend::getChangesForCalendar
3047
+            // only returns the last change per object.
3048
+            $this->addChanges($calendarId, $addedUris, 2, $calendarType);
3049
+
3050
+            $qbDeleted = $this->db->getQueryBuilder();
3051
+            $qbDeleted->select('uri')
3052
+                ->from('calendarobjects')
3053
+                ->where(
3054
+                    $qbDeleted->expr()->andX(
3055
+                        $qbDeleted->expr()->eq('calendarid', $qbDeleted->createNamedParameter($calendarId)),
3056
+                        $qbDeleted->expr()->eq('calendartype', $qbDeleted->createNamedParameter($calendarType)),
3057
+                        $qbDeleted->expr()->isNotNull('deleted_at'),
3058
+                    )
3059
+                );
3060
+            $resultDeleted = $qbDeleted->executeQuery();
3061
+            $deletedUris = array_map(function (string $uri) {
3062
+                return str_replace('-deleted.ics', '.ics', $uri);
3063
+            }, $resultDeleted->fetchAll(\PDO::FETCH_COLUMN));
3064
+            $resultDeleted->closeCursor();
3065
+            $this->addChanges($calendarId, $deletedUris, 3, $calendarType);
3066
+        }, $this->db);
3067
+    }
3068
+
3069
+    /**
3070
+     * Parses some information from calendar objects, used for optimized
3071
+     * calendar-queries.
3072
+     *
3073
+     * Returns an array with the following keys:
3074
+     *   * etag - An md5 checksum of the object without the quotes.
3075
+     *   * size - Size of the object in bytes
3076
+     *   * componentType - VEVENT, VTODO or VJOURNAL
3077
+     *   * firstOccurence
3078
+     *   * lastOccurence
3079
+     *   * uid - value of the UID property
3080
+     *
3081
+     * @param string $calendarData
3082
+     * @return array
3083
+     */
3084
+    public function getDenormalizedData(string $calendarData): array {
3085
+        $vObject = Reader::read($calendarData);
3086
+        $vEvents = [];
3087
+        $componentType = null;
3088
+        $component = null;
3089
+        $firstOccurrence = null;
3090
+        $lastOccurrence = null;
3091
+        $uid = null;
3092
+        $classification = self::CLASSIFICATION_PUBLIC;
3093
+        $hasDTSTART = false;
3094
+        foreach ($vObject->getComponents() as $component) {
3095
+            if ($component->name !== 'VTIMEZONE') {
3096
+                // Finding all VEVENTs, and track them
3097
+                if ($component->name === 'VEVENT') {
3098
+                    $vEvents[] = $component;
3099
+                    if ($component->DTSTART) {
3100
+                        $hasDTSTART = true;
3101
+                    }
3102
+                }
3103
+                // Track first component type and uid
3104
+                if ($uid === null) {
3105
+                    $componentType = $component->name;
3106
+                    $uid = (string)$component->UID;
3107
+                }
3108
+            }
3109
+        }
3110
+        if (!$componentType) {
3111
+            throw new BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
3112
+        }
3113
+
3114
+        if ($hasDTSTART) {
3115
+            $component = $vEvents[0];
3116
+
3117
+            // Finding the last occurrence is a bit harder
3118
+            if (!isset($component->RRULE) && count($vEvents) === 1) {
3119
+                $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
3120
+                if (isset($component->DTEND)) {
3121
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
3122
+                } elseif (isset($component->DURATION)) {
3123
+                    $endDate = clone $component->DTSTART->getDateTime();
3124
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
3125
+                    $lastOccurrence = $endDate->getTimeStamp();
3126
+                } elseif (!$component->DTSTART->hasTime()) {
3127
+                    $endDate = clone $component->DTSTART->getDateTime();
3128
+                    $endDate->modify('+1 day');
3129
+                    $lastOccurrence = $endDate->getTimeStamp();
3130
+                } else {
3131
+                    $lastOccurrence = $firstOccurrence;
3132
+                }
3133
+            } else {
3134
+                try {
3135
+                    $it = new EventIterator($vEvents);
3136
+                } catch (NoInstancesException $e) {
3137
+                    $this->logger->debug('Caught no instance exception for calendar data. This usually indicates invalid calendar data.', [
3138
+                        'app' => 'dav',
3139
+                        'exception' => $e,
3140
+                    ]);
3141
+                    throw new Forbidden($e->getMessage());
3142
+                }
3143
+                $maxDate = new DateTime(self::MAX_DATE);
3144
+                $firstOccurrence = $it->getDtStart()->getTimestamp();
3145
+                if ($it->isInfinite()) {
3146
+                    $lastOccurrence = $maxDate->getTimestamp();
3147
+                } else {
3148
+                    $end = $it->getDtEnd();
3149
+                    while ($it->valid() && $end < $maxDate) {
3150
+                        $end = $it->getDtEnd();
3151
+                        $it->next();
3152
+                    }
3153
+                    $lastOccurrence = $end->getTimestamp();
3154
+                }
3155
+            }
3156
+        }
3157
+
3158
+        if ($component->CLASS) {
3159
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
3160
+            switch ($component->CLASS->getValue()) {
3161
+                case 'PUBLIC':
3162
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
3163
+                    break;
3164
+                case 'CONFIDENTIAL':
3165
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
3166
+                    break;
3167
+            }
3168
+        }
3169
+        return [
3170
+            'etag' => md5($calendarData),
3171
+            'size' => strlen($calendarData),
3172
+            'componentType' => $componentType,
3173
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
3174
+            'lastOccurence' => is_null($lastOccurrence) ? null : max(0, $lastOccurrence),
3175
+            'uid' => $uid,
3176
+            'classification' => $classification
3177
+        ];
3178
+    }
3179
+
3180
+    /**
3181
+     * @param $cardData
3182
+     * @return bool|string
3183
+     */
3184
+    private function readBlob($cardData) {
3185
+        if (is_resource($cardData)) {
3186
+            return stream_get_contents($cardData);
3187
+        }
3188
+
3189
+        return $cardData;
3190
+    }
3191
+
3192
+    /**
3193
+     * @param list<array{href: string, commonName: string, readOnly: bool}> $add
3194
+     * @param list<string> $remove
3195
+     */
3196
+    public function updateShares(IShareable $shareable, array $add, array $remove): void {
3197
+        $this->atomic(function () use ($shareable, $add, $remove): void {
3198
+            $calendarId = $shareable->getResourceId();
3199
+            $calendarRow = $this->getCalendarById($calendarId);
3200
+            if ($calendarRow === null) {
3201
+                throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $calendarId);
3202
+            }
3203
+            $oldShares = $this->getShares($calendarId);
3204
+
3205
+            $this->calendarSharingBackend->updateShares($shareable, $add, $remove, $oldShares);
3206
+
3207
+            $this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent($calendarId, $calendarRow, $oldShares, $add, $remove));
3208
+        }, $this->db);
3209
+    }
3210
+
3211
+    /**
3212
+     * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
3213
+     */
3214
+    public function getShares(int $resourceId): array {
3215
+        return $this->calendarSharingBackend->getShares($resourceId);
3216
+    }
3217
+
3218
+    public function getSharesByShareePrincipal(string $principal): array {
3219
+        return $this->calendarSharingBackend->getSharesByShareePrincipal($principal);
3220
+    }
3221
+
3222
+    public function preloadShares(array $resourceIds): void {
3223
+        $this->calendarSharingBackend->preloadShares($resourceIds);
3224
+    }
3225
+
3226
+    /**
3227
+     * @param boolean $value
3228
+     * @param Calendar $calendar
3229
+     * @return string|null
3230
+     */
3231
+    public function setPublishStatus($value, $calendar) {
3232
+        $publishStatus = $this->atomic(function () use ($value, $calendar) {
3233
+            $calendarId = $calendar->getResourceId();
3234
+            $calendarData = $this->getCalendarById($calendarId);
3235
+
3236
+            $query = $this->db->getQueryBuilder();
3237
+            if ($value) {
3238
+                $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
3239
+                $query->insert('dav_shares')
3240
+                    ->values([
3241
+                        'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
3242
+                        'type' => $query->createNamedParameter('calendar'),
3243
+                        'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
3244
+                        'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
3245
+                        'publicuri' => $query->createNamedParameter($publicUri)
3246
+                    ]);
3247
+                $query->executeStatement();
3248
+
3249
+                $this->dispatcher->dispatchTyped(new CalendarPublishedEvent($calendarId, $calendarData, $publicUri));
3250
+                return $publicUri;
3251
+            }
3252
+            $query->delete('dav_shares')
3253
+                ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3254
+                ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
3255
+            $query->executeStatement();
3256
+
3257
+            $this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent($calendarId, $calendarData));
3258
+            return null;
3259
+        }, $this->db);
3260
+
3261
+        $this->publishStatusCache->set((string)$calendar->getResourceId(), $publishStatus ?? false);
3262
+        return $publishStatus;
3263
+    }
3264
+
3265
+    /**
3266
+     * @param Calendar $calendar
3267
+     * @return string|false
3268
+     */
3269
+    public function getPublishStatus($calendar) {
3270
+        $cached = $this->publishStatusCache->get((string)$calendar->getResourceId());
3271
+        if ($cached !== null) {
3272
+            return $cached;
3273
+        }
3274
+
3275
+        $query = $this->db->getQueryBuilder();
3276
+        $result = $query->select('publicuri')
3277
+            ->from('dav_shares')
3278
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3279
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
3280
+            ->executeQuery();
3281
+
3282
+        $publishStatus = $result->fetchOne();
3283
+        $result->closeCursor();
3284
+
3285
+        $this->publishStatusCache->set((string)$calendar->getResourceId(), $publishStatus);
3286
+        return $publishStatus;
3287
+    }
3288
+
3289
+    /**
3290
+     * @param int[] $resourceIds
3291
+     */
3292
+    public function preloadPublishStatuses(array $resourceIds): void {
3293
+        $query = $this->db->getQueryBuilder();
3294
+        $result = $query->select('resourceid', 'publicuri')
3295
+            ->from('dav_shares')
3296
+            ->where($query->expr()->in(
3297
+                'resourceid',
3298
+                $query->createNamedParameter($resourceIds, IQueryBuilder::PARAM_INT_ARRAY),
3299
+                IQueryBuilder::PARAM_INT_ARRAY,
3300
+            ))
3301
+            ->andWhere($query->expr()->eq(
3302
+                'access',
3303
+                $query->createNamedParameter(self::ACCESS_PUBLIC, IQueryBuilder::PARAM_INT),
3304
+                IQueryBuilder::PARAM_INT,
3305
+            ))
3306
+            ->executeQuery();
3307
+
3308
+        $hasPublishStatuses = [];
3309
+        while ($row = $result->fetch()) {
3310
+            $this->publishStatusCache->set((string)$row['resourceid'], $row['publicuri']);
3311
+            $hasPublishStatuses[(int)$row['resourceid']] = true;
3312
+        }
3313
+
3314
+        // Also remember resources with no publish status
3315
+        foreach ($resourceIds as $resourceId) {
3316
+            if (!isset($hasPublishStatuses[$resourceId])) {
3317
+                $this->publishStatusCache->set((string)$resourceId, false);
3318
+            }
3319
+        }
3320
+
3321
+        $result->closeCursor();
3322
+    }
3323
+
3324
+    /**
3325
+     * @param int $resourceId
3326
+     * @param list<array{privilege: string, principal: string, protected: bool}> $acl
3327
+     * @return list<array{privilege: string, principal: string, protected: bool}>
3328
+     */
3329
+    public function applyShareAcl(int $resourceId, array $acl): array {
3330
+        $shares = $this->calendarSharingBackend->getShares($resourceId);
3331
+        return $this->calendarSharingBackend->applyShareAcl($shares, $acl);
3332
+    }
3333
+
3334
+    /**
3335
+     * update properties table
3336
+     *
3337
+     * @param int $calendarId
3338
+     * @param string $objectUri
3339
+     * @param string $calendarData
3340
+     * @param int $calendarType
3341
+     */
3342
+    public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
3343
+        $this->cachedObjects = [];
3344
+        $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $calendarType): void {
3345
+            $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
3346
+
3347
+            try {
3348
+                $vCalendar = $this->readCalendarData($calendarData);
3349
+            } catch (\Exception $ex) {
3350
+                return;
3351
+            }
3352
+
3353
+            $this->purgeProperties($calendarId, $objectId);
3354
+
3355
+            $query = $this->db->getQueryBuilder();
3356
+            $query->insert($this->dbObjectPropertiesTable)
3357
+                ->values(
3358
+                    [
3359
+                        'calendarid' => $query->createNamedParameter($calendarId),
3360
+                        'calendartype' => $query->createNamedParameter($calendarType),
3361
+                        'objectid' => $query->createNamedParameter($objectId),
3362
+                        'name' => $query->createParameter('name'),
3363
+                        'parameter' => $query->createParameter('parameter'),
3364
+                        'value' => $query->createParameter('value'),
3365
+                    ]
3366
+                );
3367
+
3368
+            $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
3369
+            foreach ($vCalendar->getComponents() as $component) {
3370
+                if (!in_array($component->name, $indexComponents)) {
3371
+                    continue;
3372
+                }
3373
+
3374
+                foreach ($component->children() as $property) {
3375
+                    if (in_array($property->name, self::INDEXED_PROPERTIES, true)) {
3376
+                        $value = $property->getValue();
3377
+                        // is this a shitty db?
3378
+                        if (!$this->db->supports4ByteText()) {
3379
+                            $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3380
+                        }
3381
+                        $value = mb_strcut($value, 0, 254);
3382
+
3383
+                        $query->setParameter('name', $property->name);
3384
+                        $query->setParameter('parameter', null);
3385
+                        $query->setParameter('value', mb_strcut($value, 0, 254));
3386
+                        $query->executeStatement();
3387
+                    }
3388
+
3389
+                    if (array_key_exists($property->name, self::$indexParameters)) {
3390
+                        $parameters = $property->parameters();
3391
+                        $indexedParametersForProperty = self::$indexParameters[$property->name];
3392
+
3393
+                        foreach ($parameters as $key => $value) {
3394
+                            if (in_array($key, $indexedParametersForProperty)) {
3395
+                                // is this a shitty db?
3396
+                                if ($this->db->supports4ByteText()) {
3397
+                                    $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3398
+                                }
3399
+
3400
+                                $query->setParameter('name', $property->name);
3401
+                                $query->setParameter('parameter', mb_strcut($key, 0, 254));
3402
+                                $query->setParameter('value', mb_strcut($value, 0, 254));
3403
+                                $query->executeStatement();
3404
+                            }
3405
+                        }
3406
+                    }
3407
+                }
3408
+            }
3409
+        }, $this->db);
3410
+    }
3411
+
3412
+    /**
3413
+     * deletes all birthday calendars
3414
+     */
3415
+    public function deleteAllBirthdayCalendars() {
3416
+        $this->atomic(function (): void {
3417
+            $query = $this->db->getQueryBuilder();
3418
+            $result = $query->select(['id'])->from('calendars')
3419
+                ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
3420
+                ->executeQuery();
3421
+
3422
+            while (($row = $result->fetch()) !== false) {
3423
+                $this->deleteCalendar(
3424
+                    $row['id'],
3425
+                    true // No data to keep in the trashbin, if the user re-enables then we regenerate
3426
+                );
3427
+            }
3428
+            $result->closeCursor();
3429
+        }, $this->db);
3430
+    }
3431
+
3432
+    /**
3433
+     * @param $subscriptionId
3434
+     */
3435
+    public function purgeAllCachedEventsForSubscription($subscriptionId) {
3436
+        $this->atomic(function () use ($subscriptionId): void {
3437
+            $query = $this->db->getQueryBuilder();
3438
+            $query->select('uri')
3439
+                ->from('calendarobjects')
3440
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3441
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
3442
+            $stmt = $query->executeQuery();
3443
+
3444
+            $uris = [];
3445
+            while (($row = $stmt->fetch()) !== false) {
3446
+                $uris[] = $row['uri'];
3447
+            }
3448
+            $stmt->closeCursor();
3449
+
3450
+            $query = $this->db->getQueryBuilder();
3451
+            $query->delete('calendarobjects')
3452
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3453
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3454
+                ->executeStatement();
3455
+
3456
+            $query = $this->db->getQueryBuilder();
3457
+            $query->delete('calendarchanges')
3458
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3459
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3460
+                ->executeStatement();
3461
+
3462
+            $query = $this->db->getQueryBuilder();
3463
+            $query->delete($this->dbObjectPropertiesTable)
3464
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3465
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3466
+                ->executeStatement();
3467
+
3468
+            $this->addChanges($subscriptionId, $uris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3469
+        }, $this->db);
3470
+    }
3471
+
3472
+    /**
3473
+     * @param int $subscriptionId
3474
+     * @param array<int> $calendarObjectIds
3475
+     * @param array<string> $calendarObjectUris
3476
+     */
3477
+    public function purgeCachedEventsForSubscription(int $subscriptionId, array $calendarObjectIds, array $calendarObjectUris): void {
3478
+        if (empty($calendarObjectUris)) {
3479
+            return;
3480
+        }
3481
+
3482
+        $this->atomic(function () use ($subscriptionId, $calendarObjectIds, $calendarObjectUris): void {
3483
+            foreach (array_chunk($calendarObjectIds, 1000) as $chunk) {
3484
+                $query = $this->db->getQueryBuilder();
3485
+                $query->delete($this->dbObjectPropertiesTable)
3486
+                    ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3487
+                    ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3488
+                    ->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3489
+                    ->executeStatement();
3490
+
3491
+                $query = $this->db->getQueryBuilder();
3492
+                $query->delete('calendarobjects')
3493
+                    ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3494
+                    ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3495
+                    ->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3496
+                    ->executeStatement();
3497
+            }
3498
+
3499
+            foreach (array_chunk($calendarObjectUris, 1000) as $chunk) {
3500
+                $query = $this->db->getQueryBuilder();
3501
+                $query->delete('calendarchanges')
3502
+                    ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3503
+                    ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3504
+                    ->andWhere($query->expr()->in('uri', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
3505
+                    ->executeStatement();
3506
+            }
3507
+            $this->addChanges($subscriptionId, $calendarObjectUris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3508
+        }, $this->db);
3509
+    }
3510
+
3511
+    /**
3512
+     * Move a calendar from one user to another
3513
+     *
3514
+     * @param string $uriName
3515
+     * @param string $uriOrigin
3516
+     * @param string $uriDestination
3517
+     * @param string $newUriName (optional) the new uriName
3518
+     */
3519
+    public function moveCalendar($uriName, $uriOrigin, $uriDestination, $newUriName = null) {
3520
+        $query = $this->db->getQueryBuilder();
3521
+        $query->update('calendars')
3522
+            ->set('principaluri', $query->createNamedParameter($uriDestination))
3523
+            ->set('uri', $query->createNamedParameter($newUriName ?: $uriName))
3524
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
3525
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
3526
+            ->executeStatement();
3527
+    }
3528
+
3529
+    /**
3530
+     * read VCalendar data into a VCalendar object
3531
+     *
3532
+     * @param string $objectData
3533
+     * @return VCalendar
3534
+     */
3535
+    protected function readCalendarData($objectData) {
3536
+        return Reader::read($objectData);
3537
+    }
3538
+
3539
+    /**
3540
+     * delete all properties from a given calendar object
3541
+     *
3542
+     * @param int $calendarId
3543
+     * @param int $objectId
3544
+     */
3545
+    protected function purgeProperties($calendarId, $objectId) {
3546
+        $this->cachedObjects = [];
3547
+        $query = $this->db->getQueryBuilder();
3548
+        $query->delete($this->dbObjectPropertiesTable)
3549
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
3550
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
3551
+        $query->executeStatement();
3552
+    }
3553
+
3554
+    /**
3555
+     * get ID from a given calendar object
3556
+     *
3557
+     * @param int $calendarId
3558
+     * @param string $uri
3559
+     * @param int $calendarType
3560
+     * @return int
3561
+     */
3562
+    protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
3563
+        $query = $this->db->getQueryBuilder();
3564
+        $query->select('id')
3565
+            ->from('calendarobjects')
3566
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
3567
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
3568
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
3569
+
3570
+        $result = $query->executeQuery();
3571
+        $objectIds = $result->fetch();
3572
+        $result->closeCursor();
3573
+
3574
+        if (!isset($objectIds['id'])) {
3575
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
3576
+        }
3577
+
3578
+        return (int)$objectIds['id'];
3579
+    }
3580
+
3581
+    /**
3582
+     * @throws \InvalidArgumentException
3583
+     */
3584
+    public function pruneOutdatedSyncTokens(int $keep, int $retention): int {
3585
+        if ($keep < 0) {
3586
+            throw new \InvalidArgumentException();
3587
+        }
3588
+
3589
+        $query = $this->db->getQueryBuilder();
3590
+        $query->select($query->func()->max('id'))
3591
+            ->from('calendarchanges');
3592
+
3593
+        $result = $query->executeQuery();
3594
+        $maxId = (int)$result->fetchOne();
3595
+        $result->closeCursor();
3596
+        if (!$maxId || $maxId < $keep) {
3597
+            return 0;
3598
+        }
3599
+
3600
+        $query = $this->db->getQueryBuilder();
3601
+        $query->delete('calendarchanges')
3602
+            ->where(
3603
+                $query->expr()->lte('id', $query->createNamedParameter($maxId - $keep, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
3604
+                $query->expr()->lte('created_at', $query->createNamedParameter($retention)),
3605
+            );
3606
+        return $query->executeStatement();
3607
+    }
3608
+
3609
+    /**
3610
+     * return legacy endpoint principal name to new principal name
3611
+     *
3612
+     * @param $principalUri
3613
+     * @param $toV2
3614
+     * @return string
3615
+     */
3616
+    private function convertPrincipal($principalUri, $toV2) {
3617
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
3618
+            [, $name] = Uri\split($principalUri);
3619
+            if ($toV2 === true) {
3620
+                return "principals/users/$name";
3621
+            }
3622
+            return "principals/$name";
3623
+        }
3624
+        return $principalUri;
3625
+    }
3626
+
3627
+    /**
3628
+     * adds information about an owner to the calendar data
3629
+     *
3630
+     */
3631
+    private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
3632
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
3633
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
3634
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
3635
+            $uri = $calendarInfo[$ownerPrincipalKey];
3636
+        } else {
3637
+            $uri = $calendarInfo['principaluri'];
3638
+        }
3639
+
3640
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
3641
+        if (isset($principalInformation['{DAV:}displayname'])) {
3642
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
3643
+        }
3644
+        return $calendarInfo;
3645
+    }
3646
+
3647
+    private function addResourceTypeToCalendar(array $row, array $calendar): array {
3648
+        if (isset($row['deleted_at'])) {
3649
+            // Columns is set and not null -> this is a deleted calendar
3650
+            // we send a custom resourcetype to hide the deleted calendar
3651
+            // from ordinary DAV clients, but the Calendar app will know
3652
+            // how to handle this special resource.
3653
+            $calendar['{DAV:}resourcetype'] = new DAV\Xml\Property\ResourceType([
3654
+                '{DAV:}collection',
3655
+                sprintf('{%s}deleted-calendar', \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD),
3656
+            ]);
3657
+        }
3658
+        return $calendar;
3659
+    }
3660
+
3661
+    /**
3662
+     * Amend the calendar info with database row data
3663
+     *
3664
+     * @param array $row
3665
+     * @param array $calendar
3666
+     *
3667
+     * @return array
3668
+     */
3669
+    private function rowToCalendar($row, array $calendar): array {
3670
+        foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
3671
+            $value = $row[$dbName];
3672
+            if ($value !== null) {
3673
+                settype($value, $type);
3674
+            }
3675
+            $calendar[$xmlName] = $value;
3676
+        }
3677
+        return $calendar;
3678
+    }
3679
+
3680
+    /**
3681
+     * Amend the subscription info with database row data
3682
+     *
3683
+     * @param array $row
3684
+     * @param array $subscription
3685
+     *
3686
+     * @return array
3687
+     */
3688
+    private function rowToSubscription($row, array $subscription): array {
3689
+        foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
3690
+            $value = $row[$dbName];
3691
+            if ($value !== null) {
3692
+                settype($value, $type);
3693
+            }
3694
+            $subscription[$xmlName] = $value;
3695
+        }
3696
+        return $subscription;
3697
+    }
3698
+
3699
+    /**
3700
+     * delete all invitations from a given calendar
3701
+     *
3702
+     * @since 31.0.0
3703
+     *
3704
+     * @param int $calendarId
3705
+     *
3706
+     * @return void
3707
+     */
3708
+    protected function purgeCalendarInvitations(int $calendarId): void {
3709
+        // select all calendar object uid's
3710
+        $cmd = $this->db->getQueryBuilder();
3711
+        $cmd->select('uid')
3712
+            ->from($this->dbObjectsTable)
3713
+            ->where($cmd->expr()->eq('calendarid', $cmd->createNamedParameter($calendarId)));
3714
+        $allIds = $cmd->executeQuery()->fetchAll(\PDO::FETCH_COLUMN);
3715
+        // delete all links that match object uid's
3716
+        $cmd = $this->db->getQueryBuilder();
3717
+        $cmd->delete($this->dbObjectInvitationsTable)
3718
+            ->where($cmd->expr()->in('uid', $cmd->createParameter('uids'), IQueryBuilder::PARAM_STR_ARRAY));
3719
+        foreach (array_chunk($allIds, 1000) as $chunkIds) {
3720
+            $cmd->setParameter('uids', $chunkIds, IQueryBuilder::PARAM_STR_ARRAY);
3721
+            $cmd->executeStatement();
3722
+        }
3723
+    }
3724
+
3725
+    /**
3726
+     * Delete all invitations from a given calendar event
3727
+     *
3728
+     * @since 31.0.0
3729
+     *
3730
+     * @param string $eventId UID of the event
3731
+     *
3732
+     * @return void
3733
+     */
3734
+    protected function purgeObjectInvitations(string $eventId): void {
3735
+        $cmd = $this->db->getQueryBuilder();
3736
+        $cmd->delete($this->dbObjectInvitationsTable)
3737
+            ->where($cmd->expr()->eq('uid', $cmd->createNamedParameter($eventId, IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR));
3738
+        $cmd->executeStatement();
3739
+    }
3740
+
3741
+    public function unshare(IShareable $shareable, string $principal): void {
3742
+        $this->atomic(function () use ($shareable, $principal): void {
3743
+            $calendarData = $this->getCalendarById($shareable->getResourceId());
3744
+            if ($calendarData === null) {
3745
+                throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $shareable->getResourceId());
3746
+            }
3747
+
3748
+            $oldShares = $this->getShares($shareable->getResourceId());
3749
+            $unshare = $this->calendarSharingBackend->unshare($shareable, $principal);
3750
+
3751
+            if ($unshare) {
3752
+                $this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent(
3753
+                    $shareable->getResourceId(),
3754
+                    $calendarData,
3755
+                    $oldShares,
3756
+                    [],
3757
+                    [$principal]
3758
+                ));
3759
+            }
3760
+        }, $this->db);
3761
+    }
3762
+
3763
+    /**
3764
+     * @return array<string, mixed>[]
3765
+     */
3766
+    public function getFederatedCalendarsForUser(string $principalUri): array {
3767
+        $federatedCalendars = $this->federatedCalendarMapper->findByPrincipalUri($principalUri);
3768
+        return array_map(
3769
+            static fn (FederatedCalendarEntity $entity) => $entity->toCalendarInfo(),
3770
+            $federatedCalendars,
3771
+        );
3772
+    }
3773
+
3774
+    public function getFederatedCalendarByUri(string $principalUri, string $uri): ?array {
3775
+        $federatedCalendar = $this->federatedCalendarMapper->findByUri($principalUri, $uri);
3776
+        return $federatedCalendar?->toCalendarInfo();
3777
+    }
3778 3778
 }
Please login to merge, or discard this patch.
Spacing   +173 added lines, -173 removed lines patch added patch discarded remove patch
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 		'{urn:ietf:params:xml:ns:caldav}calendar-timezone' => ['timezone', 'string'],
151 151
 		'{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
152 152
 		'{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
153
-		'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => ['deleted_at', 'int'],
153
+		'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}deleted-at' => ['deleted_at', 'int'],
154 154
 	];
155 155
 
156 156
 	/**
@@ -246,7 +246,7 @@  discard block
 block discarded – undo
246 246
 		}
247 247
 
248 248
 		$result = $query->executeQuery();
249
-		$column = (int)$result->fetchOne();
249
+		$column = (int) $result->fetchOne();
250 250
 		$result->closeCursor();
251 251
 		return $column;
252 252
 	}
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
 		}
268 268
 
269 269
 		$result = $query->executeQuery();
270
-		$column = (int)$result->fetchOne();
270
+		$column = (int) $result->fetchOne();
271 271
 		$result->closeCursor();
272 272
 		return $column;
273 273
 	}
@@ -285,8 +285,8 @@  discard block
 block discarded – undo
285 285
 		$calendars = [];
286 286
 		while (($row = $result->fetch()) !== false) {
287 287
 			$calendars[] = [
288
-				'id' => (int)$row['id'],
289
-				'deleted_at' => (int)$row['deleted_at'],
288
+				'id' => (int) $row['id'],
289
+				'deleted_at' => (int) $row['deleted_at'],
290 290
 			];
291 291
 		}
292 292
 		$result->closeCursor();
@@ -319,7 +319,7 @@  discard block
 block discarded – undo
319 319
 	 * @return array
320 320
 	 */
321 321
 	public function getCalendarsForUser($principalUri) {
322
-		return $this->atomic(function () use ($principalUri) {
322
+		return $this->atomic(function() use ($principalUri) {
323 323
 			$principalUriOriginal = $principalUri;
324 324
 			$principalUri = $this->convertPrincipal($principalUri, true);
325 325
 			$fields = array_column($this->propertyMap, 0);
@@ -346,7 +346,7 @@  discard block
 block discarded – undo
346 346
 
347 347
 			$calendars = [];
348 348
 			while ($row = $result->fetch()) {
349
-				$row['principaluri'] = (string)$row['principaluri'];
349
+				$row['principaluri'] = (string) $row['principaluri'];
350 350
 				$components = [];
351 351
 				if ($row['components']) {
352 352
 					$components = explode(',', $row['components']);
@@ -356,11 +356,11 @@  discard block
 block discarded – undo
356 356
 					'id' => $row['id'],
357 357
 					'uri' => $row['uri'],
358 358
 					'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
359
-					'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
359
+					'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
360 360
 					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
361
-					'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
362
-					'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
363
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
361
+					'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
362
+					'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
363
+					'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
364 364
 				];
365 365
 
366 366
 				$calendar = $this->rowToCalendar($row, $calendar);
@@ -379,8 +379,8 @@  discard block
 block discarded – undo
379 379
 			$principals[] = $principalUri;
380 380
 
381 381
 			$fields = array_column($this->propertyMap, 0);
382
-			$fields = array_map(function (string $field) {
383
-				return 'a.' . $field;
382
+			$fields = array_map(function(string $field) {
383
+				return 'a.'.$field;
384 384
 			}, $fields);
385 385
 			$fields[] = 'a.id';
386 386
 			$fields[] = 'a.uri';
@@ -407,14 +407,14 @@  discard block
 block discarded – undo
407 407
 
408 408
 			$results = $select->executeQuery();
409 409
 
410
-			$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
410
+			$readOnlyPropertyName = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only';
411 411
 			while ($row = $results->fetch()) {
412
-				$row['principaluri'] = (string)$row['principaluri'];
412
+				$row['principaluri'] = (string) $row['principaluri'];
413 413
 				if ($row['principaluri'] === $principalUri) {
414 414
 					continue;
415 415
 				}
416 416
 
417
-				$readOnly = (int)$row['access'] === Backend::ACCESS_READ;
417
+				$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
418 418
 				if (isset($calendars[$row['id']])) {
419 419
 					if ($readOnly) {
420 420
 						// New share can not have more permissions than the old one.
@@ -428,8 +428,8 @@  discard block
 block discarded – undo
428 428
 				}
429 429
 
430 430
 				[, $name] = Uri\split($row['principaluri']);
431
-				$uri = $row['uri'] . '_shared_by_' . $name;
432
-				$row['displayname'] = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? ($name ?? '')) . ')';
431
+				$uri = $row['uri'].'_shared_by_'.$name;
432
+				$row['displayname'] = $row['displayname'].' ('.($this->userManager->getDisplayName($name) ?? ($name ?? '')).')';
433 433
 				$components = [];
434 434
 				if ($row['components']) {
435 435
 					$components = explode(',', $row['components']);
@@ -438,11 +438,11 @@  discard block
 block discarded – undo
438 438
 					'id' => $row['id'],
439 439
 					'uri' => $uri,
440 440
 					'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
441
-					'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
441
+					'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
442 442
 					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
443
-					'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
444
-					'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
445
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
443
+					'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
444
+					'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
445
+					'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
446 446
 					$readOnlyPropertyName => $readOnly,
447 447
 				];
448 448
 
@@ -479,7 +479,7 @@  discard block
 block discarded – undo
479 479
 		$stmt = $query->executeQuery();
480 480
 		$calendars = [];
481 481
 		while ($row = $stmt->fetch()) {
482
-			$row['principaluri'] = (string)$row['principaluri'];
482
+			$row['principaluri'] = (string) $row['principaluri'];
483 483
 			$components = [];
484 484
 			if ($row['components']) {
485 485
 				$components = explode(',', $row['components']);
@@ -488,10 +488,10 @@  discard block
 block discarded – undo
488 488
 				'id' => $row['id'],
489 489
 				'uri' => $row['uri'],
490 490
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
491
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
491
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
492 492
 				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
493
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
494
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
493
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
494
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
495 495
 			];
496 496
 
497 497
 			$calendar = $this->rowToCalendar($row, $calendar);
@@ -529,9 +529,9 @@  discard block
 block discarded – undo
529 529
 			->executeQuery();
530 530
 
531 531
 		while ($row = $result->fetch()) {
532
-			$row['principaluri'] = (string)$row['principaluri'];
532
+			$row['principaluri'] = (string) $row['principaluri'];
533 533
 			[, $name] = Uri\split($row['principaluri']);
534
-			$row['displayname'] = $row['displayname'] . "($name)";
534
+			$row['displayname'] = $row['displayname']."($name)";
535 535
 			$components = [];
536 536
 			if ($row['components']) {
537 537
 				$components = explode(',', $row['components']);
@@ -540,13 +540,13 @@  discard block
 block discarded – undo
540 540
 				'id' => $row['id'],
541 541
 				'uri' => $row['publicuri'],
542 542
 				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
543
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
543
+				'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
544 544
 				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
545
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
546
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
547
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
548
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => true,
549
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
545
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
546
+				'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
547
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
548
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => true,
549
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
550 550
 			];
551 551
 
552 552
 			$calendar = $this->rowToCalendar($row, $calendar);
@@ -591,12 +591,12 @@  discard block
 block discarded – undo
591 591
 		$result->closeCursor();
592 592
 
593 593
 		if ($row === false) {
594
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
594
+			throw new NotFound('Node with name \''.$uri.'\' could not be found');
595 595
 		}
596 596
 
597
-		$row['principaluri'] = (string)$row['principaluri'];
597
+		$row['principaluri'] = (string) $row['principaluri'];
598 598
 		[, $name] = Uri\split($row['principaluri']);
599
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
599
+		$row['displayname'] = $row['displayname'].' '."($name)";
600 600
 		$components = [];
601 601
 		if ($row['components']) {
602 602
 			$components = explode(',', $row['components']);
@@ -605,13 +605,13 @@  discard block
 block discarded – undo
605 605
 			'id' => $row['id'],
606 606
 			'uri' => $row['publicuri'],
607 607
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
608
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
608
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
609 609
 			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
610
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
611
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
612
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
613
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => true,
614
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
610
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
611
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
612
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
613
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}read-only' => true,
614
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}public' => (int) $row['access'] === self::ACCESS_PUBLIC,
615 615
 		];
616 616
 
617 617
 		$calendar = $this->rowToCalendar($row, $calendar);
@@ -649,7 +649,7 @@  discard block
 block discarded – undo
649 649
 			return null;
650 650
 		}
651 651
 
652
-		$row['principaluri'] = (string)$row['principaluri'];
652
+		$row['principaluri'] = (string) $row['principaluri'];
653 653
 		$components = [];
654 654
 		if ($row['components']) {
655 655
 			$components = explode(',', $row['components']);
@@ -659,10 +659,10 @@  discard block
 block discarded – undo
659 659
 			'id' => $row['id'],
660 660
 			'uri' => $row['uri'],
661 661
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
662
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
662
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
663 663
 			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
664
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
665
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
664
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
665
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
666 666
 		];
667 667
 
668 668
 		$calendar = $this->rowToCalendar($row, $calendar);
@@ -698,7 +698,7 @@  discard block
 block discarded – undo
698 698
 			return null;
699 699
 		}
700 700
 
701
-		$row['principaluri'] = (string)$row['principaluri'];
701
+		$row['principaluri'] = (string) $row['principaluri'];
702 702
 		$components = [];
703 703
 		if ($row['components']) {
704 704
 			$components = explode(',', $row['components']);
@@ -708,10 +708,10 @@  discard block
 block discarded – undo
708 708
 			'id' => $row['id'],
709 709
 			'uri' => $row['uri'],
710 710
 			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
711
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
711
+			'{'.Plugin::NS_CALENDARSERVER.'}getctag' => 'http://sabre.io/ns/sync/'.($row['synctoken'] ?: '0'),
712 712
 			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?? 0,
713
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
714
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
713
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
714
+			'{'.Plugin::NS_CALDAV.'}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent'] ? 'transparent' : 'opaque'),
715 715
 		];
716 716
 
717 717
 		$calendar = $this->rowToCalendar($row, $calendar);
@@ -746,14 +746,14 @@  discard block
 block discarded – undo
746 746
 			return null;
747 747
 		}
748 748
 
749
-		$row['principaluri'] = (string)$row['principaluri'];
749
+		$row['principaluri'] = (string) $row['principaluri'];
750 750
 		$subscription = [
751 751
 			'id' => $row['id'],
752 752
 			'uri' => $row['uri'],
753 753
 			'principaluri' => $row['principaluri'],
754 754
 			'source' => $row['source'],
755 755
 			'lastmodified' => $row['lastmodified'],
756
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
756
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
757 757
 			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
758 758
 		];
759 759
 
@@ -783,14 +783,14 @@  discard block
 block discarded – undo
783 783
 			return null;
784 784
 		}
785 785
 
786
-		$row['principaluri'] = (string)$row['principaluri'];
786
+		$row['principaluri'] = (string) $row['principaluri'];
787 787
 		$subscription = [
788 788
 			'id' => $row['id'],
789 789
 			'uri' => $row['uri'],
790 790
 			'principaluri' => $row['principaluri'],
791 791
 			'source' => $row['source'],
792 792
 			'lastmodified' => $row['lastmodified'],
793
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
793
+			'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
794 794
 			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
795 795
 		];
796 796
 
@@ -828,7 +828,7 @@  discard block
 block discarded – undo
828 828
 		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
829 829
 		if (isset($properties[$sccs])) {
830 830
 			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
831
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
831
+				throw new DAV\Exception('The '.$sccs.' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
832 832
 			}
833 833
 			$values['components'] = implode(',', $properties[$sccs]->getValue());
834 834
 		} elseif (isset($properties['components'])) {
@@ -837,9 +837,9 @@  discard block
 block discarded – undo
837 837
 			$values['components'] = $properties['components'];
838 838
 		}
839 839
 
840
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
840
+		$transp = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
841 841
 		if (isset($properties[$transp])) {
842
-			$values['transparent'] = (int)($properties[$transp]->getValue() === 'transparent');
842
+			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
843 843
 		}
844 844
 
845 845
 		foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
@@ -848,7 +848,7 @@  discard block
 block discarded – undo
848 848
 			}
849 849
 		}
850 850
 
851
-		[$calendarId, $calendarData] = $this->atomic(function () use ($values) {
851
+		[$calendarId, $calendarData] = $this->atomic(function() use ($values) {
852 852
 			$query = $this->db->getQueryBuilder();
853 853
 			$query->insert('calendars');
854 854
 			foreach ($values as $column => $value) {
@@ -861,7 +861,7 @@  discard block
 block discarded – undo
861 861
 			return [$calendarId, $calendarData];
862 862
 		}, $this->db);
863 863
 
864
-		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
864
+		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int) $calendarId, $calendarData));
865 865
 
866 866
 		return $calendarId;
867 867
 	}
@@ -884,15 +884,15 @@  discard block
 block discarded – undo
884 884
 	 */
885 885
 	public function updateCalendar($calendarId, PropPatch $propPatch) {
886 886
 		$supportedProperties = array_keys($this->propertyMap);
887
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
887
+		$supportedProperties[] = '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp';
888 888
 
889
-		$propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
889
+		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
890 890
 			$newValues = [];
891 891
 			foreach ($mutations as $propertyName => $propertyValue) {
892 892
 				switch ($propertyName) {
893
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
893
+					case '{'.Plugin::NS_CALDAV.'}schedule-calendar-transp':
894 894
 						$fieldName = 'transparent';
895
-						$newValues[$fieldName] = (int)($propertyValue->getValue() === 'transparent');
895
+						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
896 896
 						break;
897 897
 					default:
898 898
 						$fieldName = $this->propertyMap[$propertyName][0];
@@ -900,7 +900,7 @@  discard block
 block discarded – undo
900 900
 						break;
901 901
 				}
902 902
 			}
903
-			[$calendarData, $shares] = $this->atomic(function () use ($calendarId, $newValues) {
903
+			[$calendarData, $shares] = $this->atomic(function() use ($calendarId, $newValues) {
904 904
 				$query = $this->db->getQueryBuilder();
905 905
 				$query->update('calendars');
906 906
 				foreach ($newValues as $fieldName => $value) {
@@ -929,9 +929,9 @@  discard block
 block discarded – undo
929 929
 	 * @return void
930 930
 	 */
931 931
 	public function deleteCalendar($calendarId, bool $forceDeletePermanently = false) {
932
-		$this->publishStatusCache->remove((string)$calendarId);
932
+		$this->publishStatusCache->remove((string) $calendarId);
933 933
 
934
-		$this->atomic(function () use ($calendarId, $forceDeletePermanently): void {
934
+		$this->atomic(function() use ($calendarId, $forceDeletePermanently): void {
935 935
 			// The calendar is deleted right away if this is either enforced by the caller
936 936
 			// or the special contacts birthday calendar or when the preference of an empty
937 937
 			// retention (0 seconds) is set, which signals a disabled trashbin.
@@ -994,7 +994,7 @@  discard block
 block discarded – undo
994 994
 	}
995 995
 
996 996
 	public function restoreCalendar(int $id): void {
997
-		$this->atomic(function () use ($id): void {
997
+		$this->atomic(function() use ($id): void {
998 998
 			$qb = $this->db->getQueryBuilder();
999 999
 			$update = $qb->update('calendars')
1000 1000
 				->set('deleted_at', $qb->createNamedParameter(null))
@@ -1068,7 +1068,7 @@  discard block
 block discarded – undo
1068 1068
 	 */
1069 1069
 	public function getLimitedCalendarObjects(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1070 1070
 		$query = $this->db->getQueryBuilder();
1071
-		$query->select(['id','uid', 'etag', 'uri', 'calendardata'])
1071
+		$query->select(['id', 'uid', 'etag', 'uri', 'calendardata'])
1072 1072
 			->from('calendarobjects')
1073 1073
 			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1074 1074
 			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
@@ -1146,11 +1146,11 @@  discard block
 block discarded – undo
1146 1146
 				'id' => $row['id'],
1147 1147
 				'uri' => $row['uri'],
1148 1148
 				'lastmodified' => $row['lastmodified'],
1149
-				'etag' => '"' . $row['etag'] . '"',
1149
+				'etag' => '"'.$row['etag'].'"',
1150 1150
 				'calendarid' => $row['calendarid'],
1151
-				'size' => (int)$row['size'],
1151
+				'size' => (int) $row['size'],
1152 1152
 				'component' => strtolower($row['componenttype']),
1153
-				'classification' => (int)$row['classification']
1153
+				'classification' => (int) $row['classification']
1154 1154
 			];
1155 1155
 		}
1156 1156
 		$stmt->closeCursor();
@@ -1173,13 +1173,13 @@  discard block
 block discarded – undo
1173 1173
 				'id' => $row['id'],
1174 1174
 				'uri' => $row['uri'],
1175 1175
 				'lastmodified' => $row['lastmodified'],
1176
-				'etag' => '"' . $row['etag'] . '"',
1177
-				'calendarid' => (int)$row['calendarid'],
1178
-				'calendartype' => (int)$row['calendartype'],
1179
-				'size' => (int)$row['size'],
1176
+				'etag' => '"'.$row['etag'].'"',
1177
+				'calendarid' => (int) $row['calendarid'],
1178
+				'calendartype' => (int) $row['calendartype'],
1179
+				'size' => (int) $row['size'],
1180 1180
 				'component' => strtolower($row['componenttype']),
1181
-				'classification' => (int)$row['classification'],
1182
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1181
+				'classification' => (int) $row['classification'],
1182
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int) $row['deleted_at'],
1183 1183
 			];
1184 1184
 		}
1185 1185
 		$stmt->closeCursor();
@@ -1212,13 +1212,13 @@  discard block
 block discarded – undo
1212 1212
 				'id' => $row['id'],
1213 1213
 				'uri' => $row['uri'],
1214 1214
 				'lastmodified' => $row['lastmodified'],
1215
-				'etag' => '"' . $row['etag'] . '"',
1215
+				'etag' => '"'.$row['etag'].'"',
1216 1216
 				'calendarid' => $row['calendarid'],
1217 1217
 				'calendaruri' => $row['calendaruri'],
1218
-				'size' => (int)$row['size'],
1218
+				'size' => (int) $row['size'],
1219 1219
 				'component' => strtolower($row['componenttype']),
1220
-				'classification' => (int)$row['classification'],
1221
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1220
+				'classification' => (int) $row['classification'],
1221
+				'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int) $row['deleted_at'],
1222 1222
 			];
1223 1223
 		}
1224 1224
 		$stmt->closeCursor();
@@ -1244,7 +1244,7 @@  discard block
 block discarded – undo
1244 1244
 	 * @return array|null
1245 1245
 	 */
1246 1246
 	public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1247
-		$key = $calendarId . '::' . $objectUri . '::' . $calendarType;
1247
+		$key = $calendarId.'::'.$objectUri.'::'.$calendarType;
1248 1248
 		if (isset($this->cachedObjects[$key])) {
1249 1249
 			return $this->cachedObjects[$key];
1250 1250
 		}
@@ -1273,13 +1273,13 @@  discard block
 block discarded – undo
1273 1273
 			'uri' => $row['uri'],
1274 1274
 			'uid' => $row['uid'],
1275 1275
 			'lastmodified' => $row['lastmodified'],
1276
-			'etag' => '"' . $row['etag'] . '"',
1276
+			'etag' => '"'.$row['etag'].'"',
1277 1277
 			'calendarid' => $row['calendarid'],
1278
-			'size' => (int)$row['size'],
1278
+			'size' => (int) $row['size'],
1279 1279
 			'calendardata' => $this->readBlob($row['calendardata']),
1280 1280
 			'component' => strtolower($row['componenttype']),
1281
-			'classification' => (int)$row['classification'],
1282
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1281
+			'classification' => (int) $row['classification'],
1282
+			'{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int) $row['deleted_at'],
1283 1283
 		];
1284 1284
 	}
1285 1285
 
@@ -1321,12 +1321,12 @@  discard block
 block discarded – undo
1321 1321
 					'id' => $row['id'],
1322 1322
 					'uri' => $row['uri'],
1323 1323
 					'lastmodified' => $row['lastmodified'],
1324
-					'etag' => '"' . $row['etag'] . '"',
1324
+					'etag' => '"'.$row['etag'].'"',
1325 1325
 					'calendarid' => $row['calendarid'],
1326
-					'size' => (int)$row['size'],
1326
+					'size' => (int) $row['size'],
1327 1327
 					'calendardata' => $this->readBlob($row['calendardata']),
1328 1328
 					'component' => strtolower($row['componenttype']),
1329
-					'classification' => (int)$row['classification']
1329
+					'classification' => (int) $row['classification']
1330 1330
 				];
1331 1331
 			}
1332 1332
 			$result->closeCursor();
@@ -1358,7 +1358,7 @@  discard block
 block discarded – undo
1358 1358
 		$this->cachedObjects = [];
1359 1359
 		$extraData = $this->getDenormalizedData($calendarData);
1360 1360
 
1361
-		return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1361
+		return $this->atomic(function() use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1362 1362
 			// Try to detect duplicates
1363 1363
 			$qb = $this->db->getQueryBuilder();
1364 1364
 			$qb->select($qb->func()->count('*'))
@@ -1368,7 +1368,7 @@  discard block
 block discarded – undo
1368 1368
 				->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1369 1369
 				->andWhere($qb->expr()->isNull('deleted_at'));
1370 1370
 			$result = $qb->executeQuery();
1371
-			$count = (int)$result->fetchOne();
1371
+			$count = (int) $result->fetchOne();
1372 1372
 			$result->closeCursor();
1373 1373
 
1374 1374
 			if ($count !== 0) {
@@ -1428,7 +1428,7 @@  discard block
 block discarded – undo
1428 1428
 				// TODO: implement custom event for federated calendars
1429 1429
 			}
1430 1430
 
1431
-			return '"' . $extraData['etag'] . '"';
1431
+			return '"'.$extraData['etag'].'"';
1432 1432
 		}, $this->db);
1433 1433
 	}
1434 1434
 
@@ -1455,7 +1455,7 @@  discard block
 block discarded – undo
1455 1455
 		$this->cachedObjects = [];
1456 1456
 		$extraData = $this->getDenormalizedData($calendarData);
1457 1457
 
1458
-		return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1458
+		return $this->atomic(function() use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1459 1459
 			$query = $this->db->getQueryBuilder();
1460 1460
 			$query->update('calendarobjects')
1461 1461
 				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
@@ -1491,7 +1491,7 @@  discard block
 block discarded – undo
1491 1491
 				}
1492 1492
 			}
1493 1493
 
1494
-			return '"' . $extraData['etag'] . '"';
1494
+			return '"'.$extraData['etag'].'"';
1495 1495
 		}, $this->db);
1496 1496
 	}
1497 1497
 
@@ -1509,7 +1509,7 @@  discard block
 block discarded – undo
1509 1509
 	 */
1510 1510
 	public function moveCalendarObject(string $sourcePrincipalUri, int $sourceObjectId, string $targetPrincipalUri, int $targetCalendarId, string $tragetObjectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR): bool {
1511 1511
 		$this->cachedObjects = [];
1512
-		return $this->atomic(function () use ($sourcePrincipalUri, $sourceObjectId, $targetPrincipalUri, $targetCalendarId, $tragetObjectUri, $calendarType) {
1512
+		return $this->atomic(function() use ($sourcePrincipalUri, $sourceObjectId, $targetPrincipalUri, $targetCalendarId, $tragetObjectUri, $calendarType) {
1513 1513
 			$object = $this->getCalendarObjectById($sourcePrincipalUri, $sourceObjectId);
1514 1514
 			if (empty($object)) {
1515 1515
 				return false;
@@ -1566,7 +1566,7 @@  discard block
 block discarded – undo
1566 1566
 	 */
1567 1567
 	public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
1568 1568
 		$this->cachedObjects = [];
1569
-		$this->atomic(function () use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently): void {
1569
+		$this->atomic(function() use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently): void {
1570 1570
 			$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1571 1571
 
1572 1572
 			if ($data === null) {
@@ -1650,8 +1650,8 @@  discard block
 block discarded – undo
1650 1650
 	 */
1651 1651
 	public function restoreCalendarObject(array $objectData): void {
1652 1652
 		$this->cachedObjects = [];
1653
-		$this->atomic(function () use ($objectData): void {
1654
-			$id = (int)$objectData['id'];
1653
+		$this->atomic(function() use ($objectData): void {
1654
+			$id = (int) $objectData['id'];
1655 1655
 			$restoreUri = str_replace('-deleted.ics', '.ics', $objectData['uri']);
1656 1656
 			$targetObject = $this->getCalendarObject(
1657 1657
 				$objectData['calendarid'],
@@ -1681,17 +1681,17 @@  discard block
 block discarded – undo
1681 1681
 				// Welp, this should possibly not have happened, but let's ignore
1682 1682
 				return;
1683 1683
 			}
1684
-			$this->addChanges($row['calendarid'], [$row['uri']], 1, (int)$row['calendartype']);
1684
+			$this->addChanges($row['calendarid'], [$row['uri']], 1, (int) $row['calendartype']);
1685 1685
 
1686
-			$calendarRow = $this->getCalendarById((int)$row['calendarid']);
1686
+			$calendarRow = $this->getCalendarById((int) $row['calendarid']);
1687 1687
 			if ($calendarRow === null) {
1688 1688
 				throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
1689 1689
 			}
1690 1690
 			$this->dispatcher->dispatchTyped(
1691 1691
 				new CalendarObjectRestoredEvent(
1692
-					(int)$objectData['calendarid'],
1692
+					(int) $objectData['calendarid'],
1693 1693
 					$calendarRow,
1694
-					$this->getShares((int)$row['calendarid']),
1694
+					$this->getShares((int) $row['calendarid']),
1695 1695
 					$row
1696 1696
 				)
1697 1697
 			);
@@ -1810,19 +1810,19 @@  discard block
 block discarded – undo
1810 1810
 				try {
1811 1811
 					$matches = $this->validateFilterForObject($row, $filters);
1812 1812
 				} catch (ParseException $ex) {
1813
-					$this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1813
+					$this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri'], [
1814 1814
 						'app' => 'dav',
1815 1815
 						'exception' => $ex,
1816 1816
 					]);
1817 1817
 					continue;
1818 1818
 				} catch (InvalidDataException $ex) {
1819
-					$this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1819
+					$this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri'], [
1820 1820
 						'app' => 'dav',
1821 1821
 						'exception' => $ex,
1822 1822
 					]);
1823 1823
 					continue;
1824 1824
 				} catch (MaxInstancesExceededException $ex) {
1825
-					$this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
1825
+					$this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: '.$row['uri'], [
1826 1826
 						'app' => 'dav',
1827 1827
 						'exception' => $ex,
1828 1828
 					]);
@@ -1834,7 +1834,7 @@  discard block
 block discarded – undo
1834 1834
 				}
1835 1835
 			}
1836 1836
 			$result[] = $row['uri'];
1837
-			$key = $calendarId . '::' . $row['uri'] . '::' . $calendarType;
1837
+			$key = $calendarId.'::'.$row['uri'].'::'.$calendarType;
1838 1838
 			$this->cachedObjects[$key] = $this->rowToCalendarObject($row);
1839 1839
 		}
1840 1840
 
@@ -1853,7 +1853,7 @@  discard block
 block discarded – undo
1853 1853
 	 * @return array
1854 1854
 	 */
1855 1855
 	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1856
-		return $this->atomic(function () use ($principalUri, $filters, $limit, $offset) {
1856
+		return $this->atomic(function() use ($principalUri, $filters, $limit, $offset) {
1857 1857
 			$calendars = $this->getCalendarsForUser($principalUri);
1858 1858
 			$ownCalendars = [];
1859 1859
 			$sharedCalendars = [];
@@ -1945,7 +1945,7 @@  discard block
 block discarded – undo
1945 1945
 				->andWhere($compExpr)
1946 1946
 				->andWhere($propParamExpr)
1947 1947
 				->andWhere($query->expr()->iLike('i.value',
1948
-					$query->createNamedParameter('%' . $this->db->escapeLikeParameter($filters['search-term']) . '%')))
1948
+					$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')))
1949 1949
 				->andWhere($query->expr()->isNull('deleted_at'));
1950 1950
 
1951 1951
 			if ($offset) {
@@ -1959,7 +1959,7 @@  discard block
 block discarded – undo
1959 1959
 
1960 1960
 			$result = [];
1961 1961
 			while ($row = $stmt->fetch()) {
1962
-				$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1962
+				$path = $uriMapper[$row['calendarid']].'/'.$row['uri'];
1963 1963
 				if (!in_array($path, $result)) {
1964 1964
 					$result[] = $path;
1965 1965
 				}
@@ -2029,7 +2029,7 @@  discard block
 block discarded – undo
2029 2029
 		if ($pattern !== '') {
2030 2030
 			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
2031 2031
 				$outerQuery->createNamedParameter('%'
2032
-					. $this->db->escapeLikeParameter($pattern) . '%')));
2032
+					. $this->db->escapeLikeParameter($pattern).'%')));
2033 2033
 		}
2034 2034
 
2035 2035
 		$start = null;
@@ -2081,7 +2081,7 @@  discard block
 block discarded – undo
2081 2081
 		// For the pagination with hasLimit and hasTimeRange, a stable ordering is helpful.
2082 2082
 		$outerQuery->addOrderBy('id');
2083 2083
 
2084
-		$offset = (int)$offset;
2084
+		$offset = (int) $offset;
2085 2085
 		$outerQuery->setFirstResult($offset);
2086 2086
 
2087 2087
 		$calendarObjects = [];
@@ -2102,7 +2102,7 @@  discard block
 block discarded – undo
2102 2102
 			 *
2103 2103
 			 * 25 rows and 3 retries is entirely arbitrary.
2104 2104
 			 */
2105
-			$maxResults = (int)max($limit, 25);
2105
+			$maxResults = (int) max($limit, 25);
2106 2106
 			$outerQuery->setMaxResults($maxResults);
2107 2107
 
2108 2108
 			for ($attempt = $objectsCount = 0; $attempt < 3 && $objectsCount < $limit; $attempt++) {
@@ -2116,7 +2116,7 @@  discard block
 block discarded – undo
2116 2116
 			$calendarObjects = $this->searchCalendarObjects($outerQuery, $start, $end);
2117 2117
 		}
2118 2118
 
2119
-		$calendarObjects = array_map(function ($o) use ($options) {
2119
+		$calendarObjects = array_map(function($o) use ($options) {
2120 2120
 			$calendarData = Reader::read($o['calendardata']);
2121 2121
 
2122 2122
 			// Expand recurrences if an explicit time range is requested
@@ -2144,16 +2144,16 @@  discard block
 block discarded – undo
2144 2144
 				'type' => $o['componenttype'],
2145 2145
 				'uid' => $o['uid'],
2146 2146
 				'uri' => $o['uri'],
2147
-				'objects' => array_map(function ($c) {
2147
+				'objects' => array_map(function($c) {
2148 2148
 					return $this->transformSearchData($c);
2149 2149
 				}, $objects),
2150
-				'timezones' => array_map(function ($c) {
2150
+				'timezones' => array_map(function($c) {
2151 2151
 					return $this->transformSearchData($c);
2152 2152
 				}, $timezones),
2153 2153
 			];
2154 2154
 		}, $calendarObjects);
2155 2155
 
2156
-		usort($calendarObjects, function (array $a, array $b) {
2156
+		usort($calendarObjects, function(array $a, array $b) {
2157 2157
 			/** @var DateTimeImmutable $startA */
2158 2158
 			$startA = $a['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2159 2159
 			/** @var DateTimeImmutable $startB */
@@ -2198,7 +2198,7 @@  discard block
 block discarded – undo
2198 2198
 					'time-range' => null,
2199 2199
 				]);
2200 2200
 			} catch (MaxInstancesExceededException $ex) {
2201
-				$this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: ' . $row['uri'], [
2201
+				$this->logger->warning('Caught max instances exceeded exception for calendar data. This usually indicates too much recurring (more than 3500) event in calendar data. Object uri: '.$row['uri'], [
2202 2202
 					'app' => 'dav',
2203 2203
 					'exception' => $ex,
2204 2204
 				]);
@@ -2229,7 +2229,7 @@  discard block
 block discarded – undo
2229 2229
 		/** @var Component[] $subComponents */
2230 2230
 		$subComponents = $comp->getComponents();
2231 2231
 		/** @var Property[] $properties */
2232
-		$properties = array_filter($comp->children(), function ($c) {
2232
+		$properties = array_filter($comp->children(), function($c) {
2233 2233
 			return $c instanceof Property;
2234 2234
 		});
2235 2235
 		$validationRules = $comp->getValidationRules();
@@ -2297,7 +2297,7 @@  discard block
 block discarded – undo
2297 2297
 		array $searchParameters,
2298 2298
 		array $options = [],
2299 2299
 	): array {
2300
-		return $this->atomic(function () use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
2300
+		return $this->atomic(function() use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
2301 2301
 			$escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
2302 2302
 
2303 2303
 			$calendarObjectIdQuery = $this->db->getQueryBuilder();
@@ -2309,7 +2309,7 @@  discard block
 block discarded – undo
2309 2309
 			$subscriptions = $this->getSubscriptionsForUser($principalUri);
2310 2310
 			foreach ($calendars as $calendar) {
2311 2311
 				$calendarAnd = $calendarObjectIdQuery->expr()->andX(
2312
-					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])),
2312
+					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int) $calendar['id'])),
2313 2313
 					$calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)),
2314 2314
 				);
2315 2315
 
@@ -2323,7 +2323,7 @@  discard block
 block discarded – undo
2323 2323
 			}
2324 2324
 			foreach ($subscriptions as $subscription) {
2325 2325
 				$subscriptionAnd = $calendarObjectIdQuery->expr()->andX(
2326
-					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])),
2326
+					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int) $subscription['id'])),
2327 2327
 					$calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)),
2328 2328
 				);
2329 2329
 
@@ -2372,7 +2372,7 @@  discard block
 block discarded – undo
2372 2372
 				if (!$escapePattern) {
2373 2373
 					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
2374 2374
 				} else {
2375
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
2375
+					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%'.$this->db->escapeLikeParameter($pattern).'%')));
2376 2376
 				}
2377 2377
 			}
2378 2378
 
@@ -2400,7 +2400,7 @@  discard block
 block discarded – undo
2400 2400
 			$result = $calendarObjectIdQuery->executeQuery();
2401 2401
 			$matches = [];
2402 2402
 			while (($row = $result->fetch()) !== false) {
2403
-				$matches[] = (int)$row['objectid'];
2403
+				$matches[] = (int) $row['objectid'];
2404 2404
 			}
2405 2405
 			$result->closeCursor();
2406 2406
 
@@ -2412,8 +2412,8 @@  discard block
 block discarded – undo
2412 2412
 			$result = $query->executeQuery();
2413 2413
 			$calendarObjects = [];
2414 2414
 			while (($array = $result->fetch()) !== false) {
2415
-				$array['calendarid'] = (int)$array['calendarid'];
2416
-				$array['calendartype'] = (int)$array['calendartype'];
2415
+				$array['calendarid'] = (int) $array['calendarid'];
2416
+				$array['calendartype'] = (int) $array['calendartype'];
2417 2417
 				$array['calendardata'] = $this->readBlob($array['calendardata']);
2418 2418
 
2419 2419
 				$calendarObjects[] = $array;
@@ -2459,7 +2459,7 @@  discard block
 block discarded – undo
2459 2459
 		$row = $stmt->fetch();
2460 2460
 		$stmt->closeCursor();
2461 2461
 		if ($row) {
2462
-			return $row['calendaruri'] . '/' . $row['objecturi'];
2462
+			return $row['calendaruri'].'/'.$row['objecturi'];
2463 2463
 		}
2464 2464
 
2465 2465
 		return null;
@@ -2485,14 +2485,14 @@  discard block
 block discarded – undo
2485 2485
 			'id' => $row['id'],
2486 2486
 			'uri' => $row['uri'],
2487 2487
 			'lastmodified' => $row['lastmodified'],
2488
-			'etag' => '"' . $row['etag'] . '"',
2488
+			'etag' => '"'.$row['etag'].'"',
2489 2489
 			'calendarid' => $row['calendarid'],
2490 2490
 			'calendaruri' => $row['calendaruri'],
2491
-			'size' => (int)$row['size'],
2491
+			'size' => (int) $row['size'],
2492 2492
 			'calendardata' => $this->readBlob($row['calendardata']),
2493 2493
 			'component' => strtolower($row['componenttype']),
2494
-			'classification' => (int)$row['classification'],
2495
-			'deleted_at' => isset($row['deleted_at']) ? ((int)$row['deleted_at']) : null,
2494
+			'classification' => (int) $row['classification'],
2495
+			'deleted_at' => isset($row['deleted_at']) ? ((int) $row['deleted_at']) : null,
2496 2496
 		];
2497 2497
 	}
2498 2498
 
@@ -2554,9 +2554,9 @@  discard block
 block discarded – undo
2554 2554
 	 * @return ?array
2555 2555
 	 */
2556 2556
 	public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2557
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2557
+		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars' : 'calendarsubscriptions';
2558 2558
 
2559
-		return $this->atomic(function () use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
2559
+		return $this->atomic(function() use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
2560 2560
 			// Current synctoken
2561 2561
 			$qb = $this->db->getQueryBuilder();
2562 2562
 			$qb->select('synctoken')
@@ -2607,7 +2607,7 @@  discard block
 block discarded – undo
2607 2607
 				while ($entry = $stmt->fetch(\PDO::FETCH_NUM)) {
2608 2608
 					// assign uri (column 0) to appropriate mutation based on operation (column 1)
2609 2609
 					// forced (int) is needed as doctrine with OCI returns the operation field as string not integer
2610
-					match ((int)$entry[1]) {
2610
+					match ((int) $entry[1]) {
2611 2611
 						1 => $result['added'][] = $entry[0],
2612 2612
 						2 => $result['modified'][] = $entry[0],
2613 2613
 						3 => $result['deleted'][] = $entry[0],
@@ -2678,7 +2678,7 @@  discard block
 block discarded – undo
2678 2678
 				'source' => $row['source'],
2679 2679
 				'lastmodified' => $row['lastmodified'],
2680 2680
 
2681
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2681
+				'{'.Plugin::NS_CALDAV.'}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2682 2682
 				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
2683 2683
 			];
2684 2684
 
@@ -2722,7 +2722,7 @@  discard block
 block discarded – undo
2722 2722
 			}
2723 2723
 		}
2724 2724
 
2725
-		[$subscriptionId, $subscriptionRow] = $this->atomic(function () use ($values) {
2725
+		[$subscriptionId, $subscriptionRow] = $this->atomic(function() use ($values) {
2726 2726
 			$valuesToInsert = [];
2727 2727
 			$query = $this->db->getQueryBuilder();
2728 2728
 			foreach (array_keys($values) as $name) {
@@ -2763,7 +2763,7 @@  discard block
 block discarded – undo
2763 2763
 		$supportedProperties = array_keys($this->subscriptionPropertyMap);
2764 2764
 		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
2765 2765
 
2766
-		$propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2766
+		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
2767 2767
 			$newValues = [];
2768 2768
 
2769 2769
 			foreach ($mutations as $propertyName => $propertyValue) {
@@ -2775,7 +2775,7 @@  discard block
 block discarded – undo
2775 2775
 				}
2776 2776
 			}
2777 2777
 
2778
-			$subscriptionRow = $this->atomic(function () use ($subscriptionId, $newValues) {
2778
+			$subscriptionRow = $this->atomic(function() use ($subscriptionId, $newValues) {
2779 2779
 				$query = $this->db->getQueryBuilder();
2780 2780
 				$query->update('calendarsubscriptions')
2781 2781
 					->set('lastmodified', $query->createNamedParameter(time()));
@@ -2788,7 +2788,7 @@  discard block
 block discarded – undo
2788 2788
 				return $this->getSubscriptionById($subscriptionId);
2789 2789
 			}, $this->db);
2790 2790
 
2791
-			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2791
+			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int) $subscriptionId, $subscriptionRow, [], $mutations));
2792 2792
 
2793 2793
 			return true;
2794 2794
 		});
@@ -2801,7 +2801,7 @@  discard block
 block discarded – undo
2801 2801
 	 * @return void
2802 2802
 	 */
2803 2803
 	public function deleteSubscription($subscriptionId) {
2804
-		$this->atomic(function () use ($subscriptionId): void {
2804
+		$this->atomic(function() use ($subscriptionId): void {
2805 2805
 			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2806 2806
 
2807 2807
 			$query = $this->db->getQueryBuilder();
@@ -2826,7 +2826,7 @@  discard block
 block discarded – undo
2826 2826
 				->executeStatement();
2827 2827
 
2828 2828
 			if ($subscriptionRow) {
2829
-				$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2829
+				$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int) $subscriptionId, $subscriptionRow, []));
2830 2830
 			}
2831 2831
 		}, $this->db);
2832 2832
 	}
@@ -2865,8 +2865,8 @@  discard block
 block discarded – undo
2865 2865
 			'uri' => $row['uri'],
2866 2866
 			'calendardata' => $row['calendardata'],
2867 2867
 			'lastmodified' => $row['lastmodified'],
2868
-			'etag' => '"' . $row['etag'] . '"',
2869
-			'size' => (int)$row['size'],
2868
+			'etag' => '"'.$row['etag'].'"',
2869
+			'size' => (int) $row['size'],
2870 2870
 		];
2871 2871
 	}
2872 2872
 
@@ -2894,8 +2894,8 @@  discard block
 block discarded – undo
2894 2894
 				'calendardata' => $row['calendardata'],
2895 2895
 				'uri' => $row['uri'],
2896 2896
 				'lastmodified' => $row['lastmodified'],
2897
-				'etag' => '"' . $row['etag'] . '"',
2898
-				'size' => (int)$row['size'],
2897
+				'etag' => '"'.$row['etag'].'"',
2898
+				'size' => (int) $row['size'],
2899 2899
 			];
2900 2900
 		}
2901 2901
 		$stmt->closeCursor();
@@ -2937,8 +2937,8 @@  discard block
 block discarded – undo
2937 2937
 		if ($count === 0) {
2938 2938
 			return;
2939 2939
 		}
2940
-		$ids = array_map(static function (array $id) {
2941
-			return (int)$id[0];
2940
+		$ids = array_map(static function(array $id) {
2941
+			return (int) $id[0];
2942 2942
 		}, $result->fetchAll(\PDO::FETCH_NUM));
2943 2943
 		$result->closeCursor();
2944 2944
 
@@ -2991,15 +2991,15 @@  discard block
 block discarded – undo
2991 2991
 	 */
2992 2992
 	protected function addChanges(int $calendarId, array $objectUris, int $operation, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
2993 2993
 		$this->cachedObjects = [];
2994
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2994
+		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars' : 'calendarsubscriptions';
2995 2995
 
2996
-		$this->atomic(function () use ($calendarId, $objectUris, $operation, $calendarType, $table): void {
2996
+		$this->atomic(function() use ($calendarId, $objectUris, $operation, $calendarType, $table): void {
2997 2997
 			$query = $this->db->getQueryBuilder();
2998 2998
 			$query->select('synctoken')
2999 2999
 				->from($table)
3000 3000
 				->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
3001 3001
 			$result = $query->executeQuery();
3002
-			$syncToken = (int)$result->fetchOne();
3002
+			$syncToken = (int) $result->fetchOne();
3003 3003
 			$result->closeCursor();
3004 3004
 
3005 3005
 			$query = $this->db->getQueryBuilder();
@@ -3028,7 +3028,7 @@  discard block
 block discarded – undo
3028 3028
 	public function restoreChanges(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
3029 3029
 		$this->cachedObjects = [];
3030 3030
 
3031
-		$this->atomic(function () use ($calendarId, $calendarType): void {
3031
+		$this->atomic(function() use ($calendarId, $calendarType): void {
3032 3032
 			$qbAdded = $this->db->getQueryBuilder();
3033 3033
 			$qbAdded->select('uri')
3034 3034
 				->from('calendarobjects')
@@ -3058,7 +3058,7 @@  discard block
 block discarded – undo
3058 3058
 					)
3059 3059
 				);
3060 3060
 			$resultDeleted = $qbDeleted->executeQuery();
3061
-			$deletedUris = array_map(function (string $uri) {
3061
+			$deletedUris = array_map(function(string $uri) {
3062 3062
 				return str_replace('-deleted.ics', '.ics', $uri);
3063 3063
 			}, $resultDeleted->fetchAll(\PDO::FETCH_COLUMN));
3064 3064
 			$resultDeleted->closeCursor();
@@ -3103,7 +3103,7 @@  discard block
 block discarded – undo
3103 3103
 				// Track first component type and uid
3104 3104
 				if ($uid === null) {
3105 3105
 					$componentType = $component->name;
3106
-					$uid = (string)$component->UID;
3106
+					$uid = (string) $component->UID;
3107 3107
 				}
3108 3108
 			}
3109 3109
 		}
@@ -3194,11 +3194,11 @@  discard block
 block discarded – undo
3194 3194
 	 * @param list<string> $remove
3195 3195
 	 */
3196 3196
 	public function updateShares(IShareable $shareable, array $add, array $remove): void {
3197
-		$this->atomic(function () use ($shareable, $add, $remove): void {
3197
+		$this->atomic(function() use ($shareable, $add, $remove): void {
3198 3198
 			$calendarId = $shareable->getResourceId();
3199 3199
 			$calendarRow = $this->getCalendarById($calendarId);
3200 3200
 			if ($calendarRow === null) {
3201
-				throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $calendarId);
3201
+				throw new \RuntimeException('Trying to update shares for non-existing calendar: '.$calendarId);
3202 3202
 			}
3203 3203
 			$oldShares = $this->getShares($calendarId);
3204 3204
 
@@ -3229,7 +3229,7 @@  discard block
 block discarded – undo
3229 3229
 	 * @return string|null
3230 3230
 	 */
3231 3231
 	public function setPublishStatus($value, $calendar) {
3232
-		$publishStatus = $this->atomic(function () use ($value, $calendar) {
3232
+		$publishStatus = $this->atomic(function() use ($value, $calendar) {
3233 3233
 			$calendarId = $calendar->getResourceId();
3234 3234
 			$calendarData = $this->getCalendarById($calendarId);
3235 3235
 
@@ -3258,7 +3258,7 @@  discard block
 block discarded – undo
3258 3258
 			return null;
3259 3259
 		}, $this->db);
3260 3260
 
3261
-		$this->publishStatusCache->set((string)$calendar->getResourceId(), $publishStatus ?? false);
3261
+		$this->publishStatusCache->set((string) $calendar->getResourceId(), $publishStatus ?? false);
3262 3262
 		return $publishStatus;
3263 3263
 	}
3264 3264
 
@@ -3267,7 +3267,7 @@  discard block
 block discarded – undo
3267 3267
 	 * @return string|false
3268 3268
 	 */
3269 3269
 	public function getPublishStatus($calendar) {
3270
-		$cached = $this->publishStatusCache->get((string)$calendar->getResourceId());
3270
+		$cached = $this->publishStatusCache->get((string) $calendar->getResourceId());
3271 3271
 		if ($cached !== null) {
3272 3272
 			return $cached;
3273 3273
 		}
@@ -3282,7 +3282,7 @@  discard block
 block discarded – undo
3282 3282
 		$publishStatus = $result->fetchOne();
3283 3283
 		$result->closeCursor();
3284 3284
 
3285
-		$this->publishStatusCache->set((string)$calendar->getResourceId(), $publishStatus);
3285
+		$this->publishStatusCache->set((string) $calendar->getResourceId(), $publishStatus);
3286 3286
 		return $publishStatus;
3287 3287
 	}
3288 3288
 
@@ -3307,14 +3307,14 @@  discard block
 block discarded – undo
3307 3307
 
3308 3308
 		$hasPublishStatuses = [];
3309 3309
 		while ($row = $result->fetch()) {
3310
-			$this->publishStatusCache->set((string)$row['resourceid'], $row['publicuri']);
3311
-			$hasPublishStatuses[(int)$row['resourceid']] = true;
3310
+			$this->publishStatusCache->set((string) $row['resourceid'], $row['publicuri']);
3311
+			$hasPublishStatuses[(int) $row['resourceid']] = true;
3312 3312
 		}
3313 3313
 
3314 3314
 		// Also remember resources with no publish status
3315 3315
 		foreach ($resourceIds as $resourceId) {
3316 3316
 			if (!isset($hasPublishStatuses[$resourceId])) {
3317
-				$this->publishStatusCache->set((string)$resourceId, false);
3317
+				$this->publishStatusCache->set((string) $resourceId, false);
3318 3318
 			}
3319 3319
 		}
3320 3320
 
@@ -3341,7 +3341,7 @@  discard block
 block discarded – undo
3341 3341
 	 */
3342 3342
 	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
3343 3343
 		$this->cachedObjects = [];
3344
-		$this->atomic(function () use ($calendarId, $objectUri, $calendarData, $calendarType): void {
3344
+		$this->atomic(function() use ($calendarId, $objectUri, $calendarData, $calendarType): void {
3345 3345
 			$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
3346 3346
 
3347 3347
 			try {
@@ -3413,7 +3413,7 @@  discard block
 block discarded – undo
3413 3413
 	 * deletes all birthday calendars
3414 3414
 	 */
3415 3415
 	public function deleteAllBirthdayCalendars() {
3416
-		$this->atomic(function (): void {
3416
+		$this->atomic(function(): void {
3417 3417
 			$query = $this->db->getQueryBuilder();
3418 3418
 			$result = $query->select(['id'])->from('calendars')
3419 3419
 				->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
@@ -3433,7 +3433,7 @@  discard block
 block discarded – undo
3433 3433
 	 * @param $subscriptionId
3434 3434
 	 */
3435 3435
 	public function purgeAllCachedEventsForSubscription($subscriptionId) {
3436
-		$this->atomic(function () use ($subscriptionId): void {
3436
+		$this->atomic(function() use ($subscriptionId): void {
3437 3437
 			$query = $this->db->getQueryBuilder();
3438 3438
 			$query->select('uri')
3439 3439
 				->from('calendarobjects')
@@ -3479,7 +3479,7 @@  discard block
 block discarded – undo
3479 3479
 			return;
3480 3480
 		}
3481 3481
 
3482
-		$this->atomic(function () use ($subscriptionId, $calendarObjectIds, $calendarObjectUris): void {
3482
+		$this->atomic(function() use ($subscriptionId, $calendarObjectIds, $calendarObjectUris): void {
3483 3483
 			foreach (array_chunk($calendarObjectIds, 1000) as $chunk) {
3484 3484
 				$query = $this->db->getQueryBuilder();
3485 3485
 				$query->delete($this->dbObjectPropertiesTable)
@@ -3572,10 +3572,10 @@  discard block
 block discarded – undo
3572 3572
 		$result->closeCursor();
3573 3573
 
3574 3574
 		if (!isset($objectIds['id'])) {
3575
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
3575
+			throw new \InvalidArgumentException('Calendarobject does not exists: '.$uri);
3576 3576
 		}
3577 3577
 
3578
-		return (int)$objectIds['id'];
3578
+		return (int) $objectIds['id'];
3579 3579
 	}
3580 3580
 
3581 3581
 	/**
@@ -3591,7 +3591,7 @@  discard block
 block discarded – undo
3591 3591
 			->from('calendarchanges');
3592 3592
 
3593 3593
 		$result = $query->executeQuery();
3594
-		$maxId = (int)$result->fetchOne();
3594
+		$maxId = (int) $result->fetchOne();
3595 3595
 		$result->closeCursor();
3596 3596
 		if (!$maxId || $maxId < $keep) {
3597 3597
 			return 0;
@@ -3629,8 +3629,8 @@  discard block
 block discarded – undo
3629 3629
 	 *
3630 3630
 	 */
3631 3631
 	private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
3632
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
3633
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
3632
+		$ownerPrincipalKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD.'}owner-principal';
3633
+		$displaynameKey = '{'.\OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD.'}owner-displayname';
3634 3634
 		if (isset($calendarInfo[$ownerPrincipalKey])) {
3635 3635
 			$uri = $calendarInfo[$ownerPrincipalKey];
3636 3636
 		} else {
@@ -3739,10 +3739,10 @@  discard block
 block discarded – undo
3739 3739
 	}
3740 3740
 
3741 3741
 	public function unshare(IShareable $shareable, string $principal): void {
3742
-		$this->atomic(function () use ($shareable, $principal): void {
3742
+		$this->atomic(function() use ($shareable, $principal): void {
3743 3743
 			$calendarData = $this->getCalendarById($shareable->getResourceId());
3744 3744
 			if ($calendarData === null) {
3745
-				throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $shareable->getResourceId());
3745
+				throw new \RuntimeException('Trying to update shares for non-existing calendar: '.$shareable->getResourceId());
3746 3746
 			}
3747 3747
 
3748 3748
 			$oldShares = $this->getShares($shareable->getResourceId());
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Publishing/PublishPlugin.php 2 patches
Indentation   +218 added lines, -218 removed lines patch added patch discarded remove patch
@@ -23,223 +23,223 @@
 block discarded – undo
23 23
 use Sabre\HTTP\ResponseInterface;
24 24
 
25 25
 class PublishPlugin extends ServerPlugin {
26
-	public const NS_CALENDARSERVER = 'http://calendarserver.org/ns/';
27
-
28
-	/**
29
-	 * Reference to SabreDAV server object.
30
-	 *
31
-	 * @var \Sabre\DAV\Server
32
-	 */
33
-	protected $server;
34
-
35
-	/**
36
-	 * PublishPlugin constructor.
37
-	 *
38
-	 * @param IConfig $config
39
-	 * @param IURLGenerator $urlGenerator
40
-	 */
41
-	public function __construct(
42
-		/**
43
-		 * Config instance to get instance secret.
44
-		 */
45
-		protected IConfig $config,
46
-		/**
47
-		 * URL Generator for absolute URLs.
48
-		 */
49
-		protected IURLGenerator $urlGenerator,
50
-	) {
51
-	}
52
-
53
-	/**
54
-	 * This method should return a list of server-features.
55
-	 *
56
-	 * This is for example 'versioning' and is added to the DAV: header
57
-	 * in an OPTIONS response.
58
-	 *
59
-	 * @return string[]
60
-	 */
61
-	public function getFeatures() {
62
-		// May have to be changed to be detected
63
-		return ['oc-calendar-publishing', 'calendarserver-sharing'];
64
-	}
65
-
66
-	/**
67
-	 * Returns a plugin name.
68
-	 *
69
-	 * Using this name other plugins will be able to access other plugins
70
-	 * using Sabre\DAV\Server::getPlugin
71
-	 *
72
-	 * @return string
73
-	 */
74
-	public function getPluginName() {
75
-		return 'oc-calendar-publishing';
76
-	}
77
-
78
-	/**
79
-	 * This initializes the plugin.
80
-	 *
81
-	 * This function is called by Sabre\DAV\Server, after
82
-	 * addPlugin is called.
83
-	 *
84
-	 * This method should set up the required event subscriptions.
85
-	 *
86
-	 * @param Server $server
87
-	 */
88
-	public function initialize(Server $server) {
89
-		$this->server = $server;
90
-
91
-		$this->server->on('method:POST', [$this, 'httpPost']);
92
-		$this->server->on('propFind', [$this, 'propFind']);
93
-	}
94
-
95
-	public function propFind(PropFind $propFind, INode $node) {
96
-		if ($node instanceof CalendarHome && $propFind->getDepth() === 1) {
97
-			$backend = $node->getCalDAVBackend();
98
-			if ($backend instanceof CalDavBackend) {
99
-				$calendars = array_filter(
100
-					$node->getChildren(),
101
-					static fn ($child) => $child instanceof Calendar,
102
-				);
103
-				$resourceIds = array_map(
104
-					static fn (Calendar $calendar) => $calendar->getResourceId(),
105
-					$calendars,
106
-				);
107
-				$backend->preloadPublishStatuses($resourceIds);
108
-			}
109
-		}
110
-		if ($node instanceof Calendar) {
111
-			$propFind->handle('{' . self::NS_CALENDARSERVER . '}publish-url', function () use ($node) {
112
-				if ($node->getPublishStatus()) {
113
-					// We return the publish-url only if the calendar is published.
114
-					$token = $node->getPublishStatus();
115
-					$publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri() . 'public-calendars/') . $token;
116
-
117
-					return new Publisher($publishUrl, true);
118
-				}
119
-			});
120
-
121
-			$propFind->handle('{' . self::NS_CALENDARSERVER . '}allowed-sharing-modes', function () use ($node) {
122
-				$canShare = (!$node->isSubscription() && $node->canWrite());
123
-				$canPublish = (!$node->isSubscription() && $node->canWrite());
124
-
125
-				if ($this->config->getAppValue('dav', 'limitAddressBookAndCalendarSharingToOwner', 'no') === 'yes') {
126
-					$canShare = $canShare && ($node->getOwner() === $node->getPrincipalURI());
127
-					$canPublish = $canPublish && ($node->getOwner() === $node->getPrincipalURI());
128
-				}
129
-
130
-				return new AllowedSharingModes($canShare, $canPublish);
131
-			});
132
-		}
133
-	}
134
-
135
-	/**
136
-	 * We intercept this to handle POST requests on calendars.
137
-	 *
138
-	 * @param RequestInterface $request
139
-	 * @param ResponseInterface $response
140
-	 *
141
-	 * @return void|bool
142
-	 */
143
-	public function httpPost(RequestInterface $request, ResponseInterface $response) {
144
-		$path = $request->getPath();
145
-
146
-		// Only handling xml
147
-		$contentType = (string)$request->getHeader('Content-Type');
148
-		if (!str_contains($contentType, 'application/xml') && !str_contains($contentType, 'text/xml')) {
149
-			return;
150
-		}
151
-
152
-		// Making sure the node exists
153
-		try {
154
-			$node = $this->server->tree->getNodeForPath($path);
155
-		} catch (NotFound $e) {
156
-			return;
157
-		}
158
-
159
-		$requestBody = $request->getBodyAsString();
160
-
161
-		// If this request handler could not deal with this POST request, it
162
-		// will return 'null' and other plugins get a chance to handle the
163
-		// request.
164
-		//
165
-		// However, we already requested the full body. This is a problem,
166
-		// because a body can only be read once. This is why we preemptively
167
-		// re-populated the request body with the existing data.
168
-		$request->setBody($requestBody);
169
-
170
-		$this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
171
-
172
-		switch ($documentType) {
173
-
174
-			case '{' . self::NS_CALENDARSERVER . '}publish-calendar':
175
-
176
-				// We can only deal with IShareableCalendar objects
177
-				if (!$node instanceof Calendar) {
178
-					return;
179
-				}
180
-				$this->server->transactionType = 'post-publish-calendar';
181
-
182
-				// Getting ACL info
183
-				$acl = $this->server->getPlugin('acl');
184
-
185
-				// If there's no ACL support, we allow everything
186
-				if ($acl) {
187
-					/** @var \Sabre\DAVACL\Plugin $acl */
188
-					$acl->checkPrivileges($path, '{DAV:}write');
189
-
190
-					$limitSharingToOwner = $this->config->getAppValue('dav', 'limitAddressBookAndCalendarSharingToOwner', 'no') === 'yes';
191
-					$isOwner = $acl->getCurrentUserPrincipal() === $node->getOwner();
192
-					if ($limitSharingToOwner && !$isOwner) {
193
-						return;
194
-					}
195
-				}
196
-
197
-				$node->setPublishStatus(true);
198
-
199
-				// iCloud sends back the 202, so we will too.
200
-				$response->setStatus(Http::STATUS_ACCEPTED);
201
-
202
-				// Adding this because sending a response body may cause issues,
203
-				// and I wanted some type of indicator the response was handled.
204
-				$response->setHeader('X-Sabre-Status', 'everything-went-well');
205
-
206
-				// Breaking the event chain
207
-				return false;
208
-
209
-			case '{' . self::NS_CALENDARSERVER . '}unpublish-calendar':
210
-
211
-				// We can only deal with IShareableCalendar objects
212
-				if (!$node instanceof Calendar) {
213
-					return;
214
-				}
215
-				$this->server->transactionType = 'post-unpublish-calendar';
216
-
217
-				// Getting ACL info
218
-				$acl = $this->server->getPlugin('acl');
219
-
220
-				// If there's no ACL support, we allow everything
221
-				if ($acl) {
222
-					/** @var \Sabre\DAVACL\Plugin $acl */
223
-					$acl->checkPrivileges($path, '{DAV:}write');
224
-
225
-					$limitSharingToOwner = $this->config->getAppValue('dav', 'limitAddressBookAndCalendarSharingToOwner', 'no') === 'yes';
226
-					$isOwner = $acl->getCurrentUserPrincipal() === $node->getOwner();
227
-					if ($limitSharingToOwner && !$isOwner) {
228
-						return;
229
-					}
230
-				}
231
-
232
-				$node->setPublishStatus(false);
233
-
234
-				$response->setStatus(Http::STATUS_OK);
235
-
236
-				// Adding this because sending a response body may cause issues,
237
-				// and I wanted some type of indicator the response was handled.
238
-				$response->setHeader('X-Sabre-Status', 'everything-went-well');
239
-
240
-				// Breaking the event chain
241
-				return false;
26
+    public const NS_CALENDARSERVER = 'http://calendarserver.org/ns/';
27
+
28
+    /**
29
+     * Reference to SabreDAV server object.
30
+     *
31
+     * @var \Sabre\DAV\Server
32
+     */
33
+    protected $server;
34
+
35
+    /**
36
+     * PublishPlugin constructor.
37
+     *
38
+     * @param IConfig $config
39
+     * @param IURLGenerator $urlGenerator
40
+     */
41
+    public function __construct(
42
+        /**
43
+         * Config instance to get instance secret.
44
+         */
45
+        protected IConfig $config,
46
+        /**
47
+         * URL Generator for absolute URLs.
48
+         */
49
+        protected IURLGenerator $urlGenerator,
50
+    ) {
51
+    }
52
+
53
+    /**
54
+     * This method should return a list of server-features.
55
+     *
56
+     * This is for example 'versioning' and is added to the DAV: header
57
+     * in an OPTIONS response.
58
+     *
59
+     * @return string[]
60
+     */
61
+    public function getFeatures() {
62
+        // May have to be changed to be detected
63
+        return ['oc-calendar-publishing', 'calendarserver-sharing'];
64
+    }
65
+
66
+    /**
67
+     * Returns a plugin name.
68
+     *
69
+     * Using this name other plugins will be able to access other plugins
70
+     * using Sabre\DAV\Server::getPlugin
71
+     *
72
+     * @return string
73
+     */
74
+    public function getPluginName() {
75
+        return 'oc-calendar-publishing';
76
+    }
77
+
78
+    /**
79
+     * This initializes the plugin.
80
+     *
81
+     * This function is called by Sabre\DAV\Server, after
82
+     * addPlugin is called.
83
+     *
84
+     * This method should set up the required event subscriptions.
85
+     *
86
+     * @param Server $server
87
+     */
88
+    public function initialize(Server $server) {
89
+        $this->server = $server;
90
+
91
+        $this->server->on('method:POST', [$this, 'httpPost']);
92
+        $this->server->on('propFind', [$this, 'propFind']);
93
+    }
94
+
95
+    public function propFind(PropFind $propFind, INode $node) {
96
+        if ($node instanceof CalendarHome && $propFind->getDepth() === 1) {
97
+            $backend = $node->getCalDAVBackend();
98
+            if ($backend instanceof CalDavBackend) {
99
+                $calendars = array_filter(
100
+                    $node->getChildren(),
101
+                    static fn ($child) => $child instanceof Calendar,
102
+                );
103
+                $resourceIds = array_map(
104
+                    static fn (Calendar $calendar) => $calendar->getResourceId(),
105
+                    $calendars,
106
+                );
107
+                $backend->preloadPublishStatuses($resourceIds);
108
+            }
109
+        }
110
+        if ($node instanceof Calendar) {
111
+            $propFind->handle('{' . self::NS_CALENDARSERVER . '}publish-url', function () use ($node) {
112
+                if ($node->getPublishStatus()) {
113
+                    // We return the publish-url only if the calendar is published.
114
+                    $token = $node->getPublishStatus();
115
+                    $publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri() . 'public-calendars/') . $token;
116
+
117
+                    return new Publisher($publishUrl, true);
118
+                }
119
+            });
120
+
121
+            $propFind->handle('{' . self::NS_CALENDARSERVER . '}allowed-sharing-modes', function () use ($node) {
122
+                $canShare = (!$node->isSubscription() && $node->canWrite());
123
+                $canPublish = (!$node->isSubscription() && $node->canWrite());
124
+
125
+                if ($this->config->getAppValue('dav', 'limitAddressBookAndCalendarSharingToOwner', 'no') === 'yes') {
126
+                    $canShare = $canShare && ($node->getOwner() === $node->getPrincipalURI());
127
+                    $canPublish = $canPublish && ($node->getOwner() === $node->getPrincipalURI());
128
+                }
129
+
130
+                return new AllowedSharingModes($canShare, $canPublish);
131
+            });
132
+        }
133
+    }
134
+
135
+    /**
136
+     * We intercept this to handle POST requests on calendars.
137
+     *
138
+     * @param RequestInterface $request
139
+     * @param ResponseInterface $response
140
+     *
141
+     * @return void|bool
142
+     */
143
+    public function httpPost(RequestInterface $request, ResponseInterface $response) {
144
+        $path = $request->getPath();
145
+
146
+        // Only handling xml
147
+        $contentType = (string)$request->getHeader('Content-Type');
148
+        if (!str_contains($contentType, 'application/xml') && !str_contains($contentType, 'text/xml')) {
149
+            return;
150
+        }
151
+
152
+        // Making sure the node exists
153
+        try {
154
+            $node = $this->server->tree->getNodeForPath($path);
155
+        } catch (NotFound $e) {
156
+            return;
157
+        }
158
+
159
+        $requestBody = $request->getBodyAsString();
160
+
161
+        // If this request handler could not deal with this POST request, it
162
+        // will return 'null' and other plugins get a chance to handle the
163
+        // request.
164
+        //
165
+        // However, we already requested the full body. This is a problem,
166
+        // because a body can only be read once. This is why we preemptively
167
+        // re-populated the request body with the existing data.
168
+        $request->setBody($requestBody);
169
+
170
+        $this->server->xml->parse($requestBody, $request->getUrl(), $documentType);
171
+
172
+        switch ($documentType) {
173
+
174
+            case '{' . self::NS_CALENDARSERVER . '}publish-calendar':
175
+
176
+                // We can only deal with IShareableCalendar objects
177
+                if (!$node instanceof Calendar) {
178
+                    return;
179
+                }
180
+                $this->server->transactionType = 'post-publish-calendar';
181
+
182
+                // Getting ACL info
183
+                $acl = $this->server->getPlugin('acl');
184
+
185
+                // If there's no ACL support, we allow everything
186
+                if ($acl) {
187
+                    /** @var \Sabre\DAVACL\Plugin $acl */
188
+                    $acl->checkPrivileges($path, '{DAV:}write');
189
+
190
+                    $limitSharingToOwner = $this->config->getAppValue('dav', 'limitAddressBookAndCalendarSharingToOwner', 'no') === 'yes';
191
+                    $isOwner = $acl->getCurrentUserPrincipal() === $node->getOwner();
192
+                    if ($limitSharingToOwner && !$isOwner) {
193
+                        return;
194
+                    }
195
+                }
196
+
197
+                $node->setPublishStatus(true);
198
+
199
+                // iCloud sends back the 202, so we will too.
200
+                $response->setStatus(Http::STATUS_ACCEPTED);
201
+
202
+                // Adding this because sending a response body may cause issues,
203
+                // and I wanted some type of indicator the response was handled.
204
+                $response->setHeader('X-Sabre-Status', 'everything-went-well');
205
+
206
+                // Breaking the event chain
207
+                return false;
208
+
209
+            case '{' . self::NS_CALENDARSERVER . '}unpublish-calendar':
210
+
211
+                // We can only deal with IShareableCalendar objects
212
+                if (!$node instanceof Calendar) {
213
+                    return;
214
+                }
215
+                $this->server->transactionType = 'post-unpublish-calendar';
216
+
217
+                // Getting ACL info
218
+                $acl = $this->server->getPlugin('acl');
219
+
220
+                // If there's no ACL support, we allow everything
221
+                if ($acl) {
222
+                    /** @var \Sabre\DAVACL\Plugin $acl */
223
+                    $acl->checkPrivileges($path, '{DAV:}write');
224
+
225
+                    $limitSharingToOwner = $this->config->getAppValue('dav', 'limitAddressBookAndCalendarSharingToOwner', 'no') === 'yes';
226
+                    $isOwner = $acl->getCurrentUserPrincipal() === $node->getOwner();
227
+                    if ($limitSharingToOwner && !$isOwner) {
228
+                        return;
229
+                    }
230
+                }
231
+
232
+                $node->setPublishStatus(false);
233
+
234
+                $response->setStatus(Http::STATUS_OK);
235
+
236
+                // Adding this because sending a response body may cause issues,
237
+                // and I wanted some type of indicator the response was handled.
238
+                $response->setHeader('X-Sabre-Status', 'everything-went-well');
239
+
240
+                // Breaking the event chain
241
+                return false;
242 242
 
243
-		}
244
-	}
243
+        }
244
+    }
245 245
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -108,17 +108,17 @@  discard block
 block discarded – undo
108 108
 			}
109 109
 		}
110 110
 		if ($node instanceof Calendar) {
111
-			$propFind->handle('{' . self::NS_CALENDARSERVER . '}publish-url', function () use ($node) {
111
+			$propFind->handle('{'.self::NS_CALENDARSERVER.'}publish-url', function() use ($node) {
112 112
 				if ($node->getPublishStatus()) {
113 113
 					// We return the publish-url only if the calendar is published.
114 114
 					$token = $node->getPublishStatus();
115
-					$publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri() . 'public-calendars/') . $token;
115
+					$publishUrl = $this->urlGenerator->getAbsoluteURL($this->server->getBaseUri().'public-calendars/').$token;
116 116
 
117 117
 					return new Publisher($publishUrl, true);
118 118
 				}
119 119
 			});
120 120
 
121
-			$propFind->handle('{' . self::NS_CALENDARSERVER . '}allowed-sharing-modes', function () use ($node) {
121
+			$propFind->handle('{'.self::NS_CALENDARSERVER.'}allowed-sharing-modes', function() use ($node) {
122 122
 				$canShare = (!$node->isSubscription() && $node->canWrite());
123 123
 				$canPublish = (!$node->isSubscription() && $node->canWrite());
124 124
 
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 		$path = $request->getPath();
145 145
 
146 146
 		// Only handling xml
147
-		$contentType = (string)$request->getHeader('Content-Type');
147
+		$contentType = (string) $request->getHeader('Content-Type');
148 148
 		if (!str_contains($contentType, 'application/xml') && !str_contains($contentType, 'text/xml')) {
149 149
 			return;
150 150
 		}
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 
172 172
 		switch ($documentType) {
173 173
 
174
-			case '{' . self::NS_CALENDARSERVER . '}publish-calendar':
174
+			case '{'.self::NS_CALENDARSERVER.'}publish-calendar':
175 175
 
176 176
 				// We can only deal with IShareableCalendar objects
177 177
 				if (!$node instanceof Calendar) {
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
 				// Breaking the event chain
207 207
 				return false;
208 208
 
209
-			case '{' . self::NS_CALENDARSERVER . '}unpublish-calendar':
209
+			case '{'.self::NS_CALENDARSERVER.'}unpublish-calendar':
210 210
 
211 211
 				// We can only deal with IShareableCalendar objects
212 212
 				if (!$node instanceof Calendar) {
Please login to merge, or discard this patch.
apps/dav/lib/RootCollection.php 1 patch
Indentation   +167 added lines, -167 removed lines patch added patch discarded remove patch
@@ -50,171 +50,171 @@
 block discarded – undo
50 50
 use Sabre\DAV\SimpleCollection;
51 51
 
52 52
 class RootCollection extends SimpleCollection {
53
-	public function __construct() {
54
-		$l10n = \OC::$server->getL10N('dav');
55
-		$random = Server::get(ISecureRandom::class);
56
-		$logger = Server::get(LoggerInterface::class);
57
-		$userManager = Server::get(IUserManager::class);
58
-		$userSession = Server::get(IUserSession::class);
59
-		$groupManager = Server::get(IGroupManager::class);
60
-		$shareManager = Server::get(\OCP\Share\IManager::class);
61
-		$db = Server::get(IDBConnection::class);
62
-		$dispatcher = Server::get(IEventDispatcher::class);
63
-		$config = Server::get(IConfig::class);
64
-		$proxyMapper = Server::get(ProxyMapper::class);
65
-		$rootFolder = Server::get(IRootFolder::class);
66
-		$federatedCalendarFactory = Server::get(FederatedCalendarFactory::class);
67
-
68
-		$userPrincipalBackend = new Principal(
69
-			$userManager,
70
-			$groupManager,
71
-			Server::get(IAccountManager::class),
72
-			$shareManager,
73
-			Server::get(IUserSession::class),
74
-			Server::get(IAppManager::class),
75
-			$proxyMapper,
76
-			Server::get(KnownUserService::class),
77
-			Server::get(IConfig::class),
78
-			\OC::$server->getL10NFactory()
79
-		);
80
-
81
-		$groupPrincipalBackend = new GroupPrincipalBackend($groupManager, $userSession, $shareManager, $config);
82
-		$calendarResourcePrincipalBackend = new ResourcePrincipalBackend($db, $userSession, $groupManager, $logger, $proxyMapper);
83
-		$calendarRoomPrincipalBackend = new RoomPrincipalBackend($db, $userSession, $groupManager, $logger, $proxyMapper);
84
-		$remoteUserPrincipalBackend = Server::get(RemoteUserPrincipalBackend::class);
85
-		// as soon as debug mode is enabled we allow listing of principals
86
-		$disableListing = !$config->getSystemValue('debug', false);
87
-
88
-		// setup the first level of the dav tree
89
-		$userPrincipals = new Collection($userPrincipalBackend, 'principals/users');
90
-		$userPrincipals->disableListing = $disableListing;
91
-		$groupPrincipals = new Collection($groupPrincipalBackend, 'principals/groups');
92
-		$groupPrincipals->disableListing = $disableListing;
93
-		$systemPrincipals = new Collection(new SystemPrincipalBackend(), 'principals/system');
94
-		$systemPrincipals->disableListing = $disableListing;
95
-		$calendarResourcePrincipals = new Collection($calendarResourcePrincipalBackend, 'principals/calendar-resources');
96
-		$calendarRoomPrincipals = new Collection($calendarRoomPrincipalBackend, 'principals/calendar-rooms');
97
-		$remoteUserPrincipals = new Collection($remoteUserPrincipalBackend, RemoteUserPrincipalBackend::PRINCIPAL_PREFIX);
98
-		$calendarSharingBackend = Server::get(Backend::class);
99
-
100
-		$filesCollection = new Files\RootCollection($userPrincipalBackend, 'principals/users');
101
-		$filesCollection->disableListing = $disableListing;
102
-		$caldavBackend = new CalDavBackend(
103
-			$db,
104
-			$userPrincipalBackend,
105
-			$userManager,
106
-			$random,
107
-			$logger,
108
-			$dispatcher,
109
-			$config,
110
-			$calendarSharingBackend,
111
-			Server::get(FederatedCalendarMapper::class),
112
-			Server::get(ICacheFactory::class),
113
-			false,
114
-		);
115
-		$userCalendarRoot = new CalendarRoot($userPrincipalBackend, $caldavBackend, 'principals/users', $logger, $l10n, $config, $federatedCalendarFactory);
116
-		$userCalendarRoot->disableListing = $disableListing;
117
-
118
-		$remoteUserCalendarRoot = new CalendarRoot($remoteUserPrincipalBackend, $caldavBackend, RemoteUserPrincipalBackend::PRINCIPAL_PREFIX, $logger, $l10n, $config, $federatedCalendarFactory);
119
-		$remoteUserCalendarRoot->disableListing = $disableListing;
120
-
121
-		$resourceCalendarRoot = new CalendarRoot($calendarResourcePrincipalBackend, $caldavBackend, 'principals/calendar-resources', $logger, $l10n, $config, $federatedCalendarFactory);
122
-		$resourceCalendarRoot->disableListing = $disableListing;
123
-		$roomCalendarRoot = new CalendarRoot($calendarRoomPrincipalBackend, $caldavBackend, 'principals/calendar-rooms', $logger, $l10n, $config, $federatedCalendarFactory);
124
-		$roomCalendarRoot->disableListing = $disableListing;
125
-
126
-		$publicCalendarRoot = new PublicCalendarRoot($caldavBackend, $l10n, $config, $logger);
127
-
128
-		$systemTagCollection = Server::get(SystemTagsByIdCollection::class);
129
-		$systemTagRelationsCollection = new SystemTagsRelationsCollection(
130
-			Server::get(ISystemTagManager::class),
131
-			Server::get(ISystemTagObjectMapper::class),
132
-			Server::get(IUserSession::class),
133
-			$groupManager,
134
-			$dispatcher,
135
-			$rootFolder,
136
-		);
137
-		$systemTagInUseCollection = Server::get(SystemTagsInUseCollection::class);
138
-		$commentsCollection = new Comments\RootCollection(
139
-			Server::get(ICommentsManager::class),
140
-			$userManager,
141
-			Server::get(IUserSession::class),
142
-			$dispatcher,
143
-			$logger
144
-		);
145
-
146
-		$contactsSharingBackend = Server::get(\OCA\DAV\CardDAV\Sharing\Backend::class);
147
-		$config = Server::get(IConfig::class);
148
-
149
-		$pluginManager = new PluginManager(\OC::$server, Server::get(IAppManager::class));
150
-		$usersCardDavBackend = new CardDavBackend(
151
-			$db,
152
-			$userPrincipalBackend,
153
-			$userManager,
154
-			$dispatcher,
155
-			$contactsSharingBackend,
156
-			$config
157
-		);
158
-		$usersAddressBookRoot = new AddressBookRoot($userPrincipalBackend, $usersCardDavBackend, $pluginManager, $userSession->getUser(), $groupManager, 'principals/users');
159
-		$usersAddressBookRoot->disableListing = $disableListing;
160
-
161
-		$systemCardDavBackend = new CardDavBackend(
162
-			$db,
163
-			$userPrincipalBackend,
164
-			$userManager,
165
-			$dispatcher,
166
-			$contactsSharingBackend,
167
-			$config
168
-		);
169
-		$systemAddressBookRoot = new AddressBookRoot(new SystemPrincipalBackend(), $systemCardDavBackend, $pluginManager, $userSession->getUser(), $groupManager, 'principals/system');
170
-		$systemAddressBookRoot->disableListing = $disableListing;
171
-
172
-		$uploadCollection = new Upload\RootCollection(
173
-			$userPrincipalBackend,
174
-			'principals/users',
175
-			Server::get(CleanupService::class),
176
-			$rootFolder,
177
-			$userSession,
178
-			$shareManager,
179
-		);
180
-		$uploadCollection->disableListing = $disableListing;
181
-
182
-		$avatarCollection = new Avatars\RootCollection($userPrincipalBackend, 'principals/users');
183
-		$avatarCollection->disableListing = $disableListing;
184
-
185
-		$appleProvisioning = new AppleProvisioningNode(
186
-			Server::get(ITimeFactory::class));
187
-
188
-		$children = [
189
-			new SimpleCollection('principals', [
190
-				$userPrincipals,
191
-				$groupPrincipals,
192
-				$systemPrincipals,
193
-				$calendarResourcePrincipals,
194
-				$calendarRoomPrincipals,
195
-				$remoteUserPrincipals]),
196
-			$filesCollection,
197
-			$userCalendarRoot,
198
-			$remoteUserCalendarRoot,
199
-			new SimpleCollection('system-calendars', [
200
-				$resourceCalendarRoot,
201
-				$roomCalendarRoot,
202
-			]),
203
-			$publicCalendarRoot,
204
-			new SimpleCollection('addressbooks', [
205
-				$usersAddressBookRoot,
206
-				$systemAddressBookRoot]),
207
-			$systemTagCollection,
208
-			$systemTagRelationsCollection,
209
-			$systemTagInUseCollection,
210
-			$commentsCollection,
211
-			$uploadCollection,
212
-			$avatarCollection,
213
-			new SimpleCollection('provisioning', [
214
-				$appleProvisioning
215
-			])
216
-		];
217
-
218
-		parent::__construct('root', $children);
219
-	}
53
+    public function __construct() {
54
+        $l10n = \OC::$server->getL10N('dav');
55
+        $random = Server::get(ISecureRandom::class);
56
+        $logger = Server::get(LoggerInterface::class);
57
+        $userManager = Server::get(IUserManager::class);
58
+        $userSession = Server::get(IUserSession::class);
59
+        $groupManager = Server::get(IGroupManager::class);
60
+        $shareManager = Server::get(\OCP\Share\IManager::class);
61
+        $db = Server::get(IDBConnection::class);
62
+        $dispatcher = Server::get(IEventDispatcher::class);
63
+        $config = Server::get(IConfig::class);
64
+        $proxyMapper = Server::get(ProxyMapper::class);
65
+        $rootFolder = Server::get(IRootFolder::class);
66
+        $federatedCalendarFactory = Server::get(FederatedCalendarFactory::class);
67
+
68
+        $userPrincipalBackend = new Principal(
69
+            $userManager,
70
+            $groupManager,
71
+            Server::get(IAccountManager::class),
72
+            $shareManager,
73
+            Server::get(IUserSession::class),
74
+            Server::get(IAppManager::class),
75
+            $proxyMapper,
76
+            Server::get(KnownUserService::class),
77
+            Server::get(IConfig::class),
78
+            \OC::$server->getL10NFactory()
79
+        );
80
+
81
+        $groupPrincipalBackend = new GroupPrincipalBackend($groupManager, $userSession, $shareManager, $config);
82
+        $calendarResourcePrincipalBackend = new ResourcePrincipalBackend($db, $userSession, $groupManager, $logger, $proxyMapper);
83
+        $calendarRoomPrincipalBackend = new RoomPrincipalBackend($db, $userSession, $groupManager, $logger, $proxyMapper);
84
+        $remoteUserPrincipalBackend = Server::get(RemoteUserPrincipalBackend::class);
85
+        // as soon as debug mode is enabled we allow listing of principals
86
+        $disableListing = !$config->getSystemValue('debug', false);
87
+
88
+        // setup the first level of the dav tree
89
+        $userPrincipals = new Collection($userPrincipalBackend, 'principals/users');
90
+        $userPrincipals->disableListing = $disableListing;
91
+        $groupPrincipals = new Collection($groupPrincipalBackend, 'principals/groups');
92
+        $groupPrincipals->disableListing = $disableListing;
93
+        $systemPrincipals = new Collection(new SystemPrincipalBackend(), 'principals/system');
94
+        $systemPrincipals->disableListing = $disableListing;
95
+        $calendarResourcePrincipals = new Collection($calendarResourcePrincipalBackend, 'principals/calendar-resources');
96
+        $calendarRoomPrincipals = new Collection($calendarRoomPrincipalBackend, 'principals/calendar-rooms');
97
+        $remoteUserPrincipals = new Collection($remoteUserPrincipalBackend, RemoteUserPrincipalBackend::PRINCIPAL_PREFIX);
98
+        $calendarSharingBackend = Server::get(Backend::class);
99
+
100
+        $filesCollection = new Files\RootCollection($userPrincipalBackend, 'principals/users');
101
+        $filesCollection->disableListing = $disableListing;
102
+        $caldavBackend = new CalDavBackend(
103
+            $db,
104
+            $userPrincipalBackend,
105
+            $userManager,
106
+            $random,
107
+            $logger,
108
+            $dispatcher,
109
+            $config,
110
+            $calendarSharingBackend,
111
+            Server::get(FederatedCalendarMapper::class),
112
+            Server::get(ICacheFactory::class),
113
+            false,
114
+        );
115
+        $userCalendarRoot = new CalendarRoot($userPrincipalBackend, $caldavBackend, 'principals/users', $logger, $l10n, $config, $federatedCalendarFactory);
116
+        $userCalendarRoot->disableListing = $disableListing;
117
+
118
+        $remoteUserCalendarRoot = new CalendarRoot($remoteUserPrincipalBackend, $caldavBackend, RemoteUserPrincipalBackend::PRINCIPAL_PREFIX, $logger, $l10n, $config, $federatedCalendarFactory);
119
+        $remoteUserCalendarRoot->disableListing = $disableListing;
120
+
121
+        $resourceCalendarRoot = new CalendarRoot($calendarResourcePrincipalBackend, $caldavBackend, 'principals/calendar-resources', $logger, $l10n, $config, $federatedCalendarFactory);
122
+        $resourceCalendarRoot->disableListing = $disableListing;
123
+        $roomCalendarRoot = new CalendarRoot($calendarRoomPrincipalBackend, $caldavBackend, 'principals/calendar-rooms', $logger, $l10n, $config, $federatedCalendarFactory);
124
+        $roomCalendarRoot->disableListing = $disableListing;
125
+
126
+        $publicCalendarRoot = new PublicCalendarRoot($caldavBackend, $l10n, $config, $logger);
127
+
128
+        $systemTagCollection = Server::get(SystemTagsByIdCollection::class);
129
+        $systemTagRelationsCollection = new SystemTagsRelationsCollection(
130
+            Server::get(ISystemTagManager::class),
131
+            Server::get(ISystemTagObjectMapper::class),
132
+            Server::get(IUserSession::class),
133
+            $groupManager,
134
+            $dispatcher,
135
+            $rootFolder,
136
+        );
137
+        $systemTagInUseCollection = Server::get(SystemTagsInUseCollection::class);
138
+        $commentsCollection = new Comments\RootCollection(
139
+            Server::get(ICommentsManager::class),
140
+            $userManager,
141
+            Server::get(IUserSession::class),
142
+            $dispatcher,
143
+            $logger
144
+        );
145
+
146
+        $contactsSharingBackend = Server::get(\OCA\DAV\CardDAV\Sharing\Backend::class);
147
+        $config = Server::get(IConfig::class);
148
+
149
+        $pluginManager = new PluginManager(\OC::$server, Server::get(IAppManager::class));
150
+        $usersCardDavBackend = new CardDavBackend(
151
+            $db,
152
+            $userPrincipalBackend,
153
+            $userManager,
154
+            $dispatcher,
155
+            $contactsSharingBackend,
156
+            $config
157
+        );
158
+        $usersAddressBookRoot = new AddressBookRoot($userPrincipalBackend, $usersCardDavBackend, $pluginManager, $userSession->getUser(), $groupManager, 'principals/users');
159
+        $usersAddressBookRoot->disableListing = $disableListing;
160
+
161
+        $systemCardDavBackend = new CardDavBackend(
162
+            $db,
163
+            $userPrincipalBackend,
164
+            $userManager,
165
+            $dispatcher,
166
+            $contactsSharingBackend,
167
+            $config
168
+        );
169
+        $systemAddressBookRoot = new AddressBookRoot(new SystemPrincipalBackend(), $systemCardDavBackend, $pluginManager, $userSession->getUser(), $groupManager, 'principals/system');
170
+        $systemAddressBookRoot->disableListing = $disableListing;
171
+
172
+        $uploadCollection = new Upload\RootCollection(
173
+            $userPrincipalBackend,
174
+            'principals/users',
175
+            Server::get(CleanupService::class),
176
+            $rootFolder,
177
+            $userSession,
178
+            $shareManager,
179
+        );
180
+        $uploadCollection->disableListing = $disableListing;
181
+
182
+        $avatarCollection = new Avatars\RootCollection($userPrincipalBackend, 'principals/users');
183
+        $avatarCollection->disableListing = $disableListing;
184
+
185
+        $appleProvisioning = new AppleProvisioningNode(
186
+            Server::get(ITimeFactory::class));
187
+
188
+        $children = [
189
+            new SimpleCollection('principals', [
190
+                $userPrincipals,
191
+                $groupPrincipals,
192
+                $systemPrincipals,
193
+                $calendarResourcePrincipals,
194
+                $calendarRoomPrincipals,
195
+                $remoteUserPrincipals]),
196
+            $filesCollection,
197
+            $userCalendarRoot,
198
+            $remoteUserCalendarRoot,
199
+            new SimpleCollection('system-calendars', [
200
+                $resourceCalendarRoot,
201
+                $roomCalendarRoot,
202
+            ]),
203
+            $publicCalendarRoot,
204
+            new SimpleCollection('addressbooks', [
205
+                $usersAddressBookRoot,
206
+                $systemAddressBookRoot]),
207
+            $systemTagCollection,
208
+            $systemTagRelationsCollection,
209
+            $systemTagInUseCollection,
210
+            $commentsCollection,
211
+            $uploadCollection,
212
+            $avatarCollection,
213
+            new SimpleCollection('provisioning', [
214
+                $appleProvisioning
215
+            ])
216
+        ];
217
+
218
+        parent::__construct('root', $children);
219
+    }
220 220
 }
Please login to merge, or discard this patch.
apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php 1 patch
Indentation   +176 added lines, -176 removed lines patch added patch discarded remove patch
@@ -46,157 +46,157 @@  discard block
 block discarded – undo
46 46
 abstract class AbstractCalDavBackend extends TestCase {
47 47
 
48 48
 
49
-	protected CalDavBackend $backend;
50
-	protected Principal&MockObject $principal;
51
-	protected IUserManager&MockObject $userManager;
52
-	protected IGroupManager&MockObject $groupManager;
53
-	protected IEventDispatcher&MockObject $dispatcher;
54
-	private LoggerInterface&MockObject $logger;
55
-	private IConfig&MockObject $config;
56
-	private ISecureRandom $random;
57
-	protected SharingBackend $sharingBackend;
58
-	protected IDBConnection $db;
59
-	protected RemoteUserPrincipalBackend&MockObject $remoteUserPrincipalBackend;
60
-	protected FederationSharingService&MockObject $federationSharingService;
61
-	protected FederatedCalendarMapper&MockObject $federatedCalendarMapper;
62
-	protected ICacheFactory $cacheFactory;
49
+    protected CalDavBackend $backend;
50
+    protected Principal&MockObject $principal;
51
+    protected IUserManager&MockObject $userManager;
52
+    protected IGroupManager&MockObject $groupManager;
53
+    protected IEventDispatcher&MockObject $dispatcher;
54
+    private LoggerInterface&MockObject $logger;
55
+    private IConfig&MockObject $config;
56
+    private ISecureRandom $random;
57
+    protected SharingBackend $sharingBackend;
58
+    protected IDBConnection $db;
59
+    protected RemoteUserPrincipalBackend&MockObject $remoteUserPrincipalBackend;
60
+    protected FederationSharingService&MockObject $federationSharingService;
61
+    protected FederatedCalendarMapper&MockObject $federatedCalendarMapper;
62
+    protected ICacheFactory $cacheFactory;
63 63
 
64
-	public const UNIT_TEST_USER = 'principals/users/caldav-unit-test';
65
-	public const UNIT_TEST_USER1 = 'principals/users/caldav-unit-test1';
66
-	public const UNIT_TEST_GROUP = 'principals/groups/caldav-unit-test-group';
67
-	public const UNIT_TEST_GROUP2 = 'principals/groups/caldav-unit-test-group2';
64
+    public const UNIT_TEST_USER = 'principals/users/caldav-unit-test';
65
+    public const UNIT_TEST_USER1 = 'principals/users/caldav-unit-test1';
66
+    public const UNIT_TEST_GROUP = 'principals/groups/caldav-unit-test-group';
67
+    public const UNIT_TEST_GROUP2 = 'principals/groups/caldav-unit-test-group2';
68 68
 
69
-	protected function setUp(): void {
70
-		parent::setUp();
69
+    protected function setUp(): void {
70
+        parent::setUp();
71 71
 
72
-		$this->userManager = $this->createMock(IUserManager::class);
73
-		$this->groupManager = $this->createMock(IGroupManager::class);
74
-		$this->dispatcher = $this->createMock(IEventDispatcher::class);
75
-		$this->principal = $this->getMockBuilder(Principal::class)
76
-			->setConstructorArgs([
77
-				$this->userManager,
78
-				$this->groupManager,
79
-				$this->createMock(IAccountManager::class),
80
-				$this->createMock(ShareManager::class),
81
-				$this->createMock(IUserSession::class),
82
-				$this->createMock(IAppManager::class),
83
-				$this->createMock(ProxyMapper::class),
84
-				$this->createMock(KnownUserService::class),
85
-				$this->createMock(IConfig::class),
86
-				$this->createMock(IFactory::class)
87
-			])
88
-			->onlyMethods(['getPrincipalByPath', 'getGroupMembership', 'findByUri'])
89
-			->getMock();
90
-		$this->principal->expects($this->any())->method('getPrincipalByPath')
91
-			->willReturn([
92
-				'uri' => 'principals/best-friend',
93
-				'{DAV:}displayname' => 'User\'s displayname',
94
-			]);
95
-		$this->principal->expects($this->any())->method('getGroupMembership')
96
-			->withAnyParameters()
97
-			->willReturn([self::UNIT_TEST_GROUP, self::UNIT_TEST_GROUP2]);
72
+        $this->userManager = $this->createMock(IUserManager::class);
73
+        $this->groupManager = $this->createMock(IGroupManager::class);
74
+        $this->dispatcher = $this->createMock(IEventDispatcher::class);
75
+        $this->principal = $this->getMockBuilder(Principal::class)
76
+            ->setConstructorArgs([
77
+                $this->userManager,
78
+                $this->groupManager,
79
+                $this->createMock(IAccountManager::class),
80
+                $this->createMock(ShareManager::class),
81
+                $this->createMock(IUserSession::class),
82
+                $this->createMock(IAppManager::class),
83
+                $this->createMock(ProxyMapper::class),
84
+                $this->createMock(KnownUserService::class),
85
+                $this->createMock(IConfig::class),
86
+                $this->createMock(IFactory::class)
87
+            ])
88
+            ->onlyMethods(['getPrincipalByPath', 'getGroupMembership', 'findByUri'])
89
+            ->getMock();
90
+        $this->principal->expects($this->any())->method('getPrincipalByPath')
91
+            ->willReturn([
92
+                'uri' => 'principals/best-friend',
93
+                '{DAV:}displayname' => 'User\'s displayname',
94
+            ]);
95
+        $this->principal->expects($this->any())->method('getGroupMembership')
96
+            ->withAnyParameters()
97
+            ->willReturn([self::UNIT_TEST_GROUP, self::UNIT_TEST_GROUP2]);
98 98
 
99
-		$this->db = Server::get(IDBConnection::class);
100
-		$this->random = Server::get(ISecureRandom::class);
101
-		$this->logger = $this->createMock(LoggerInterface::class);
102
-		$this->config = $this->createMock(IConfig::class);
103
-		$this->remoteUserPrincipalBackend = $this->createMock(RemoteUserPrincipalBackend::class);
104
-		$this->federationSharingService = $this->createMock(FederationSharingService::class);
105
-		$this->federatedCalendarMapper = $this->createMock(FederatedCalendarMapper::class);
106
-		$this->sharingBackend = new SharingBackend(
107
-			$this->userManager,
108
-			$this->groupManager,
109
-			$this->principal,
110
-			$this->remoteUserPrincipalBackend,
111
-			$this->createMock(ICacheFactory::class),
112
-			new Service(new SharingMapper($this->db)),
113
-			$this->federationSharingService,
114
-			$this->logger);
115
-		$this->cacheFactory = $this->createMock(ICacheFactory::class);
116
-		$this->backend = new CalDavBackend(
117
-			$this->db,
118
-			$this->principal,
119
-			$this->userManager,
120
-			$this->random,
121
-			$this->logger,
122
-			$this->dispatcher,
123
-			$this->config,
124
-			$this->sharingBackend,
125
-			$this->federatedCalendarMapper,
126
-			$this->cacheFactory,
127
-			false,
128
-		);
99
+        $this->db = Server::get(IDBConnection::class);
100
+        $this->random = Server::get(ISecureRandom::class);
101
+        $this->logger = $this->createMock(LoggerInterface::class);
102
+        $this->config = $this->createMock(IConfig::class);
103
+        $this->remoteUserPrincipalBackend = $this->createMock(RemoteUserPrincipalBackend::class);
104
+        $this->federationSharingService = $this->createMock(FederationSharingService::class);
105
+        $this->federatedCalendarMapper = $this->createMock(FederatedCalendarMapper::class);
106
+        $this->sharingBackend = new SharingBackend(
107
+            $this->userManager,
108
+            $this->groupManager,
109
+            $this->principal,
110
+            $this->remoteUserPrincipalBackend,
111
+            $this->createMock(ICacheFactory::class),
112
+            new Service(new SharingMapper($this->db)),
113
+            $this->federationSharingService,
114
+            $this->logger);
115
+        $this->cacheFactory = $this->createMock(ICacheFactory::class);
116
+        $this->backend = new CalDavBackend(
117
+            $this->db,
118
+            $this->principal,
119
+            $this->userManager,
120
+            $this->random,
121
+            $this->logger,
122
+            $this->dispatcher,
123
+            $this->config,
124
+            $this->sharingBackend,
125
+            $this->federatedCalendarMapper,
126
+            $this->cacheFactory,
127
+            false,
128
+        );
129 129
 
130
-		$this->cleanUpBackend();
131
-	}
130
+        $this->cleanUpBackend();
131
+    }
132 132
 
133
-	protected function tearDown(): void {
134
-		$this->cleanUpBackend();
135
-		parent::tearDown();
136
-	}
133
+    protected function tearDown(): void {
134
+        $this->cleanUpBackend();
135
+        parent::tearDown();
136
+    }
137 137
 
138
-	public function cleanUpBackend(): void {
139
-		if (is_null($this->backend)) {
140
-			return;
141
-		}
142
-		$this->principal->expects($this->any())->method('getGroupMembership')
143
-			->withAnyParameters()
144
-			->willReturn([self::UNIT_TEST_GROUP, self::UNIT_TEST_GROUP2]);
145
-		$this->cleanupForPrincipal(self::UNIT_TEST_USER);
146
-		$this->cleanupForPrincipal(self::UNIT_TEST_USER1);
147
-	}
138
+    public function cleanUpBackend(): void {
139
+        if (is_null($this->backend)) {
140
+            return;
141
+        }
142
+        $this->principal->expects($this->any())->method('getGroupMembership')
143
+            ->withAnyParameters()
144
+            ->willReturn([self::UNIT_TEST_GROUP, self::UNIT_TEST_GROUP2]);
145
+        $this->cleanupForPrincipal(self::UNIT_TEST_USER);
146
+        $this->cleanupForPrincipal(self::UNIT_TEST_USER1);
147
+    }
148 148
 
149
-	private function cleanupForPrincipal($principal): void {
150
-		$calendars = $this->backend->getCalendarsForUser($principal);
151
-		$this->dispatcher->expects(self::any())
152
-			->method('dispatchTyped');
153
-		foreach ($calendars as $calendar) {
154
-			$this->backend->deleteCalendar($calendar['id'], true);
155
-		}
156
-		$subscriptions = $this->backend->getSubscriptionsForUser($principal);
157
-		foreach ($subscriptions as $subscription) {
158
-			$this->backend->deleteSubscription($subscription['id']);
159
-		}
160
-	}
149
+    private function cleanupForPrincipal($principal): void {
150
+        $calendars = $this->backend->getCalendarsForUser($principal);
151
+        $this->dispatcher->expects(self::any())
152
+            ->method('dispatchTyped');
153
+        foreach ($calendars as $calendar) {
154
+            $this->backend->deleteCalendar($calendar['id'], true);
155
+        }
156
+        $subscriptions = $this->backend->getSubscriptionsForUser($principal);
157
+        foreach ($subscriptions as $subscription) {
158
+            $this->backend->deleteSubscription($subscription['id']);
159
+        }
160
+    }
161 161
 
162
-	protected function createTestCalendar(): int {
163
-		$this->dispatcher->expects(self::any())
164
-			->method('dispatchTyped');
162
+    protected function createTestCalendar(): int {
163
+        $this->dispatcher->expects(self::any())
164
+            ->method('dispatchTyped');
165 165
 
166
-		$this->backend->createCalendar(self::UNIT_TEST_USER, 'Example', [
167
-			'{http://apple.com/ns/ical/}calendar-color' => '#1C4587FF'
168
-		]);
169
-		$calendars = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER);
170
-		$this->assertEquals(1, count($calendars));
171
-		$this->assertEquals(self::UNIT_TEST_USER, $calendars[0]['principaluri']);
172
-		/** @var SupportedCalendarComponentSet $components */
173
-		$components = $calendars[0]['{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set'];
174
-		$this->assertEquals(['VEVENT','VTODO','VJOURNAL'], $components->getValue());
175
-		$color = $calendars[0]['{http://apple.com/ns/ical/}calendar-color'];
176
-		$this->assertEquals('#1C4587FF', $color);
177
-		$this->assertEquals('Example', $calendars[0]['uri']);
178
-		$this->assertEquals('Example', $calendars[0]['{DAV:}displayname']);
179
-		return (int)$calendars[0]['id'];
180
-	}
166
+        $this->backend->createCalendar(self::UNIT_TEST_USER, 'Example', [
167
+            '{http://apple.com/ns/ical/}calendar-color' => '#1C4587FF'
168
+        ]);
169
+        $calendars = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER);
170
+        $this->assertEquals(1, count($calendars));
171
+        $this->assertEquals(self::UNIT_TEST_USER, $calendars[0]['principaluri']);
172
+        /** @var SupportedCalendarComponentSet $components */
173
+        $components = $calendars[0]['{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set'];
174
+        $this->assertEquals(['VEVENT','VTODO','VJOURNAL'], $components->getValue());
175
+        $color = $calendars[0]['{http://apple.com/ns/ical/}calendar-color'];
176
+        $this->assertEquals('#1C4587FF', $color);
177
+        $this->assertEquals('Example', $calendars[0]['uri']);
178
+        $this->assertEquals('Example', $calendars[0]['{DAV:}displayname']);
179
+        return (int)$calendars[0]['id'];
180
+    }
181 181
 
182
-	protected function createTestSubscription() {
183
-		$this->backend->createSubscription(self::UNIT_TEST_USER, 'Example', [
184
-			'{http://apple.com/ns/ical/}calendar-color' => '#1C4587FF',
185
-			'{http://calendarserver.org/ns/}source' => new Href(['foo']),
186
-		]);
187
-		$calendars = $this->backend->getSubscriptionsForUser(self::UNIT_TEST_USER);
188
-		$this->assertEquals(1, count($calendars));
189
-		$this->assertEquals(self::UNIT_TEST_USER, $calendars[0]['principaluri']);
190
-		$this->assertEquals('Example', $calendars[0]['uri']);
191
-		$calendarId = $calendars[0]['id'];
182
+    protected function createTestSubscription() {
183
+        $this->backend->createSubscription(self::UNIT_TEST_USER, 'Example', [
184
+            '{http://apple.com/ns/ical/}calendar-color' => '#1C4587FF',
185
+            '{http://calendarserver.org/ns/}source' => new Href(['foo']),
186
+        ]);
187
+        $calendars = $this->backend->getSubscriptionsForUser(self::UNIT_TEST_USER);
188
+        $this->assertEquals(1, count($calendars));
189
+        $this->assertEquals(self::UNIT_TEST_USER, $calendars[0]['principaluri']);
190
+        $this->assertEquals('Example', $calendars[0]['uri']);
191
+        $calendarId = $calendars[0]['id'];
192 192
 
193
-		return $calendarId;
194
-	}
193
+        return $calendarId;
194
+    }
195 195
 
196
-	protected function createEvent($calendarId, $start = '20130912T130000Z', $end = '20130912T140000Z') {
197
-		$randomPart = self::getUniqueID();
196
+    protected function createEvent($calendarId, $start = '20130912T130000Z', $end = '20130912T140000Z') {
197
+        $randomPart = self::getUniqueID();
198 198
 
199
-		$calData = <<<EOD
199
+        $calData = <<<EOD
200 200
 BEGIN:VCALENDAR
201 201
 VERSION:2.0
202 202
 PRODID:ownCloud Calendar
@@ -212,20 +212,20 @@  discard block
 block discarded – undo
212 212
 END:VEVENT
213 213
 END:VCALENDAR
214 214
 EOD;
215
-		$uri0 = $this->getUniqueID('event');
215
+        $uri0 = $this->getUniqueID('event');
216 216
 
217
-		$this->dispatcher->expects(self::atLeastOnce())
218
-			->method('dispatchTyped');
217
+        $this->dispatcher->expects(self::atLeastOnce())
218
+            ->method('dispatchTyped');
219 219
 
220
-		$this->backend->createCalendarObject($calendarId, $uri0, $calData);
220
+        $this->backend->createCalendarObject($calendarId, $uri0, $calData);
221 221
 
222
-		return $uri0;
223
-	}
222
+        return $uri0;
223
+    }
224 224
 
225
-	protected function modifyEvent($calendarId, $objectId, $start = '20130912T130000Z', $end = '20130912T140000Z') {
226
-		$randomPart = self::getUniqueID();
225
+    protected function modifyEvent($calendarId, $objectId, $start = '20130912T130000Z', $end = '20130912T140000Z') {
226
+        $randomPart = self::getUniqueID();
227 227
 
228
-		$calData = <<<EOD
228
+        $calData = <<<EOD
229 229
 BEGIN:VCALENDAR
230 230
 VERSION:2.0
231 231
 PRODID:ownCloud Calendar
@@ -242,38 +242,38 @@  discard block
 block discarded – undo
242 242
 END:VCALENDAR
243 243
 EOD;
244 244
 
245
-		$this->backend->updateCalendarObject($calendarId, $objectId, $calData);
246
-	}
245
+        $this->backend->updateCalendarObject($calendarId, $objectId, $calData);
246
+    }
247 247
 
248
-	protected function deleteEvent($calendarId, $objectId) {
249
-		$this->backend->deleteCalendarObject($calendarId, $objectId);
250
-	}
248
+    protected function deleteEvent($calendarId, $objectId) {
249
+        $this->backend->deleteCalendarObject($calendarId, $objectId);
250
+    }
251 251
 
252
-	protected function assertAcl($principal, $privilege, $acl) {
253
-		foreach ($acl as $a) {
254
-			if ($a['principal'] === $principal && $a['privilege'] === $privilege) {
255
-				$this->addToAssertionCount(1);
256
-				return;
257
-			}
258
-		}
259
-		$this->fail("ACL does not contain $principal / $privilege");
260
-	}
252
+    protected function assertAcl($principal, $privilege, $acl) {
253
+        foreach ($acl as $a) {
254
+            if ($a['principal'] === $principal && $a['privilege'] === $privilege) {
255
+                $this->addToAssertionCount(1);
256
+                return;
257
+            }
258
+        }
259
+        $this->fail("ACL does not contain $principal / $privilege");
260
+    }
261 261
 
262
-	protected function assertNotAcl($principal, $privilege, $acl) {
263
-		foreach ($acl as $a) {
264
-			if ($a['principal'] === $principal && $a['privilege'] === $privilege) {
265
-				$this->fail("ACL contains $principal / $privilege");
266
-				return;
267
-			}
268
-		}
269
-		$this->addToAssertionCount(1);
270
-	}
262
+    protected function assertNotAcl($principal, $privilege, $acl) {
263
+        foreach ($acl as $a) {
264
+            if ($a['principal'] === $principal && $a['privilege'] === $privilege) {
265
+                $this->fail("ACL contains $principal / $privilege");
266
+                return;
267
+            }
268
+        }
269
+        $this->addToAssertionCount(1);
270
+    }
271 271
 
272
-	protected function assertAccess($shouldHaveAcl, $principal, $privilege, $acl) {
273
-		if ($shouldHaveAcl) {
274
-			$this->assertAcl($principal, $privilege, $acl);
275
-		} else {
276
-			$this->assertNotAcl($principal, $privilege, $acl);
277
-		}
278
-	}
272
+    protected function assertAccess($shouldHaveAcl, $principal, $privilege, $acl) {
273
+        if ($shouldHaveAcl) {
274
+            $this->assertAcl($principal, $privilege, $acl);
275
+        } else {
276
+            $this->assertNotAcl($principal, $privilege, $acl);
277
+        }
278
+    }
279 279
 }
Please login to merge, or discard this patch.
apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php 1 patch
Indentation   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -34,117 +34,117 @@
 block discarded – undo
34 34
  * @package OCA\DAV\Tests\unit\CalDAV
35 35
  */
36 36
 class PublicCalendarRootTest extends TestCase {
37
-	public const UNIT_TEST_USER = '';
38
-	private CalDavBackend $backend;
39
-	private PublicCalendarRoot $publicCalendarRoot;
40
-	private IL10N&MockObject $l10n;
41
-	private Principal&MockObject $principal;
42
-	protected IUserManager&MockObject $userManager;
43
-	protected IGroupManager&MockObject $groupManager;
44
-	protected IConfig&MockObject $config;
45
-	private ISecureRandom $random;
46
-	private LoggerInterface&MockObject $logger;
47
-	protected ICacheFactory&MockObject $cacheFactory;
48
-
49
-	protected FederatedCalendarMapper&MockObject $federatedCalendarMapper;
50
-
51
-	protected function setUp(): void {
52
-		parent::setUp();
53
-
54
-		$db = Server::get(IDBConnection::class);
55
-		$this->principal = $this->createMock('OCA\DAV\Connector\Sabre\Principal');
56
-		$this->userManager = $this->createMock(IUserManager::class);
57
-		$this->groupManager = $this->createMock(IGroupManager::class);
58
-		$this->random = Server::get(ISecureRandom::class);
59
-		$this->logger = $this->createMock(LoggerInterface::class);
60
-		$this->federatedCalendarMapper = $this->createMock(FederatedCalendarMapper::class);
61
-		$this->cacheFactory = $this->createMock(ICacheFactory::class);
62
-		$dispatcher = $this->createMock(IEventDispatcher::class);
63
-		$config = $this->createMock(IConfig::class);
64
-		$sharingBackend = $this->createMock(\OCA\DAV\CalDAV\Sharing\Backend::class);
65
-
66
-		$this->principal->expects($this->any())->method('getGroupMembership')
67
-			->withAnyParameters()
68
-			->willReturn([]);
69
-
70
-		$this->principal->expects($this->any())->method('getCircleMembership')
71
-			->withAnyParameters()
72
-			->willReturn([]);
73
-
74
-		$this->backend = new CalDavBackend(
75
-			$db,
76
-			$this->principal,
77
-			$this->userManager,
78
-			$this->random,
79
-			$this->logger,
80
-			$dispatcher,
81
-			$config,
82
-			$sharingBackend,
83
-			$this->federatedCalendarMapper,
84
-			$this->cacheFactory,
85
-			false,
86
-		);
87
-		$this->l10n = $this->createMock(IL10N::class);
88
-		$this->config = $this->createMock(IConfig::class);
89
-
90
-		$this->publicCalendarRoot = new PublicCalendarRoot($this->backend,
91
-			$this->l10n, $this->config, $this->logger);
92
-	}
93
-
94
-	protected function tearDown(): void {
95
-		parent::tearDown();
96
-
97
-		if (is_null($this->backend)) {
98
-			return;
99
-		}
100
-		$this->principal->expects($this->any())->method('getGroupMembership')
101
-			->withAnyParameters()
102
-			->willReturn([]);
103
-
104
-		$this->principal->expects($this->any())->method('getCircleMembership')
105
-			->withAnyParameters()
106
-			->willReturn([]);
107
-
108
-		$books = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER);
109
-		foreach ($books as $book) {
110
-			$this->backend->deleteCalendar($book['id'], true);
111
-		}
112
-	}
113
-
114
-	public function testGetName(): void {
115
-		$name = $this->publicCalendarRoot->getName();
116
-		$this->assertEquals('public-calendars', $name);
117
-	}
118
-
119
-	public function testGetChild(): void {
120
-		$calendar = $this->createPublicCalendar();
121
-
122
-		$publicCalendars = $this->backend->getPublicCalendars();
123
-		$this->assertEquals(1, count($publicCalendars));
124
-		$this->assertEquals(true, $publicCalendars[0]['{http://owncloud.org/ns}public']);
125
-
126
-		$publicCalendarURI = $publicCalendars[0]['uri'];
127
-
128
-		$calendarResult = $this->publicCalendarRoot->getChild($publicCalendarURI);
129
-		$this->assertEquals($calendar, $calendarResult);
130
-	}
131
-
132
-	public function testGetChildren(): void {
133
-		$this->createPublicCalendar();
134
-		$calendarResults = $this->publicCalendarRoot->getChildren();
135
-		$this->assertSame([], $calendarResults);
136
-	}
137
-
138
-	protected function createPublicCalendar(): Calendar {
139
-		$this->backend->createCalendar(self::UNIT_TEST_USER, 'Example', []);
140
-
141
-		$calendarInfo = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER)[0];
142
-		$calendar = new PublicCalendar($this->backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
143
-		$publicUri = $calendar->setPublishStatus(true);
144
-
145
-		$calendarInfo = $this->backend->getPublicCalendar($publicUri);
146
-		$calendar = new PublicCalendar($this->backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
147
-
148
-		return $calendar;
149
-	}
37
+    public const UNIT_TEST_USER = '';
38
+    private CalDavBackend $backend;
39
+    private PublicCalendarRoot $publicCalendarRoot;
40
+    private IL10N&MockObject $l10n;
41
+    private Principal&MockObject $principal;
42
+    protected IUserManager&MockObject $userManager;
43
+    protected IGroupManager&MockObject $groupManager;
44
+    protected IConfig&MockObject $config;
45
+    private ISecureRandom $random;
46
+    private LoggerInterface&MockObject $logger;
47
+    protected ICacheFactory&MockObject $cacheFactory;
48
+
49
+    protected FederatedCalendarMapper&MockObject $federatedCalendarMapper;
50
+
51
+    protected function setUp(): void {
52
+        parent::setUp();
53
+
54
+        $db = Server::get(IDBConnection::class);
55
+        $this->principal = $this->createMock('OCA\DAV\Connector\Sabre\Principal');
56
+        $this->userManager = $this->createMock(IUserManager::class);
57
+        $this->groupManager = $this->createMock(IGroupManager::class);
58
+        $this->random = Server::get(ISecureRandom::class);
59
+        $this->logger = $this->createMock(LoggerInterface::class);
60
+        $this->federatedCalendarMapper = $this->createMock(FederatedCalendarMapper::class);
61
+        $this->cacheFactory = $this->createMock(ICacheFactory::class);
62
+        $dispatcher = $this->createMock(IEventDispatcher::class);
63
+        $config = $this->createMock(IConfig::class);
64
+        $sharingBackend = $this->createMock(\OCA\DAV\CalDAV\Sharing\Backend::class);
65
+
66
+        $this->principal->expects($this->any())->method('getGroupMembership')
67
+            ->withAnyParameters()
68
+            ->willReturn([]);
69
+
70
+        $this->principal->expects($this->any())->method('getCircleMembership')
71
+            ->withAnyParameters()
72
+            ->willReturn([]);
73
+
74
+        $this->backend = new CalDavBackend(
75
+            $db,
76
+            $this->principal,
77
+            $this->userManager,
78
+            $this->random,
79
+            $this->logger,
80
+            $dispatcher,
81
+            $config,
82
+            $sharingBackend,
83
+            $this->federatedCalendarMapper,
84
+            $this->cacheFactory,
85
+            false,
86
+        );
87
+        $this->l10n = $this->createMock(IL10N::class);
88
+        $this->config = $this->createMock(IConfig::class);
89
+
90
+        $this->publicCalendarRoot = new PublicCalendarRoot($this->backend,
91
+            $this->l10n, $this->config, $this->logger);
92
+    }
93
+
94
+    protected function tearDown(): void {
95
+        parent::tearDown();
96
+
97
+        if (is_null($this->backend)) {
98
+            return;
99
+        }
100
+        $this->principal->expects($this->any())->method('getGroupMembership')
101
+            ->withAnyParameters()
102
+            ->willReturn([]);
103
+
104
+        $this->principal->expects($this->any())->method('getCircleMembership')
105
+            ->withAnyParameters()
106
+            ->willReturn([]);
107
+
108
+        $books = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER);
109
+        foreach ($books as $book) {
110
+            $this->backend->deleteCalendar($book['id'], true);
111
+        }
112
+    }
113
+
114
+    public function testGetName(): void {
115
+        $name = $this->publicCalendarRoot->getName();
116
+        $this->assertEquals('public-calendars', $name);
117
+    }
118
+
119
+    public function testGetChild(): void {
120
+        $calendar = $this->createPublicCalendar();
121
+
122
+        $publicCalendars = $this->backend->getPublicCalendars();
123
+        $this->assertEquals(1, count($publicCalendars));
124
+        $this->assertEquals(true, $publicCalendars[0]['{http://owncloud.org/ns}public']);
125
+
126
+        $publicCalendarURI = $publicCalendars[0]['uri'];
127
+
128
+        $calendarResult = $this->publicCalendarRoot->getChild($publicCalendarURI);
129
+        $this->assertEquals($calendar, $calendarResult);
130
+    }
131
+
132
+    public function testGetChildren(): void {
133
+        $this->createPublicCalendar();
134
+        $calendarResults = $this->publicCalendarRoot->getChildren();
135
+        $this->assertSame([], $calendarResults);
136
+    }
137
+
138
+    protected function createPublicCalendar(): Calendar {
139
+        $this->backend->createCalendar(self::UNIT_TEST_USER, 'Example', []);
140
+
141
+        $calendarInfo = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER)[0];
142
+        $calendar = new PublicCalendar($this->backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
143
+        $publicUri = $calendar->setPublishStatus(true);
144
+
145
+        $calendarInfo = $this->backend->getPublicCalendar($publicUri);
146
+        $calendar = new PublicCalendar($this->backend, $calendarInfo, $this->l10n, $this->config, $this->logger);
147
+
148
+        return $calendar;
149
+    }
150 150
 }
Please login to merge, or discard this patch.
apps/dav/appinfo/v1/caldav.php 1 patch
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -38,25 +38,25 @@  discard block
 block discarded – undo
38 38
 use Psr\Log\LoggerInterface;
39 39
 
40 40
 $authBackend = new Auth(
41
-	Server::get(ISession::class),
42
-	Server::get(IUserSession::class),
43
-	Server::get(IRequest::class),
44
-	Server::get(\OC\Authentication\TwoFactorAuth\Manager::class),
45
-	Server::get(IThrottler::class),
46
-	'principals/'
41
+    Server::get(ISession::class),
42
+    Server::get(IUserSession::class),
43
+    Server::get(IRequest::class),
44
+    Server::get(\OC\Authentication\TwoFactorAuth\Manager::class),
45
+    Server::get(IThrottler::class),
46
+    'principals/'
47 47
 );
48 48
 $principalBackend = new Principal(
49
-	Server::get(IUserManager::class),
50
-	Server::get(IGroupManager::class),
51
-	Server::get(IAccountManager::class),
52
-	Server::get(\OCP\Share\IManager::class),
53
-	Server::get(IUserSession::class),
54
-	Server::get(IAppManager::class),
55
-	Server::get(ProxyMapper::class),
56
-	Server::get(KnownUserService::class),
57
-	Server::get(IConfig::class),
58
-	\OC::$server->getL10NFactory(),
59
-	'principals/'
49
+    Server::get(IUserManager::class),
50
+    Server::get(IGroupManager::class),
51
+    Server::get(IAccountManager::class),
52
+    Server::get(\OCP\Share\IManager::class),
53
+    Server::get(IUserSession::class),
54
+    Server::get(IAppManager::class),
55
+    Server::get(ProxyMapper::class),
56
+    Server::get(KnownUserService::class),
57
+    Server::get(IConfig::class),
58
+    \OC::$server->getL10NFactory(),
59
+    'principals/'
60 60
 );
61 61
 $db = Server::get(IDBConnection::class);
62 62
 $userManager = Server::get(IUserManager::class);
@@ -69,17 +69,17 @@  discard block
 block discarded – undo
69 69
 $federatedCalendarFactory = Server::get(FederatedCalendarFactory::class);
70 70
 
71 71
 $calDavBackend = new CalDavBackend(
72
-	$db,
73
-	$principalBackend,
74
-	$userManager,
75
-	$random,
76
-	$logger,
77
-	$dispatcher,
78
-	$config,
79
-	Server::get(\OCA\DAV\CalDAV\Sharing\Backend::class),
80
-	Server::get(FederatedCalendarMapper::class),
81
-	Server::get(\OCP\ICacheFactory::class),
82
-	true
72
+    $db,
73
+    $principalBackend,
74
+    $userManager,
75
+    $random,
76
+    $logger,
77
+    $dispatcher,
78
+    $config,
79
+    Server::get(\OCA\DAV\CalDAV\Sharing\Backend::class),
80
+    Server::get(FederatedCalendarMapper::class),
81
+    Server::get(\OCP\ICacheFactory::class),
82
+    true
83 83
 );
84 84
 
85 85
 $debugging = Server::get(IConfig::class)->getSystemValue('debug', false);
@@ -93,8 +93,8 @@  discard block
 block discarded – undo
93 93
 $addressBookRoot->disableListing = !$debugging; // Disable listing
94 94
 
95 95
 $nodes = [
96
-	$principalCollection,
97
-	$addressBookRoot,
96
+    $principalCollection,
97
+    $addressBookRoot,
98 98
 ];
99 99
 
100 100
 // Fire up server
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 
111 111
 $server->addPlugin(new LegacyDAVACL());
112 112
 if ($debugging) {
113
-	$server->addPlugin(new Sabre\DAV\Browser\Plugin());
113
+    $server->addPlugin(new Sabre\DAV\Browser\Plugin());
114 114
 }
115 115
 
116 116
 $server->addPlugin(new \Sabre\DAV\Sync\Plugin());
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
 $server->addPlugin(new \OCA\DAV\CalDAV\Schedule\Plugin(Server::get(IConfig::class), Server::get(LoggerInterface::class), Server::get(DefaultCalendarValidator::class)));
119 119
 
120 120
 if ($sendInvitations) {
121
-	$server->addPlugin(Server::get(IMipPlugin::class));
121
+    $server->addPlugin(Server::get(IMipPlugin::class));
122 122
 }
123 123
 $server->addPlugin(new ExceptionLoggerPlugin('caldav', $logger));
124 124
 $server->addPlugin(Server::get(RateLimitingPlugin::class));
Please login to merge, or discard this patch.