Completed
Push — master ( ba57f5...06183f )
by John
19:09 queued 16s
created
apps/dav/lib/CardDAV/CardDavBackend.php 1 patch
Indentation   +1425 added lines, -1425 removed lines patch added patch discarded remove patch
@@ -34,1429 +34,1429 @@
 block discarded – undo
34 34
 use Sabre\VObject\Reader;
35 35
 
36 36
 class CardDavBackend implements BackendInterface, SyncSupport {
37
-	use TTransactional;
38
-	public const PERSONAL_ADDRESSBOOK_URI = 'contacts';
39
-	public const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
40
-
41
-	private string $dbCardsTable = 'cards';
42
-	private string $dbCardsPropertiesTable = 'cards_properties';
43
-
44
-	/** @var array properties to index */
45
-	public static array $indexProperties = [
46
-		'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
47
-		'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO',
48
-		'CLOUD', 'X-SOCIALPROFILE'];
49
-
50
-	/**
51
-	 * @var string[] Map of uid => display name
52
-	 */
53
-	protected array $userDisplayNames;
54
-	private array $etagCache = [];
55
-
56
-	public function __construct(
57
-		private IDBConnection $db,
58
-		private Principal $principalBackend,
59
-		private IUserManager $userManager,
60
-		private IEventDispatcher $dispatcher,
61
-		private Sharing\Backend $sharingBackend,
62
-	) {
63
-	}
64
-
65
-	/**
66
-	 * Return the number of address books for a principal
67
-	 *
68
-	 * @param $principalUri
69
-	 * @return int
70
-	 */
71
-	public function getAddressBooksForUserCount($principalUri) {
72
-		$principalUri = $this->convertPrincipal($principalUri, true);
73
-		$query = $this->db->getQueryBuilder();
74
-		$query->select($query->func()->count('*'))
75
-			->from('addressbooks')
76
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
77
-
78
-		$result = $query->executeQuery();
79
-		$column = (int)$result->fetchOne();
80
-		$result->closeCursor();
81
-		return $column;
82
-	}
83
-
84
-	/**
85
-	 * Returns the list of address books for a specific user.
86
-	 *
87
-	 * Every addressbook should have the following properties:
88
-	 *   id - an arbitrary unique id
89
-	 *   uri - the 'basename' part of the url
90
-	 *   principaluri - Same as the passed parameter
91
-	 *
92
-	 * Any additional clark-notation property may be passed besides this. Some
93
-	 * common ones are :
94
-	 *   {DAV:}displayname
95
-	 *   {urn:ietf:params:xml:ns:carddav}addressbook-description
96
-	 *   {http://calendarserver.org/ns/}getctag
97
-	 *
98
-	 * @param string $principalUri
99
-	 * @return array
100
-	 */
101
-	public function getAddressBooksForUser($principalUri) {
102
-		return $this->atomic(function () use ($principalUri) {
103
-			$principalUriOriginal = $principalUri;
104
-			$principalUri = $this->convertPrincipal($principalUri, true);
105
-			$select = $this->db->getQueryBuilder();
106
-			$select->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
107
-				->from('addressbooks')
108
-				->where($select->expr()->eq('principaluri', $select->createNamedParameter($principalUri)));
109
-
110
-			$addressBooks = [];
111
-
112
-			$result = $select->executeQuery();
113
-			while ($row = $result->fetch()) {
114
-				$addressBooks[$row['id']] = [
115
-					'id' => $row['id'],
116
-					'uri' => $row['uri'],
117
-					'principaluri' => $this->convertPrincipal($row['principaluri'], false),
118
-					'{DAV:}displayname' => $row['displayname'],
119
-					'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
120
-					'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
121
-					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
122
-				];
123
-
124
-				$this->addOwnerPrincipal($addressBooks[$row['id']]);
125
-			}
126
-			$result->closeCursor();
127
-
128
-			// query for shared addressbooks
129
-			$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
130
-
131
-			$principals[] = $principalUri;
132
-
133
-			$select = $this->db->getQueryBuilder();
134
-			$subSelect = $this->db->getQueryBuilder();
135
-
136
-			$subSelect->select('id')
137
-				->from('dav_shares', 'd')
138
-				->where($subSelect->expr()->eq('d.access', $select->createNamedParameter(\OCA\DAV\CardDAV\Sharing\Backend::ACCESS_UNSHARED, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
139
-				->andWhere($subSelect->expr()->in('d.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY));
140
-
141
-
142
-			$select->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
143
-				->from('dav_shares', 's')
144
-				->join('s', 'addressbooks', 'a', $select->expr()->eq('s.resourceid', 'a.id'))
145
-				->where($select->expr()->in('s.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY)))
146
-				->andWhere($select->expr()->eq('s.type', $select->createNamedParameter('addressbook', IQueryBuilder::PARAM_STR)))
147
-				->andWhere($select->expr()->notIn('s.id', $select->createFunction($subSelect->getSQL()), IQueryBuilder::PARAM_INT_ARRAY));
148
-			$result = $select->executeQuery();
149
-
150
-			$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
151
-			while ($row = $result->fetch()) {
152
-				if ($row['principaluri'] === $principalUri) {
153
-					continue;
154
-				}
155
-
156
-				$readOnly = (int)$row['access'] === Backend::ACCESS_READ;
157
-				if (isset($addressBooks[$row['id']])) {
158
-					if ($readOnly) {
159
-						// New share can not have more permissions then the old one.
160
-						continue;
161
-					}
162
-					if (isset($addressBooks[$row['id']][$readOnlyPropertyName])
163
-						&& $addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
164
-						// Old share is already read-write, no more permissions can be gained
165
-						continue;
166
-					}
167
-				}
168
-
169
-				[, $name] = \Sabre\Uri\split($row['principaluri']);
170
-				$uri = $row['uri'] . '_shared_by_' . $name;
171
-				$displayName = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? $name ?? '') . ')';
172
-
173
-				$addressBooks[$row['id']] = [
174
-					'id' => $row['id'],
175
-					'uri' => $uri,
176
-					'principaluri' => $principalUriOriginal,
177
-					'{DAV:}displayname' => $displayName,
178
-					'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
179
-					'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
180
-					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
181
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
182
-					$readOnlyPropertyName => $readOnly,
183
-				];
184
-
185
-				$this->addOwnerPrincipal($addressBooks[$row['id']]);
186
-			}
187
-			$result->closeCursor();
188
-
189
-			return array_values($addressBooks);
190
-		}, $this->db);
191
-	}
192
-
193
-	public function getUsersOwnAddressBooks($principalUri) {
194
-		$principalUri = $this->convertPrincipal($principalUri, true);
195
-		$query = $this->db->getQueryBuilder();
196
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
197
-			->from('addressbooks')
198
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
199
-
200
-		$addressBooks = [];
201
-
202
-		$result = $query->executeQuery();
203
-		while ($row = $result->fetch()) {
204
-			$addressBooks[$row['id']] = [
205
-				'id' => $row['id'],
206
-				'uri' => $row['uri'],
207
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
208
-				'{DAV:}displayname' => $row['displayname'],
209
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
210
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
211
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
212
-			];
213
-
214
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
215
-		}
216
-		$result->closeCursor();
217
-
218
-		return array_values($addressBooks);
219
-	}
220
-
221
-	/**
222
-	 * @param int $addressBookId
223
-	 */
224
-	public function getAddressBookById(int $addressBookId): ?array {
225
-		$query = $this->db->getQueryBuilder();
226
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
227
-			->from('addressbooks')
228
-			->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId, IQueryBuilder::PARAM_INT)))
229
-			->executeQuery();
230
-		$row = $result->fetch();
231
-		$result->closeCursor();
232
-		if (!$row) {
233
-			return null;
234
-		}
235
-
236
-		$addressBook = [
237
-			'id' => $row['id'],
238
-			'uri' => $row['uri'],
239
-			'principaluri' => $row['principaluri'],
240
-			'{DAV:}displayname' => $row['displayname'],
241
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
242
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
243
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
244
-		];
245
-
246
-		$this->addOwnerPrincipal($addressBook);
247
-
248
-		return $addressBook;
249
-	}
250
-
251
-	public function getAddressBooksByUri(string $principal, string $addressBookUri): ?array {
252
-		$query = $this->db->getQueryBuilder();
253
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
254
-			->from('addressbooks')
255
-			->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
256
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
257
-			->setMaxResults(1)
258
-			->executeQuery();
259
-
260
-		$row = $result->fetch();
261
-		$result->closeCursor();
262
-		if ($row === false) {
263
-			return null;
264
-		}
265
-
266
-		$addressBook = [
267
-			'id' => $row['id'],
268
-			'uri' => $row['uri'],
269
-			'principaluri' => $row['principaluri'],
270
-			'{DAV:}displayname' => $row['displayname'],
271
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
272
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
273
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
274
-
275
-		];
276
-
277
-		// system address books are always read only
278
-		if ($principal === 'principals/system/system') {
279
-			$addressBook['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal'] = $row['principaluri'];
280
-			$addressBook['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only'] = true;
281
-		}
282
-
283
-		$this->addOwnerPrincipal($addressBook);
284
-
285
-		return $addressBook;
286
-	}
287
-
288
-	/**
289
-	 * Updates properties for an address book.
290
-	 *
291
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
292
-	 * To do the actual updates, you must tell this object which properties
293
-	 * you're going to process with the handle() method.
294
-	 *
295
-	 * Calling the handle method is like telling the PropPatch object "I
296
-	 * promise I can handle updating this property".
297
-	 *
298
-	 * Read the PropPatch documentation for more info and examples.
299
-	 *
300
-	 * @param string $addressBookId
301
-	 * @param \Sabre\DAV\PropPatch $propPatch
302
-	 * @return void
303
-	 */
304
-	public function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
305
-		$supportedProperties = [
306
-			'{DAV:}displayname',
307
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
308
-		];
309
-
310
-		$propPatch->handle($supportedProperties, function ($mutations) use ($addressBookId) {
311
-			$updates = [];
312
-			foreach ($mutations as $property => $newValue) {
313
-				switch ($property) {
314
-					case '{DAV:}displayname':
315
-						$updates['displayname'] = $newValue;
316
-						break;
317
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description':
318
-						$updates['description'] = $newValue;
319
-						break;
320
-				}
321
-			}
322
-			[$addressBookRow, $shares] = $this->atomic(function () use ($addressBookId, $updates) {
323
-				$query = $this->db->getQueryBuilder();
324
-				$query->update('addressbooks');
325
-
326
-				foreach ($updates as $key => $value) {
327
-					$query->set($key, $query->createNamedParameter($value));
328
-				}
329
-				$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
330
-					->executeStatement();
331
-
332
-				$this->addChange($addressBookId, '', 2);
333
-
334
-				$addressBookRow = $this->getAddressBookById((int)$addressBookId);
335
-				$shares = $this->getShares((int)$addressBookId);
336
-				return [$addressBookRow, $shares];
337
-			}, $this->db);
338
-
339
-			$this->dispatcher->dispatchTyped(new AddressBookUpdatedEvent((int)$addressBookId, $addressBookRow, $shares, $mutations));
340
-
341
-			return true;
342
-		});
343
-	}
344
-
345
-	/**
346
-	 * Creates a new address book
347
-	 *
348
-	 * @param string $principalUri
349
-	 * @param string $url Just the 'basename' of the url.
350
-	 * @param array $properties
351
-	 * @return int
352
-	 * @throws BadRequest
353
-	 * @throws Exception
354
-	 */
355
-	public function createAddressBook($principalUri, $url, array $properties) {
356
-		if (strlen($url) > 255) {
357
-			throw new BadRequest('URI too long. Address book not created');
358
-		}
359
-
360
-		$values = [
361
-			'displayname' => null,
362
-			'description' => null,
363
-			'principaluri' => $principalUri,
364
-			'uri' => $url,
365
-			'synctoken' => 1
366
-		];
367
-
368
-		foreach ($properties as $property => $newValue) {
369
-			switch ($property) {
370
-				case '{DAV:}displayname':
371
-					$values['displayname'] = $newValue;
372
-					break;
373
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description':
374
-					$values['description'] = $newValue;
375
-					break;
376
-				default:
377
-					throw new BadRequest('Unknown property: ' . $property);
378
-			}
379
-		}
380
-
381
-		// Fallback to make sure the displayname is set. Some clients may refuse
382
-		// to work with addressbooks not having a displayname.
383
-		if (is_null($values['displayname'])) {
384
-			$values['displayname'] = $url;
385
-		}
386
-
387
-		[$addressBookId, $addressBookRow] = $this->atomic(function () use ($values) {
388
-			$query = $this->db->getQueryBuilder();
389
-			$query->insert('addressbooks')
390
-				->values([
391
-					'uri' => $query->createParameter('uri'),
392
-					'displayname' => $query->createParameter('displayname'),
393
-					'description' => $query->createParameter('description'),
394
-					'principaluri' => $query->createParameter('principaluri'),
395
-					'synctoken' => $query->createParameter('synctoken'),
396
-				])
397
-				->setParameters($values)
398
-				->executeStatement();
399
-
400
-			$addressBookId = $query->getLastInsertId();
401
-			return [
402
-				$addressBookId,
403
-				$this->getAddressBookById($addressBookId),
404
-			];
405
-		}, $this->db);
406
-
407
-		$this->dispatcher->dispatchTyped(new AddressBookCreatedEvent($addressBookId, $addressBookRow));
408
-
409
-		return $addressBookId;
410
-	}
411
-
412
-	/**
413
-	 * Deletes an entire addressbook and all its contents
414
-	 *
415
-	 * @param mixed $addressBookId
416
-	 * @return void
417
-	 */
418
-	public function deleteAddressBook($addressBookId) {
419
-		$this->atomic(function () use ($addressBookId): void {
420
-			$addressBookId = (int)$addressBookId;
421
-			$addressBookData = $this->getAddressBookById($addressBookId);
422
-			$shares = $this->getShares($addressBookId);
423
-
424
-			$query = $this->db->getQueryBuilder();
425
-			$query->delete($this->dbCardsTable)
426
-				->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
427
-				->setParameter('addressbookid', $addressBookId, IQueryBuilder::PARAM_INT)
428
-				->executeStatement();
429
-
430
-			$query = $this->db->getQueryBuilder();
431
-			$query->delete('addressbookchanges')
432
-				->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
433
-				->setParameter('addressbookid', $addressBookId, IQueryBuilder::PARAM_INT)
434
-				->executeStatement();
435
-
436
-			$query = $this->db->getQueryBuilder();
437
-			$query->delete('addressbooks')
438
-				->where($query->expr()->eq('id', $query->createParameter('id')))
439
-				->setParameter('id', $addressBookId, IQueryBuilder::PARAM_INT)
440
-				->executeStatement();
441
-
442
-			$this->sharingBackend->deleteAllShares($addressBookId);
443
-
444
-			$query = $this->db->getQueryBuilder();
445
-			$query->delete($this->dbCardsPropertiesTable)
446
-				->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId, IQueryBuilder::PARAM_INT)))
447
-				->executeStatement();
448
-
449
-			if ($addressBookData) {
450
-				$this->dispatcher->dispatchTyped(new AddressBookDeletedEvent($addressBookId, $addressBookData, $shares));
451
-			}
452
-		}, $this->db);
453
-	}
454
-
455
-	/**
456
-	 * Returns all cards for a specific addressbook id.
457
-	 *
458
-	 * This method should return the following properties for each card:
459
-	 *   * carddata - raw vcard data
460
-	 *   * uri - Some unique url
461
-	 *   * lastmodified - A unix timestamp
462
-	 *
463
-	 * It's recommended to also return the following properties:
464
-	 *   * etag - A unique etag. This must change every time the card changes.
465
-	 *   * size - The size of the card in bytes.
466
-	 *
467
-	 * If these last two properties are provided, less time will be spent
468
-	 * calculating them. If they are specified, you can also omit carddata.
469
-	 * This may speed up certain requests, especially with large cards.
470
-	 *
471
-	 * @param mixed $addressbookId
472
-	 * @return array
473
-	 */
474
-	public function getCards($addressbookId) {
475
-		$query = $this->db->getQueryBuilder();
476
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
477
-			->from($this->dbCardsTable)
478
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressbookId)));
479
-
480
-		$cards = [];
481
-
482
-		$result = $query->executeQuery();
483
-		while ($row = $result->fetch()) {
484
-			$row['etag'] = '"' . $row['etag'] . '"';
485
-
486
-			$modified = false;
487
-			$row['carddata'] = $this->readBlob($row['carddata'], $modified);
488
-			if ($modified) {
489
-				$row['size'] = strlen($row['carddata']);
490
-			}
491
-
492
-			$cards[] = $row;
493
-		}
494
-		$result->closeCursor();
495
-
496
-		return $cards;
497
-	}
498
-
499
-	/**
500
-	 * Returns a specific card.
501
-	 *
502
-	 * The same set of properties must be returned as with getCards. The only
503
-	 * exception is that 'carddata' is absolutely required.
504
-	 *
505
-	 * If the card does not exist, you must return false.
506
-	 *
507
-	 * @param mixed $addressBookId
508
-	 * @param string $cardUri
509
-	 * @return array
510
-	 */
511
-	public function getCard($addressBookId, $cardUri) {
512
-		$query = $this->db->getQueryBuilder();
513
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
514
-			->from($this->dbCardsTable)
515
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
516
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
517
-			->setMaxResults(1);
518
-
519
-		$result = $query->executeQuery();
520
-		$row = $result->fetch();
521
-		if (!$row) {
522
-			return false;
523
-		}
524
-		$row['etag'] = '"' . $row['etag'] . '"';
525
-
526
-		$modified = false;
527
-		$row['carddata'] = $this->readBlob($row['carddata'], $modified);
528
-		if ($modified) {
529
-			$row['size'] = strlen($row['carddata']);
530
-		}
531
-
532
-		return $row;
533
-	}
534
-
535
-	/**
536
-	 * Returns a list of cards.
537
-	 *
538
-	 * This method should work identical to getCard, but instead return all the
539
-	 * cards in the list as an array.
540
-	 *
541
-	 * If the backend supports this, it may allow for some speed-ups.
542
-	 *
543
-	 * @param mixed $addressBookId
544
-	 * @param array $uris
545
-	 * @return array
546
-	 */
547
-	public function getMultipleCards($addressBookId, array $uris) {
548
-		if (empty($uris)) {
549
-			return [];
550
-		}
551
-
552
-		$chunks = array_chunk($uris, 100);
553
-		$cards = [];
554
-
555
-		$query = $this->db->getQueryBuilder();
556
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
557
-			->from($this->dbCardsTable)
558
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
559
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
560
-
561
-		foreach ($chunks as $uris) {
562
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
563
-			$result = $query->executeQuery();
564
-
565
-			while ($row = $result->fetch()) {
566
-				$row['etag'] = '"' . $row['etag'] . '"';
567
-
568
-				$modified = false;
569
-				$row['carddata'] = $this->readBlob($row['carddata'], $modified);
570
-				if ($modified) {
571
-					$row['size'] = strlen($row['carddata']);
572
-				}
573
-
574
-				$cards[] = $row;
575
-			}
576
-			$result->closeCursor();
577
-		}
578
-		return $cards;
579
-	}
580
-
581
-	/**
582
-	 * Creates a new card.
583
-	 *
584
-	 * The addressbook id will be passed as the first argument. This is the
585
-	 * same id as it is returned from the getAddressBooksForUser method.
586
-	 *
587
-	 * The cardUri is a base uri, and doesn't include the full path. The
588
-	 * cardData argument is the vcard body, and is passed as a string.
589
-	 *
590
-	 * It is possible to return an ETag from this method. This ETag is for the
591
-	 * newly created resource, and must be enclosed with double quotes (that
592
-	 * is, the string itself must contain the double quotes).
593
-	 *
594
-	 * You should only return the ETag if you store the carddata as-is. If a
595
-	 * subsequent GET request on the same card does not have the same body,
596
-	 * byte-by-byte and you did return an ETag here, clients tend to get
597
-	 * confused.
598
-	 *
599
-	 * If you don't return an ETag, you can just return null.
600
-	 *
601
-	 * @param mixed $addressBookId
602
-	 * @param string $cardUri
603
-	 * @param string $cardData
604
-	 * @param bool $checkAlreadyExists
605
-	 * @return string
606
-	 */
607
-	public function createCard($addressBookId, $cardUri, $cardData, bool $checkAlreadyExists = true) {
608
-		$etag = md5($cardData);
609
-		$uid = $this->getUID($cardData);
610
-		return $this->atomic(function () use ($addressBookId, $cardUri, $cardData, $checkAlreadyExists, $etag, $uid) {
611
-			if ($checkAlreadyExists) {
612
-				$q = $this->db->getQueryBuilder();
613
-				$q->select('uid')
614
-					->from($this->dbCardsTable)
615
-					->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId)))
616
-					->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
617
-					->setMaxResults(1);
618
-				$result = $q->executeQuery();
619
-				$count = (bool)$result->fetchOne();
620
-				$result->closeCursor();
621
-				if ($count) {
622
-					throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
623
-				}
624
-			}
625
-
626
-			$query = $this->db->getQueryBuilder();
627
-			$query->insert('cards')
628
-				->values([
629
-					'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
630
-					'uri' => $query->createNamedParameter($cardUri),
631
-					'lastmodified' => $query->createNamedParameter(time()),
632
-					'addressbookid' => $query->createNamedParameter($addressBookId),
633
-					'size' => $query->createNamedParameter(strlen($cardData)),
634
-					'etag' => $query->createNamedParameter($etag),
635
-					'uid' => $query->createNamedParameter($uid),
636
-				])
637
-				->executeStatement();
638
-
639
-			$etagCacheKey = "$addressBookId#$cardUri";
640
-			$this->etagCache[$etagCacheKey] = $etag;
641
-
642
-			$this->addChange($addressBookId, $cardUri, 1);
643
-			$this->updateProperties($addressBookId, $cardUri, $cardData);
644
-
645
-			$addressBookData = $this->getAddressBookById($addressBookId);
646
-			$shares = $this->getShares($addressBookId);
647
-			$objectRow = $this->getCard($addressBookId, $cardUri);
648
-			$this->dispatcher->dispatchTyped(new CardCreatedEvent($addressBookId, $addressBookData, $shares, $objectRow));
649
-
650
-			return '"' . $etag . '"';
651
-		}, $this->db);
652
-	}
653
-
654
-	/**
655
-	 * Updates a card.
656
-	 *
657
-	 * The addressbook id will be passed as the first argument. This is the
658
-	 * same id as it is returned from the getAddressBooksForUser method.
659
-	 *
660
-	 * The cardUri is a base uri, and doesn't include the full path. The
661
-	 * cardData argument is the vcard body, and is passed as a string.
662
-	 *
663
-	 * It is possible to return an ETag from this method. This ETag should
664
-	 * match that of the updated resource, and must be enclosed with double
665
-	 * quotes (that is: the string itself must contain the actual quotes).
666
-	 *
667
-	 * You should only return the ETag if you store the carddata as-is. If a
668
-	 * subsequent GET request on the same card does not have the same body,
669
-	 * byte-by-byte and you did return an ETag here, clients tend to get
670
-	 * confused.
671
-	 *
672
-	 * If you don't return an ETag, you can just return null.
673
-	 *
674
-	 * @param mixed $addressBookId
675
-	 * @param string $cardUri
676
-	 * @param string $cardData
677
-	 * @return string
678
-	 */
679
-	public function updateCard($addressBookId, $cardUri, $cardData) {
680
-		$uid = $this->getUID($cardData);
681
-		$etag = md5($cardData);
682
-
683
-		return $this->atomic(function () use ($addressBookId, $cardUri, $cardData, $uid, $etag) {
684
-			$query = $this->db->getQueryBuilder();
685
-
686
-			// check for recently stored etag and stop if it is the same
687
-			$etagCacheKey = "$addressBookId#$cardUri";
688
-			if (isset($this->etagCache[$etagCacheKey]) && $this->etagCache[$etagCacheKey] === $etag) {
689
-				return '"' . $etag . '"';
690
-			}
691
-
692
-			$query->update($this->dbCardsTable)
693
-				->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
694
-				->set('lastmodified', $query->createNamedParameter(time()))
695
-				->set('size', $query->createNamedParameter(strlen($cardData)))
696
-				->set('etag', $query->createNamedParameter($etag))
697
-				->set('uid', $query->createNamedParameter($uid))
698
-				->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
699
-				->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
700
-				->executeStatement();
701
-
702
-			$this->etagCache[$etagCacheKey] = $etag;
703
-
704
-			$this->addChange($addressBookId, $cardUri, 2);
705
-			$this->updateProperties($addressBookId, $cardUri, $cardData);
706
-
707
-			$addressBookData = $this->getAddressBookById($addressBookId);
708
-			$shares = $this->getShares($addressBookId);
709
-			$objectRow = $this->getCard($addressBookId, $cardUri);
710
-			$this->dispatcher->dispatchTyped(new CardUpdatedEvent($addressBookId, $addressBookData, $shares, $objectRow));
711
-			return '"' . $etag . '"';
712
-		}, $this->db);
713
-	}
714
-
715
-	/**
716
-	 * @throws Exception
717
-	 */
718
-	public function moveCard(int $sourceAddressBookId, int $targetAddressBookId, string $cardUri, string $oldPrincipalUri): bool {
719
-		return $this->atomic(function () use ($sourceAddressBookId, $targetAddressBookId, $cardUri, $oldPrincipalUri) {
720
-			$card = $this->getCard($sourceAddressBookId, $cardUri);
721
-			if (empty($card)) {
722
-				return false;
723
-			}
724
-
725
-			$query = $this->db->getQueryBuilder();
726
-			$query->update('cards')
727
-				->set('addressbookid', $query->createNamedParameter($targetAddressBookId, IQueryBuilder::PARAM_INT))
728
-				->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri, IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR))
729
-				->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($sourceAddressBookId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
730
-				->executeStatement();
731
-
732
-			$this->purgeProperties($sourceAddressBookId, (int)$card['id']);
733
-			$this->updateProperties($sourceAddressBookId, $card['uri'], $card['carddata']);
734
-
735
-			$this->addChange($sourceAddressBookId, $card['uri'], 3);
736
-			$this->addChange($targetAddressBookId, $card['uri'], 1);
737
-
738
-			$card = $this->getCard($targetAddressBookId, $cardUri);
739
-			// Card wasn't found - possibly because it was deleted in the meantime by a different client
740
-			if (empty($card)) {
741
-				return false;
742
-			}
743
-
744
-			$targetAddressBookRow = $this->getAddressBookById($targetAddressBookId);
745
-			// the address book this card is being moved to does not exist any longer
746
-			if (empty($targetAddressBookRow)) {
747
-				return false;
748
-			}
749
-
750
-			$sourceShares = $this->getShares($sourceAddressBookId);
751
-			$targetShares = $this->getShares($targetAddressBookId);
752
-			$sourceAddressBookRow = $this->getAddressBookById($sourceAddressBookId);
753
-			$this->dispatcher->dispatchTyped(new CardMovedEvent($sourceAddressBookId, $sourceAddressBookRow, $targetAddressBookId, $targetAddressBookRow, $sourceShares, $targetShares, $card));
754
-			return true;
755
-		}, $this->db);
756
-	}
757
-
758
-	/**
759
-	 * Deletes a card
760
-	 *
761
-	 * @param mixed $addressBookId
762
-	 * @param string $cardUri
763
-	 * @return bool
764
-	 */
765
-	public function deleteCard($addressBookId, $cardUri) {
766
-		return $this->atomic(function () use ($addressBookId, $cardUri) {
767
-			$addressBookData = $this->getAddressBookById($addressBookId);
768
-			$shares = $this->getShares($addressBookId);
769
-			$objectRow = $this->getCard($addressBookId, $cardUri);
770
-
771
-			try {
772
-				$cardId = $this->getCardId($addressBookId, $cardUri);
773
-			} catch (\InvalidArgumentException $e) {
774
-				$cardId = null;
775
-			}
776
-			$query = $this->db->getQueryBuilder();
777
-			$ret = $query->delete($this->dbCardsTable)
778
-				->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
779
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
780
-				->executeStatement();
781
-
782
-			$this->addChange($addressBookId, $cardUri, 3);
783
-
784
-			if ($ret === 1) {
785
-				if ($cardId !== null) {
786
-					$this->dispatcher->dispatchTyped(new CardDeletedEvent($addressBookId, $addressBookData, $shares, $objectRow));
787
-					$this->purgeProperties($addressBookId, $cardId);
788
-				}
789
-				return true;
790
-			}
791
-
792
-			return false;
793
-		}, $this->db);
794
-	}
795
-
796
-	/**
797
-	 * The getChanges method returns all the changes that have happened, since
798
-	 * the specified syncToken in the specified address book.
799
-	 *
800
-	 * This function should return an array, such as the following:
801
-	 *
802
-	 * [
803
-	 *   'syncToken' => 'The current synctoken',
804
-	 *   'added'   => [
805
-	 *      'new.txt',
806
-	 *   ],
807
-	 *   'modified'   => [
808
-	 *      'modified.txt',
809
-	 *   ],
810
-	 *   'deleted' => [
811
-	 *      'foo.php.bak',
812
-	 *      'old.txt'
813
-	 *   ]
814
-	 * ];
815
-	 *
816
-	 * The returned syncToken property should reflect the *current* syncToken
817
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
818
-	 * property. This is needed here too, to ensure the operation is atomic.
819
-	 *
820
-	 * If the $syncToken argument is specified as null, this is an initial
821
-	 * sync, and all members should be reported.
822
-	 *
823
-	 * The modified property is an array of nodenames that have changed since
824
-	 * the last token.
825
-	 *
826
-	 * The deleted property is an array with nodenames, that have been deleted
827
-	 * from collection.
828
-	 *
829
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
830
-	 * 1, you only have to report changes that happened only directly in
831
-	 * immediate descendants. If it's 2, it should also include changes from
832
-	 * the nodes below the child collections. (grandchildren)
833
-	 *
834
-	 * The $limit argument allows a client to specify how many results should
835
-	 * be returned at most. If the limit is not specified, it should be treated
836
-	 * as infinite.
837
-	 *
838
-	 * If the limit (infinite or not) is higher than you're willing to return,
839
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
840
-	 *
841
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
842
-	 * return null.
843
-	 *
844
-	 * The limit is 'suggestive'. You are free to ignore it.
845
-	 *
846
-	 * @param string $addressBookId
847
-	 * @param string $syncToken
848
-	 * @param int $syncLevel
849
-	 * @param int|null $limit
850
-	 * @return array
851
-	 */
852
-	public function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
853
-		// Current synctoken
854
-		return $this->atomic(function () use ($addressBookId, $syncToken, $syncLevel, $limit) {
855
-			$qb = $this->db->getQueryBuilder();
856
-			$qb->select('synctoken')
857
-				->from('addressbooks')
858
-				->where(
859
-					$qb->expr()->eq('id', $qb->createNamedParameter($addressBookId))
860
-				);
861
-			$stmt = $qb->executeQuery();
862
-			$currentToken = $stmt->fetchOne();
863
-			$stmt->closeCursor();
864
-
865
-			if (is_null($currentToken)) {
866
-				return [];
867
-			}
868
-
869
-			$result = [
870
-				'syncToken' => $currentToken,
871
-				'added' => [],
872
-				'modified' => [],
873
-				'deleted' => [],
874
-			];
875
-
876
-			if ($syncToken) {
877
-				$qb = $this->db->getQueryBuilder();
878
-				$qb->select('uri', 'operation')
879
-					->from('addressbookchanges')
880
-					->where(
881
-						$qb->expr()->andX(
882
-							$qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)),
883
-							$qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)),
884
-							$qb->expr()->eq('addressbookid', $qb->createNamedParameter($addressBookId))
885
-						)
886
-					)->orderBy('synctoken');
887
-
888
-				if (is_int($limit) && $limit > 0) {
889
-					$qb->setMaxResults($limit);
890
-				}
891
-
892
-				// Fetching all changes
893
-				$stmt = $qb->executeQuery();
894
-
895
-				$changes = [];
896
-
897
-				// This loop ensures that any duplicates are overwritten, only the
898
-				// last change on a node is relevant.
899
-				while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
900
-					$changes[$row['uri']] = $row['operation'];
901
-				}
902
-				$stmt->closeCursor();
903
-
904
-				foreach ($changes as $uri => $operation) {
905
-					switch ($operation) {
906
-						case 1:
907
-							$result['added'][] = $uri;
908
-							break;
909
-						case 2:
910
-							$result['modified'][] = $uri;
911
-							break;
912
-						case 3:
913
-							$result['deleted'][] = $uri;
914
-							break;
915
-					}
916
-				}
917
-			} else {
918
-				$qb = $this->db->getQueryBuilder();
919
-				$qb->select('uri')
920
-					->from('cards')
921
-					->where(
922
-						$qb->expr()->eq('addressbookid', $qb->createNamedParameter($addressBookId))
923
-					);
924
-				// No synctoken supplied, this is the initial sync.
925
-				$stmt = $qb->executeQuery();
926
-				$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
927
-				$stmt->closeCursor();
928
-			}
929
-			return $result;
930
-		}, $this->db);
931
-	}
932
-
933
-	/**
934
-	 * Adds a change record to the addressbookchanges table.
935
-	 *
936
-	 * @param mixed $addressBookId
937
-	 * @param string $objectUri
938
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete
939
-	 * @return void
940
-	 */
941
-	protected function addChange(int $addressBookId, string $objectUri, int $operation): void {
942
-		$this->atomic(function () use ($addressBookId, $objectUri, $operation): void {
943
-			$query = $this->db->getQueryBuilder();
944
-			$query->select('synctoken')
945
-				->from('addressbooks')
946
-				->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)));
947
-			$result = $query->executeQuery();
948
-			$syncToken = (int)$result->fetchOne();
949
-			$result->closeCursor();
950
-
951
-			$query = $this->db->getQueryBuilder();
952
-			$query->insert('addressbookchanges')
953
-				->values([
954
-					'uri' => $query->createNamedParameter($objectUri),
955
-					'synctoken' => $query->createNamedParameter($syncToken),
956
-					'addressbookid' => $query->createNamedParameter($addressBookId),
957
-					'operation' => $query->createNamedParameter($operation),
958
-					'created_at' => time(),
959
-				])
960
-				->executeStatement();
961
-
962
-			$query = $this->db->getQueryBuilder();
963
-			$query->update('addressbooks')
964
-				->set('synctoken', $query->createNamedParameter($syncToken + 1, IQueryBuilder::PARAM_INT))
965
-				->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
966
-				->executeStatement();
967
-		}, $this->db);
968
-	}
969
-
970
-	/**
971
-	 * @param resource|string $cardData
972
-	 * @param bool $modified
973
-	 * @return string
974
-	 */
975
-	private function readBlob($cardData, &$modified = false) {
976
-		if (is_resource($cardData)) {
977
-			$cardData = stream_get_contents($cardData);
978
-		}
979
-
980
-		// Micro optimisation
981
-		// don't loop through
982
-		if (str_starts_with($cardData, 'PHOTO:data:')) {
983
-			return $cardData;
984
-		}
985
-
986
-		$cardDataArray = explode("\r\n", $cardData);
987
-
988
-		$cardDataFiltered = [];
989
-		$removingPhoto = false;
990
-		foreach ($cardDataArray as $line) {
991
-			if (str_starts_with($line, 'PHOTO:data:')
992
-				&& !str_starts_with($line, 'PHOTO:data:image/')) {
993
-				// Filter out PHOTO data of non-images
994
-				$removingPhoto = true;
995
-				$modified = true;
996
-				continue;
997
-			}
998
-
999
-			if ($removingPhoto) {
1000
-				if (str_starts_with($line, ' ')) {
1001
-					continue;
1002
-				}
1003
-				// No leading space means this is a new property
1004
-				$removingPhoto = false;
1005
-			}
1006
-
1007
-			$cardDataFiltered[] = $line;
1008
-		}
1009
-		return implode("\r\n", $cardDataFiltered);
1010
-	}
1011
-
1012
-	/**
1013
-	 * @param list<array{href: string, commonName: string, readOnly: bool}> $add
1014
-	 * @param list<string> $remove
1015
-	 */
1016
-	public function updateShares(IShareable $shareable, array $add, array $remove): void {
1017
-		$this->atomic(function () use ($shareable, $add, $remove): void {
1018
-			$addressBookId = $shareable->getResourceId();
1019
-			$addressBookData = $this->getAddressBookById($addressBookId);
1020
-			$oldShares = $this->getShares($addressBookId);
1021
-
1022
-			$this->sharingBackend->updateShares($shareable, $add, $remove, $oldShares);
1023
-
1024
-			$this->dispatcher->dispatchTyped(new AddressBookShareUpdatedEvent($addressBookId, $addressBookData, $oldShares, $add, $remove));
1025
-		}, $this->db);
1026
-	}
1027
-
1028
-	/**
1029
-	 * Search contacts in a specific address-book
1030
-	 *
1031
-	 * @param int $addressBookId
1032
-	 * @param string $pattern which should match within the $searchProperties
1033
-	 * @param array $searchProperties defines the properties within the query pattern should match
1034
-	 * @param array $options = array() to define the search behavior
1035
-	 *                       - 'types' boolean (since 15.0.0) If set to true, fields that come with a TYPE property will be an array
1036
-	 *                       - 'escape_like_param' - If set to false wildcards _ and % are not escaped, otherwise they are
1037
-	 *                       - 'limit' - Set a numeric limit for the search results
1038
-	 *                       - 'offset' - Set the offset for the limited search results
1039
-	 *                       - 'wildcard' - Whether the search should use wildcards
1040
-	 * @psalm-param array{types?: bool, escape_like_param?: bool, limit?: int, offset?: int, wildcard?: bool} $options
1041
-	 * @return array an array of contacts which are arrays of key-value-pairs
1042
-	 */
1043
-	public function search($addressBookId, $pattern, $searchProperties, $options = []): array {
1044
-		return $this->atomic(function () use ($addressBookId, $pattern, $searchProperties, $options) {
1045
-			return $this->searchByAddressBookIds([$addressBookId], $pattern, $searchProperties, $options);
1046
-		}, $this->db);
1047
-	}
1048
-
1049
-	/**
1050
-	 * Search contacts in all address-books accessible by a user
1051
-	 *
1052
-	 * @param string $principalUri
1053
-	 * @param string $pattern
1054
-	 * @param array $searchProperties
1055
-	 * @param array $options
1056
-	 * @return array
1057
-	 */
1058
-	public function searchPrincipalUri(string $principalUri,
1059
-		string $pattern,
1060
-		array $searchProperties,
1061
-		array $options = []): array {
1062
-		return $this->atomic(function () use ($principalUri, $pattern, $searchProperties, $options) {
1063
-			$addressBookIds = array_map(static function ($row):int {
1064
-				return (int)$row['id'];
1065
-			}, $this->getAddressBooksForUser($principalUri));
1066
-
1067
-			return $this->searchByAddressBookIds($addressBookIds, $pattern, $searchProperties, $options);
1068
-		}, $this->db);
1069
-	}
1070
-
1071
-	/**
1072
-	 * @param int[] $addressBookIds
1073
-	 * @param string $pattern
1074
-	 * @param array $searchProperties
1075
-	 * @param array $options
1076
-	 * @psalm-param array{
1077
-	 *   types?: bool,
1078
-	 *   escape_like_param?: bool,
1079
-	 *   limit?: int,
1080
-	 *   offset?: int,
1081
-	 *   wildcard?: bool,
1082
-	 *   since?: DateTimeFilter|null,
1083
-	 *   until?: DateTimeFilter|null,
1084
-	 *   person?: string
1085
-	 * } $options
1086
-	 * @return array
1087
-	 */
1088
-	private function searchByAddressBookIds(array $addressBookIds,
1089
-		string $pattern,
1090
-		array $searchProperties,
1091
-		array $options = []): array {
1092
-		if (empty($addressBookIds)) {
1093
-			return [];
1094
-		}
1095
-		$escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
1096
-		$useWildcards = !\array_key_exists('wildcard', $options) || $options['wildcard'] !== false;
1097
-
1098
-		if ($escapePattern) {
1099
-			$searchProperties = array_filter($searchProperties, function ($property) use ($pattern) {
1100
-				if ($property === 'EMAIL' && str_contains($pattern, ' ')) {
1101
-					// There can be no spaces in emails
1102
-					return false;
1103
-				}
1104
-
1105
-				if ($property === 'CLOUD' && preg_match('/[^a-zA-Z0-9 :_.@\/\-\']/', $pattern) === 1) {
1106
-					// There can be no chars in cloud ids which are not valid for user ids plus :/
1107
-					// worst case: CA61590A-BBBC-423E-84AF-E6DF01455A53@https://my.nxt/srv/
1108
-					return false;
1109
-				}
1110
-
1111
-				return true;
1112
-			});
1113
-		}
1114
-
1115
-		if (empty($searchProperties)) {
1116
-			return [];
1117
-		}
1118
-
1119
-		$query2 = $this->db->getQueryBuilder();
1120
-		$query2->selectDistinct('cp.cardid')
1121
-			->from($this->dbCardsPropertiesTable, 'cp')
1122
-			->where($query2->expr()->in('cp.addressbookid', $query2->createNamedParameter($addressBookIds, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
1123
-			->andWhere($query2->expr()->in('cp.name', $query2->createNamedParameter($searchProperties, IQueryBuilder::PARAM_STR_ARRAY)));
1124
-
1125
-		// No need for like when the pattern is empty
1126
-		if ($pattern !== '') {
1127
-			if (!$useWildcards) {
1128
-				$query2->andWhere($query2->expr()->eq('cp.value', $query2->createNamedParameter($pattern)));
1129
-			} elseif (!$escapePattern) {
1130
-				$query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter($pattern)));
1131
-			} else {
1132
-				$query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
1133
-			}
1134
-		}
1135
-		if (isset($options['limit'])) {
1136
-			$query2->setMaxResults($options['limit']);
1137
-		}
1138
-		if (isset($options['offset'])) {
1139
-			$query2->setFirstResult($options['offset']);
1140
-		}
1141
-
1142
-		if (isset($options['person'])) {
1143
-			$query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter('%' . $this->db->escapeLikeParameter($options['person']) . '%')));
1144
-		}
1145
-		if (isset($options['since']) || isset($options['until'])) {
1146
-			$query2->join('cp', $this->dbCardsPropertiesTable, 'cp_bday', 'cp.cardid = cp_bday.cardid');
1147
-			$query2->andWhere($query2->expr()->eq('cp_bday.name', $query2->createNamedParameter('BDAY')));
1148
-			/**
1149
-			 * FIXME Find a way to match only 4 last digits
1150
-			 * BDAY can be --1018 without year or 20001019 with it
1151
-			 * $bDayOr = [];
1152
-			 * if ($options['since'] instanceof DateTimeFilter) {
1153
-			 * $bDayOr[] =
1154
-			 * $query2->expr()->gte('SUBSTR(cp_bday.value, -4)',
1155
-			 * $query2->createNamedParameter($options['since']->get()->format('md'))
1156
-			 * );
1157
-			 * }
1158
-			 * if ($options['until'] instanceof DateTimeFilter) {
1159
-			 * $bDayOr[] =
1160
-			 * $query2->expr()->lte('SUBSTR(cp_bday.value, -4)',
1161
-			 * $query2->createNamedParameter($options['until']->get()->format('md'))
1162
-			 * );
1163
-			 * }
1164
-			 * $query2->andWhere($query2->expr()->orX(...$bDayOr));
1165
-			 */
1166
-		}
1167
-
1168
-		$result = $query2->executeQuery();
1169
-		$matches = $result->fetchAll();
1170
-		$result->closeCursor();
1171
-		$matches = array_map(function ($match) {
1172
-			return (int)$match['cardid'];
1173
-		}, $matches);
1174
-
1175
-		$cards = [];
1176
-		$query = $this->db->getQueryBuilder();
1177
-		$query->select('c.addressbookid', 'c.carddata', 'c.uri')
1178
-			->from($this->dbCardsTable, 'c')
1179
-			->where($query->expr()->in('c.id', $query->createParameter('matches')));
1180
-
1181
-		foreach (array_chunk($matches, 1000) as $matchesChunk) {
1182
-			$query->setParameter('matches', $matchesChunk, IQueryBuilder::PARAM_INT_ARRAY);
1183
-			$result = $query->executeQuery();
1184
-			$cards = array_merge($cards, $result->fetchAll());
1185
-			$result->closeCursor();
1186
-		}
1187
-
1188
-		return array_map(function ($array) {
1189
-			$array['addressbookid'] = (int)$array['addressbookid'];
1190
-			$modified = false;
1191
-			$array['carddata'] = $this->readBlob($array['carddata'], $modified);
1192
-			if ($modified) {
1193
-				$array['size'] = strlen($array['carddata']);
1194
-			}
1195
-			return $array;
1196
-		}, $cards);
1197
-	}
1198
-
1199
-	/**
1200
-	 * @param int $bookId
1201
-	 * @param string $name
1202
-	 * @return array
1203
-	 */
1204
-	public function collectCardProperties($bookId, $name) {
1205
-		$query = $this->db->getQueryBuilder();
1206
-		$result = $query->selectDistinct('value')
1207
-			->from($this->dbCardsPropertiesTable)
1208
-			->where($query->expr()->eq('name', $query->createNamedParameter($name)))
1209
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
1210
-			->executeQuery();
1211
-
1212
-		$all = $result->fetchAll(PDO::FETCH_COLUMN);
1213
-		$result->closeCursor();
1214
-
1215
-		return $all;
1216
-	}
1217
-
1218
-	/**
1219
-	 * get URI from a given contact
1220
-	 *
1221
-	 * @param int $id
1222
-	 * @return string
1223
-	 */
1224
-	public function getCardUri($id) {
1225
-		$query = $this->db->getQueryBuilder();
1226
-		$query->select('uri')->from($this->dbCardsTable)
1227
-			->where($query->expr()->eq('id', $query->createParameter('id')))
1228
-			->setParameter('id', $id);
1229
-
1230
-		$result = $query->executeQuery();
1231
-		$uri = $result->fetch();
1232
-		$result->closeCursor();
1233
-
1234
-		if (!isset($uri['uri'])) {
1235
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
1236
-		}
1237
-
1238
-		return $uri['uri'];
1239
-	}
1240
-
1241
-	/**
1242
-	 * return contact with the given URI
1243
-	 *
1244
-	 * @param int $addressBookId
1245
-	 * @param string $uri
1246
-	 * @returns array
1247
-	 */
1248
-	public function getContact($addressBookId, $uri) {
1249
-		$result = [];
1250
-		$query = $this->db->getQueryBuilder();
1251
-		$query->select('*')->from($this->dbCardsTable)
1252
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1253
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1254
-		$queryResult = $query->executeQuery();
1255
-		$contact = $queryResult->fetch();
1256
-		$queryResult->closeCursor();
1257
-
1258
-		if (is_array($contact)) {
1259
-			$modified = false;
1260
-			$contact['etag'] = '"' . $contact['etag'] . '"';
1261
-			$contact['carddata'] = $this->readBlob($contact['carddata'], $modified);
1262
-			if ($modified) {
1263
-				$contact['size'] = strlen($contact['carddata']);
1264
-			}
1265
-
1266
-			$result = $contact;
1267
-		}
1268
-
1269
-		return $result;
1270
-	}
1271
-
1272
-	/**
1273
-	 * Returns the list of people whom this address book is shared with.
1274
-	 *
1275
-	 * Every element in this array should have the following properties:
1276
-	 *   * href - Often a mailto: address
1277
-	 *   * commonName - Optional, for example a first + last name
1278
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
1279
-	 *   * readOnly - boolean
1280
-	 *
1281
-	 * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
1282
-	 */
1283
-	public function getShares(int $addressBookId): array {
1284
-		return $this->sharingBackend->getShares($addressBookId);
1285
-	}
1286
-
1287
-	/**
1288
-	 * update properties table
1289
-	 *
1290
-	 * @param int $addressBookId
1291
-	 * @param string $cardUri
1292
-	 * @param string $vCardSerialized
1293
-	 */
1294
-	protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
1295
-		$this->atomic(function () use ($addressBookId, $cardUri, $vCardSerialized): void {
1296
-			$cardId = $this->getCardId($addressBookId, $cardUri);
1297
-			$vCard = $this->readCard($vCardSerialized);
1298
-
1299
-			$this->purgeProperties($addressBookId, $cardId);
1300
-
1301
-			$query = $this->db->getQueryBuilder();
1302
-			$query->insert($this->dbCardsPropertiesTable)
1303
-				->values(
1304
-					[
1305
-						'addressbookid' => $query->createNamedParameter($addressBookId),
1306
-						'cardid' => $query->createNamedParameter($cardId),
1307
-						'name' => $query->createParameter('name'),
1308
-						'value' => $query->createParameter('value'),
1309
-						'preferred' => $query->createParameter('preferred')
1310
-					]
1311
-				);
1312
-
1313
-			foreach ($vCard->children() as $property) {
1314
-				if (!in_array($property->name, self::$indexProperties)) {
1315
-					continue;
1316
-				}
1317
-				$preferred = 0;
1318
-				foreach ($property->parameters as $parameter) {
1319
-					if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1320
-						$preferred = 1;
1321
-						break;
1322
-					}
1323
-				}
1324
-				$query->setParameter('name', $property->name);
1325
-				$query->setParameter('value', mb_strcut($property->getValue(), 0, 254));
1326
-				$query->setParameter('preferred', $preferred);
1327
-				$query->executeStatement();
1328
-			}
1329
-		}, $this->db);
1330
-	}
1331
-
1332
-	/**
1333
-	 * read vCard data into a vCard object
1334
-	 *
1335
-	 * @param string $cardData
1336
-	 * @return VCard
1337
-	 */
1338
-	protected function readCard($cardData) {
1339
-		return Reader::read($cardData);
1340
-	}
1341
-
1342
-	/**
1343
-	 * delete all properties from a given card
1344
-	 *
1345
-	 * @param int $addressBookId
1346
-	 * @param int $cardId
1347
-	 */
1348
-	protected function purgeProperties($addressBookId, $cardId) {
1349
-		$query = $this->db->getQueryBuilder();
1350
-		$query->delete($this->dbCardsPropertiesTable)
1351
-			->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1352
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1353
-		$query->executeStatement();
1354
-	}
1355
-
1356
-	/**
1357
-	 * Get ID from a given contact
1358
-	 */
1359
-	protected function getCardId(int $addressBookId, string $uri): int {
1360
-		$query = $this->db->getQueryBuilder();
1361
-		$query->select('id')->from($this->dbCardsTable)
1362
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1363
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1364
-
1365
-		$result = $query->executeQuery();
1366
-		$cardIds = $result->fetch();
1367
-		$result->closeCursor();
1368
-
1369
-		if (!isset($cardIds['id'])) {
1370
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1371
-		}
1372
-
1373
-		return (int)$cardIds['id'];
1374
-	}
1375
-
1376
-	/**
1377
-	 * For shared address books the sharee is set in the ACL of the address book
1378
-	 *
1379
-	 * @param int $addressBookId
1380
-	 * @param list<array{privilege: string, principal: string, protected: bool}> $acl
1381
-	 * @return list<array{privilege: string, principal: string, protected: bool}>
1382
-	 */
1383
-	public function applyShareAcl(int $addressBookId, array $acl): array {
1384
-		$shares = $this->sharingBackend->getShares($addressBookId);
1385
-		return $this->sharingBackend->applyShareAcl($shares, $acl);
1386
-	}
1387
-
1388
-	/**
1389
-	 * @throws \InvalidArgumentException
1390
-	 */
1391
-	public function pruneOutdatedSyncTokens(int $keep, int $retention): int {
1392
-		if ($keep < 0) {
1393
-			throw new \InvalidArgumentException();
1394
-		}
1395
-
1396
-		$query = $this->db->getQueryBuilder();
1397
-		$query->select($query->func()->max('id'))
1398
-			->from('addressbookchanges');
1399
-
1400
-		$result = $query->executeQuery();
1401
-		$maxId = (int)$result->fetchOne();
1402
-		$result->closeCursor();
1403
-		if (!$maxId || $maxId < $keep) {
1404
-			return 0;
1405
-		}
1406
-
1407
-		$query = $this->db->getQueryBuilder();
1408
-		$query->delete('addressbookchanges')
1409
-			->where(
1410
-				$query->expr()->lte('id', $query->createNamedParameter($maxId - $keep, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
1411
-				$query->expr()->lte('created_at', $query->createNamedParameter($retention)),
1412
-			);
1413
-		return $query->executeStatement();
1414
-	}
1415
-
1416
-	private function convertPrincipal(string $principalUri, bool $toV2): string {
1417
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1418
-			[, $name] = \Sabre\Uri\split($principalUri);
1419
-			if ($toV2 === true) {
1420
-				return "principals/users/$name";
1421
-			}
1422
-			return "principals/$name";
1423
-		}
1424
-		return $principalUri;
1425
-	}
1426
-
1427
-	private function addOwnerPrincipal(array &$addressbookInfo): void {
1428
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1429
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1430
-		if (isset($addressbookInfo[$ownerPrincipalKey])) {
1431
-			$uri = $addressbookInfo[$ownerPrincipalKey];
1432
-		} else {
1433
-			$uri = $addressbookInfo['principaluri'];
1434
-		}
1435
-
1436
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1437
-		if (isset($principalInformation['{DAV:}displayname'])) {
1438
-			$addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1439
-		}
1440
-	}
1441
-
1442
-	/**
1443
-	 * Extract UID from vcard
1444
-	 *
1445
-	 * @param string $cardData the vcard raw data
1446
-	 * @return string the uid
1447
-	 * @throws BadRequest if no UID is available or vcard is empty
1448
-	 */
1449
-	private function getUID(string $cardData): string {
1450
-		if ($cardData !== '') {
1451
-			$vCard = Reader::read($cardData);
1452
-			if ($vCard->UID) {
1453
-				$uid = $vCard->UID->getValue();
1454
-				return $uid;
1455
-			}
1456
-			// should already be handled, but just in case
1457
-			throw new BadRequest('vCards on CardDAV servers MUST have a UID property');
1458
-		}
1459
-		// should already be handled, but just in case
1460
-		throw new BadRequest('vCard can not be empty');
1461
-	}
37
+    use TTransactional;
38
+    public const PERSONAL_ADDRESSBOOK_URI = 'contacts';
39
+    public const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
40
+
41
+    private string $dbCardsTable = 'cards';
42
+    private string $dbCardsPropertiesTable = 'cards_properties';
43
+
44
+    /** @var array properties to index */
45
+    public static array $indexProperties = [
46
+        'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
47
+        'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO',
48
+        'CLOUD', 'X-SOCIALPROFILE'];
49
+
50
+    /**
51
+     * @var string[] Map of uid => display name
52
+     */
53
+    protected array $userDisplayNames;
54
+    private array $etagCache = [];
55
+
56
+    public function __construct(
57
+        private IDBConnection $db,
58
+        private Principal $principalBackend,
59
+        private IUserManager $userManager,
60
+        private IEventDispatcher $dispatcher,
61
+        private Sharing\Backend $sharingBackend,
62
+    ) {
63
+    }
64
+
65
+    /**
66
+     * Return the number of address books for a principal
67
+     *
68
+     * @param $principalUri
69
+     * @return int
70
+     */
71
+    public function getAddressBooksForUserCount($principalUri) {
72
+        $principalUri = $this->convertPrincipal($principalUri, true);
73
+        $query = $this->db->getQueryBuilder();
74
+        $query->select($query->func()->count('*'))
75
+            ->from('addressbooks')
76
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
77
+
78
+        $result = $query->executeQuery();
79
+        $column = (int)$result->fetchOne();
80
+        $result->closeCursor();
81
+        return $column;
82
+    }
83
+
84
+    /**
85
+     * Returns the list of address books for a specific user.
86
+     *
87
+     * Every addressbook should have the following properties:
88
+     *   id - an arbitrary unique id
89
+     *   uri - the 'basename' part of the url
90
+     *   principaluri - Same as the passed parameter
91
+     *
92
+     * Any additional clark-notation property may be passed besides this. Some
93
+     * common ones are :
94
+     *   {DAV:}displayname
95
+     *   {urn:ietf:params:xml:ns:carddav}addressbook-description
96
+     *   {http://calendarserver.org/ns/}getctag
97
+     *
98
+     * @param string $principalUri
99
+     * @return array
100
+     */
101
+    public function getAddressBooksForUser($principalUri) {
102
+        return $this->atomic(function () use ($principalUri) {
103
+            $principalUriOriginal = $principalUri;
104
+            $principalUri = $this->convertPrincipal($principalUri, true);
105
+            $select = $this->db->getQueryBuilder();
106
+            $select->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
107
+                ->from('addressbooks')
108
+                ->where($select->expr()->eq('principaluri', $select->createNamedParameter($principalUri)));
109
+
110
+            $addressBooks = [];
111
+
112
+            $result = $select->executeQuery();
113
+            while ($row = $result->fetch()) {
114
+                $addressBooks[$row['id']] = [
115
+                    'id' => $row['id'],
116
+                    'uri' => $row['uri'],
117
+                    'principaluri' => $this->convertPrincipal($row['principaluri'], false),
118
+                    '{DAV:}displayname' => $row['displayname'],
119
+                    '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
120
+                    '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
121
+                    '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
122
+                ];
123
+
124
+                $this->addOwnerPrincipal($addressBooks[$row['id']]);
125
+            }
126
+            $result->closeCursor();
127
+
128
+            // query for shared addressbooks
129
+            $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
130
+
131
+            $principals[] = $principalUri;
132
+
133
+            $select = $this->db->getQueryBuilder();
134
+            $subSelect = $this->db->getQueryBuilder();
135
+
136
+            $subSelect->select('id')
137
+                ->from('dav_shares', 'd')
138
+                ->where($subSelect->expr()->eq('d.access', $select->createNamedParameter(\OCA\DAV\CardDAV\Sharing\Backend::ACCESS_UNSHARED, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
139
+                ->andWhere($subSelect->expr()->in('d.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY));
140
+
141
+
142
+            $select->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
143
+                ->from('dav_shares', 's')
144
+                ->join('s', 'addressbooks', 'a', $select->expr()->eq('s.resourceid', 'a.id'))
145
+                ->where($select->expr()->in('s.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY)))
146
+                ->andWhere($select->expr()->eq('s.type', $select->createNamedParameter('addressbook', IQueryBuilder::PARAM_STR)))
147
+                ->andWhere($select->expr()->notIn('s.id', $select->createFunction($subSelect->getSQL()), IQueryBuilder::PARAM_INT_ARRAY));
148
+            $result = $select->executeQuery();
149
+
150
+            $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
151
+            while ($row = $result->fetch()) {
152
+                if ($row['principaluri'] === $principalUri) {
153
+                    continue;
154
+                }
155
+
156
+                $readOnly = (int)$row['access'] === Backend::ACCESS_READ;
157
+                if (isset($addressBooks[$row['id']])) {
158
+                    if ($readOnly) {
159
+                        // New share can not have more permissions then the old one.
160
+                        continue;
161
+                    }
162
+                    if (isset($addressBooks[$row['id']][$readOnlyPropertyName])
163
+                        && $addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
164
+                        // Old share is already read-write, no more permissions can be gained
165
+                        continue;
166
+                    }
167
+                }
168
+
169
+                [, $name] = \Sabre\Uri\split($row['principaluri']);
170
+                $uri = $row['uri'] . '_shared_by_' . $name;
171
+                $displayName = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? $name ?? '') . ')';
172
+
173
+                $addressBooks[$row['id']] = [
174
+                    'id' => $row['id'],
175
+                    'uri' => $uri,
176
+                    'principaluri' => $principalUriOriginal,
177
+                    '{DAV:}displayname' => $displayName,
178
+                    '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
179
+                    '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
180
+                    '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
181
+                    '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
182
+                    $readOnlyPropertyName => $readOnly,
183
+                ];
184
+
185
+                $this->addOwnerPrincipal($addressBooks[$row['id']]);
186
+            }
187
+            $result->closeCursor();
188
+
189
+            return array_values($addressBooks);
190
+        }, $this->db);
191
+    }
192
+
193
+    public function getUsersOwnAddressBooks($principalUri) {
194
+        $principalUri = $this->convertPrincipal($principalUri, true);
195
+        $query = $this->db->getQueryBuilder();
196
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
197
+            ->from('addressbooks')
198
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
199
+
200
+        $addressBooks = [];
201
+
202
+        $result = $query->executeQuery();
203
+        while ($row = $result->fetch()) {
204
+            $addressBooks[$row['id']] = [
205
+                'id' => $row['id'],
206
+                'uri' => $row['uri'],
207
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
208
+                '{DAV:}displayname' => $row['displayname'],
209
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
210
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
211
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
212
+            ];
213
+
214
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
215
+        }
216
+        $result->closeCursor();
217
+
218
+        return array_values($addressBooks);
219
+    }
220
+
221
+    /**
222
+     * @param int $addressBookId
223
+     */
224
+    public function getAddressBookById(int $addressBookId): ?array {
225
+        $query = $this->db->getQueryBuilder();
226
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
227
+            ->from('addressbooks')
228
+            ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId, IQueryBuilder::PARAM_INT)))
229
+            ->executeQuery();
230
+        $row = $result->fetch();
231
+        $result->closeCursor();
232
+        if (!$row) {
233
+            return null;
234
+        }
235
+
236
+        $addressBook = [
237
+            'id' => $row['id'],
238
+            'uri' => $row['uri'],
239
+            'principaluri' => $row['principaluri'],
240
+            '{DAV:}displayname' => $row['displayname'],
241
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
242
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
243
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
244
+        ];
245
+
246
+        $this->addOwnerPrincipal($addressBook);
247
+
248
+        return $addressBook;
249
+    }
250
+
251
+    public function getAddressBooksByUri(string $principal, string $addressBookUri): ?array {
252
+        $query = $this->db->getQueryBuilder();
253
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
254
+            ->from('addressbooks')
255
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
256
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
257
+            ->setMaxResults(1)
258
+            ->executeQuery();
259
+
260
+        $row = $result->fetch();
261
+        $result->closeCursor();
262
+        if ($row === false) {
263
+            return null;
264
+        }
265
+
266
+        $addressBook = [
267
+            'id' => $row['id'],
268
+            'uri' => $row['uri'],
269
+            'principaluri' => $row['principaluri'],
270
+            '{DAV:}displayname' => $row['displayname'],
271
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
272
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
273
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
274
+
275
+        ];
276
+
277
+        // system address books are always read only
278
+        if ($principal === 'principals/system/system') {
279
+            $addressBook['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal'] = $row['principaluri'];
280
+            $addressBook['{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only'] = true;
281
+        }
282
+
283
+        $this->addOwnerPrincipal($addressBook);
284
+
285
+        return $addressBook;
286
+    }
287
+
288
+    /**
289
+     * Updates properties for an address book.
290
+     *
291
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
292
+     * To do the actual updates, you must tell this object which properties
293
+     * you're going to process with the handle() method.
294
+     *
295
+     * Calling the handle method is like telling the PropPatch object "I
296
+     * promise I can handle updating this property".
297
+     *
298
+     * Read the PropPatch documentation for more info and examples.
299
+     *
300
+     * @param string $addressBookId
301
+     * @param \Sabre\DAV\PropPatch $propPatch
302
+     * @return void
303
+     */
304
+    public function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
305
+        $supportedProperties = [
306
+            '{DAV:}displayname',
307
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description',
308
+        ];
309
+
310
+        $propPatch->handle($supportedProperties, function ($mutations) use ($addressBookId) {
311
+            $updates = [];
312
+            foreach ($mutations as $property => $newValue) {
313
+                switch ($property) {
314
+                    case '{DAV:}displayname':
315
+                        $updates['displayname'] = $newValue;
316
+                        break;
317
+                    case '{' . Plugin::NS_CARDDAV . '}addressbook-description':
318
+                        $updates['description'] = $newValue;
319
+                        break;
320
+                }
321
+            }
322
+            [$addressBookRow, $shares] = $this->atomic(function () use ($addressBookId, $updates) {
323
+                $query = $this->db->getQueryBuilder();
324
+                $query->update('addressbooks');
325
+
326
+                foreach ($updates as $key => $value) {
327
+                    $query->set($key, $query->createNamedParameter($value));
328
+                }
329
+                $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
330
+                    ->executeStatement();
331
+
332
+                $this->addChange($addressBookId, '', 2);
333
+
334
+                $addressBookRow = $this->getAddressBookById((int)$addressBookId);
335
+                $shares = $this->getShares((int)$addressBookId);
336
+                return [$addressBookRow, $shares];
337
+            }, $this->db);
338
+
339
+            $this->dispatcher->dispatchTyped(new AddressBookUpdatedEvent((int)$addressBookId, $addressBookRow, $shares, $mutations));
340
+
341
+            return true;
342
+        });
343
+    }
344
+
345
+    /**
346
+     * Creates a new address book
347
+     *
348
+     * @param string $principalUri
349
+     * @param string $url Just the 'basename' of the url.
350
+     * @param array $properties
351
+     * @return int
352
+     * @throws BadRequest
353
+     * @throws Exception
354
+     */
355
+    public function createAddressBook($principalUri, $url, array $properties) {
356
+        if (strlen($url) > 255) {
357
+            throw new BadRequest('URI too long. Address book not created');
358
+        }
359
+
360
+        $values = [
361
+            'displayname' => null,
362
+            'description' => null,
363
+            'principaluri' => $principalUri,
364
+            'uri' => $url,
365
+            'synctoken' => 1
366
+        ];
367
+
368
+        foreach ($properties as $property => $newValue) {
369
+            switch ($property) {
370
+                case '{DAV:}displayname':
371
+                    $values['displayname'] = $newValue;
372
+                    break;
373
+                case '{' . Plugin::NS_CARDDAV . '}addressbook-description':
374
+                    $values['description'] = $newValue;
375
+                    break;
376
+                default:
377
+                    throw new BadRequest('Unknown property: ' . $property);
378
+            }
379
+        }
380
+
381
+        // Fallback to make sure the displayname is set. Some clients may refuse
382
+        // to work with addressbooks not having a displayname.
383
+        if (is_null($values['displayname'])) {
384
+            $values['displayname'] = $url;
385
+        }
386
+
387
+        [$addressBookId, $addressBookRow] = $this->atomic(function () use ($values) {
388
+            $query = $this->db->getQueryBuilder();
389
+            $query->insert('addressbooks')
390
+                ->values([
391
+                    'uri' => $query->createParameter('uri'),
392
+                    'displayname' => $query->createParameter('displayname'),
393
+                    'description' => $query->createParameter('description'),
394
+                    'principaluri' => $query->createParameter('principaluri'),
395
+                    'synctoken' => $query->createParameter('synctoken'),
396
+                ])
397
+                ->setParameters($values)
398
+                ->executeStatement();
399
+
400
+            $addressBookId = $query->getLastInsertId();
401
+            return [
402
+                $addressBookId,
403
+                $this->getAddressBookById($addressBookId),
404
+            ];
405
+        }, $this->db);
406
+
407
+        $this->dispatcher->dispatchTyped(new AddressBookCreatedEvent($addressBookId, $addressBookRow));
408
+
409
+        return $addressBookId;
410
+    }
411
+
412
+    /**
413
+     * Deletes an entire addressbook and all its contents
414
+     *
415
+     * @param mixed $addressBookId
416
+     * @return void
417
+     */
418
+    public function deleteAddressBook($addressBookId) {
419
+        $this->atomic(function () use ($addressBookId): void {
420
+            $addressBookId = (int)$addressBookId;
421
+            $addressBookData = $this->getAddressBookById($addressBookId);
422
+            $shares = $this->getShares($addressBookId);
423
+
424
+            $query = $this->db->getQueryBuilder();
425
+            $query->delete($this->dbCardsTable)
426
+                ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
427
+                ->setParameter('addressbookid', $addressBookId, IQueryBuilder::PARAM_INT)
428
+                ->executeStatement();
429
+
430
+            $query = $this->db->getQueryBuilder();
431
+            $query->delete('addressbookchanges')
432
+                ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
433
+                ->setParameter('addressbookid', $addressBookId, IQueryBuilder::PARAM_INT)
434
+                ->executeStatement();
435
+
436
+            $query = $this->db->getQueryBuilder();
437
+            $query->delete('addressbooks')
438
+                ->where($query->expr()->eq('id', $query->createParameter('id')))
439
+                ->setParameter('id', $addressBookId, IQueryBuilder::PARAM_INT)
440
+                ->executeStatement();
441
+
442
+            $this->sharingBackend->deleteAllShares($addressBookId);
443
+
444
+            $query = $this->db->getQueryBuilder();
445
+            $query->delete($this->dbCardsPropertiesTable)
446
+                ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId, IQueryBuilder::PARAM_INT)))
447
+                ->executeStatement();
448
+
449
+            if ($addressBookData) {
450
+                $this->dispatcher->dispatchTyped(new AddressBookDeletedEvent($addressBookId, $addressBookData, $shares));
451
+            }
452
+        }, $this->db);
453
+    }
454
+
455
+    /**
456
+     * Returns all cards for a specific addressbook id.
457
+     *
458
+     * This method should return the following properties for each card:
459
+     *   * carddata - raw vcard data
460
+     *   * uri - Some unique url
461
+     *   * lastmodified - A unix timestamp
462
+     *
463
+     * It's recommended to also return the following properties:
464
+     *   * etag - A unique etag. This must change every time the card changes.
465
+     *   * size - The size of the card in bytes.
466
+     *
467
+     * If these last two properties are provided, less time will be spent
468
+     * calculating them. If they are specified, you can also omit carddata.
469
+     * This may speed up certain requests, especially with large cards.
470
+     *
471
+     * @param mixed $addressbookId
472
+     * @return array
473
+     */
474
+    public function getCards($addressbookId) {
475
+        $query = $this->db->getQueryBuilder();
476
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
477
+            ->from($this->dbCardsTable)
478
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressbookId)));
479
+
480
+        $cards = [];
481
+
482
+        $result = $query->executeQuery();
483
+        while ($row = $result->fetch()) {
484
+            $row['etag'] = '"' . $row['etag'] . '"';
485
+
486
+            $modified = false;
487
+            $row['carddata'] = $this->readBlob($row['carddata'], $modified);
488
+            if ($modified) {
489
+                $row['size'] = strlen($row['carddata']);
490
+            }
491
+
492
+            $cards[] = $row;
493
+        }
494
+        $result->closeCursor();
495
+
496
+        return $cards;
497
+    }
498
+
499
+    /**
500
+     * Returns a specific card.
501
+     *
502
+     * The same set of properties must be returned as with getCards. The only
503
+     * exception is that 'carddata' is absolutely required.
504
+     *
505
+     * If the card does not exist, you must return false.
506
+     *
507
+     * @param mixed $addressBookId
508
+     * @param string $cardUri
509
+     * @return array
510
+     */
511
+    public function getCard($addressBookId, $cardUri) {
512
+        $query = $this->db->getQueryBuilder();
513
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
514
+            ->from($this->dbCardsTable)
515
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
516
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
517
+            ->setMaxResults(1);
518
+
519
+        $result = $query->executeQuery();
520
+        $row = $result->fetch();
521
+        if (!$row) {
522
+            return false;
523
+        }
524
+        $row['etag'] = '"' . $row['etag'] . '"';
525
+
526
+        $modified = false;
527
+        $row['carddata'] = $this->readBlob($row['carddata'], $modified);
528
+        if ($modified) {
529
+            $row['size'] = strlen($row['carddata']);
530
+        }
531
+
532
+        return $row;
533
+    }
534
+
535
+    /**
536
+     * Returns a list of cards.
537
+     *
538
+     * This method should work identical to getCard, but instead return all the
539
+     * cards in the list as an array.
540
+     *
541
+     * If the backend supports this, it may allow for some speed-ups.
542
+     *
543
+     * @param mixed $addressBookId
544
+     * @param array $uris
545
+     * @return array
546
+     */
547
+    public function getMultipleCards($addressBookId, array $uris) {
548
+        if (empty($uris)) {
549
+            return [];
550
+        }
551
+
552
+        $chunks = array_chunk($uris, 100);
553
+        $cards = [];
554
+
555
+        $query = $this->db->getQueryBuilder();
556
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
557
+            ->from($this->dbCardsTable)
558
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
559
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
560
+
561
+        foreach ($chunks as $uris) {
562
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
563
+            $result = $query->executeQuery();
564
+
565
+            while ($row = $result->fetch()) {
566
+                $row['etag'] = '"' . $row['etag'] . '"';
567
+
568
+                $modified = false;
569
+                $row['carddata'] = $this->readBlob($row['carddata'], $modified);
570
+                if ($modified) {
571
+                    $row['size'] = strlen($row['carddata']);
572
+                }
573
+
574
+                $cards[] = $row;
575
+            }
576
+            $result->closeCursor();
577
+        }
578
+        return $cards;
579
+    }
580
+
581
+    /**
582
+     * Creates a new card.
583
+     *
584
+     * The addressbook id will be passed as the first argument. This is the
585
+     * same id as it is returned from the getAddressBooksForUser method.
586
+     *
587
+     * The cardUri is a base uri, and doesn't include the full path. The
588
+     * cardData argument is the vcard body, and is passed as a string.
589
+     *
590
+     * It is possible to return an ETag from this method. This ETag is for the
591
+     * newly created resource, and must be enclosed with double quotes (that
592
+     * is, the string itself must contain the double quotes).
593
+     *
594
+     * You should only return the ETag if you store the carddata as-is. If a
595
+     * subsequent GET request on the same card does not have the same body,
596
+     * byte-by-byte and you did return an ETag here, clients tend to get
597
+     * confused.
598
+     *
599
+     * If you don't return an ETag, you can just return null.
600
+     *
601
+     * @param mixed $addressBookId
602
+     * @param string $cardUri
603
+     * @param string $cardData
604
+     * @param bool $checkAlreadyExists
605
+     * @return string
606
+     */
607
+    public function createCard($addressBookId, $cardUri, $cardData, bool $checkAlreadyExists = true) {
608
+        $etag = md5($cardData);
609
+        $uid = $this->getUID($cardData);
610
+        return $this->atomic(function () use ($addressBookId, $cardUri, $cardData, $checkAlreadyExists, $etag, $uid) {
611
+            if ($checkAlreadyExists) {
612
+                $q = $this->db->getQueryBuilder();
613
+                $q->select('uid')
614
+                    ->from($this->dbCardsTable)
615
+                    ->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId)))
616
+                    ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
617
+                    ->setMaxResults(1);
618
+                $result = $q->executeQuery();
619
+                $count = (bool)$result->fetchOne();
620
+                $result->closeCursor();
621
+                if ($count) {
622
+                    throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
623
+                }
624
+            }
625
+
626
+            $query = $this->db->getQueryBuilder();
627
+            $query->insert('cards')
628
+                ->values([
629
+                    'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
630
+                    'uri' => $query->createNamedParameter($cardUri),
631
+                    'lastmodified' => $query->createNamedParameter(time()),
632
+                    'addressbookid' => $query->createNamedParameter($addressBookId),
633
+                    'size' => $query->createNamedParameter(strlen($cardData)),
634
+                    'etag' => $query->createNamedParameter($etag),
635
+                    'uid' => $query->createNamedParameter($uid),
636
+                ])
637
+                ->executeStatement();
638
+
639
+            $etagCacheKey = "$addressBookId#$cardUri";
640
+            $this->etagCache[$etagCacheKey] = $etag;
641
+
642
+            $this->addChange($addressBookId, $cardUri, 1);
643
+            $this->updateProperties($addressBookId, $cardUri, $cardData);
644
+
645
+            $addressBookData = $this->getAddressBookById($addressBookId);
646
+            $shares = $this->getShares($addressBookId);
647
+            $objectRow = $this->getCard($addressBookId, $cardUri);
648
+            $this->dispatcher->dispatchTyped(new CardCreatedEvent($addressBookId, $addressBookData, $shares, $objectRow));
649
+
650
+            return '"' . $etag . '"';
651
+        }, $this->db);
652
+    }
653
+
654
+    /**
655
+     * Updates a card.
656
+     *
657
+     * The addressbook id will be passed as the first argument. This is the
658
+     * same id as it is returned from the getAddressBooksForUser method.
659
+     *
660
+     * The cardUri is a base uri, and doesn't include the full path. The
661
+     * cardData argument is the vcard body, and is passed as a string.
662
+     *
663
+     * It is possible to return an ETag from this method. This ETag should
664
+     * match that of the updated resource, and must be enclosed with double
665
+     * quotes (that is: the string itself must contain the actual quotes).
666
+     *
667
+     * You should only return the ETag if you store the carddata as-is. If a
668
+     * subsequent GET request on the same card does not have the same body,
669
+     * byte-by-byte and you did return an ETag here, clients tend to get
670
+     * confused.
671
+     *
672
+     * If you don't return an ETag, you can just return null.
673
+     *
674
+     * @param mixed $addressBookId
675
+     * @param string $cardUri
676
+     * @param string $cardData
677
+     * @return string
678
+     */
679
+    public function updateCard($addressBookId, $cardUri, $cardData) {
680
+        $uid = $this->getUID($cardData);
681
+        $etag = md5($cardData);
682
+
683
+        return $this->atomic(function () use ($addressBookId, $cardUri, $cardData, $uid, $etag) {
684
+            $query = $this->db->getQueryBuilder();
685
+
686
+            // check for recently stored etag and stop if it is the same
687
+            $etagCacheKey = "$addressBookId#$cardUri";
688
+            if (isset($this->etagCache[$etagCacheKey]) && $this->etagCache[$etagCacheKey] === $etag) {
689
+                return '"' . $etag . '"';
690
+            }
691
+
692
+            $query->update($this->dbCardsTable)
693
+                ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
694
+                ->set('lastmodified', $query->createNamedParameter(time()))
695
+                ->set('size', $query->createNamedParameter(strlen($cardData)))
696
+                ->set('etag', $query->createNamedParameter($etag))
697
+                ->set('uid', $query->createNamedParameter($uid))
698
+                ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
699
+                ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
700
+                ->executeStatement();
701
+
702
+            $this->etagCache[$etagCacheKey] = $etag;
703
+
704
+            $this->addChange($addressBookId, $cardUri, 2);
705
+            $this->updateProperties($addressBookId, $cardUri, $cardData);
706
+
707
+            $addressBookData = $this->getAddressBookById($addressBookId);
708
+            $shares = $this->getShares($addressBookId);
709
+            $objectRow = $this->getCard($addressBookId, $cardUri);
710
+            $this->dispatcher->dispatchTyped(new CardUpdatedEvent($addressBookId, $addressBookData, $shares, $objectRow));
711
+            return '"' . $etag . '"';
712
+        }, $this->db);
713
+    }
714
+
715
+    /**
716
+     * @throws Exception
717
+     */
718
+    public function moveCard(int $sourceAddressBookId, int $targetAddressBookId, string $cardUri, string $oldPrincipalUri): bool {
719
+        return $this->atomic(function () use ($sourceAddressBookId, $targetAddressBookId, $cardUri, $oldPrincipalUri) {
720
+            $card = $this->getCard($sourceAddressBookId, $cardUri);
721
+            if (empty($card)) {
722
+                return false;
723
+            }
724
+
725
+            $query = $this->db->getQueryBuilder();
726
+            $query->update('cards')
727
+                ->set('addressbookid', $query->createNamedParameter($targetAddressBookId, IQueryBuilder::PARAM_INT))
728
+                ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri, IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR))
729
+                ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($sourceAddressBookId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
730
+                ->executeStatement();
731
+
732
+            $this->purgeProperties($sourceAddressBookId, (int)$card['id']);
733
+            $this->updateProperties($sourceAddressBookId, $card['uri'], $card['carddata']);
734
+
735
+            $this->addChange($sourceAddressBookId, $card['uri'], 3);
736
+            $this->addChange($targetAddressBookId, $card['uri'], 1);
737
+
738
+            $card = $this->getCard($targetAddressBookId, $cardUri);
739
+            // Card wasn't found - possibly because it was deleted in the meantime by a different client
740
+            if (empty($card)) {
741
+                return false;
742
+            }
743
+
744
+            $targetAddressBookRow = $this->getAddressBookById($targetAddressBookId);
745
+            // the address book this card is being moved to does not exist any longer
746
+            if (empty($targetAddressBookRow)) {
747
+                return false;
748
+            }
749
+
750
+            $sourceShares = $this->getShares($sourceAddressBookId);
751
+            $targetShares = $this->getShares($targetAddressBookId);
752
+            $sourceAddressBookRow = $this->getAddressBookById($sourceAddressBookId);
753
+            $this->dispatcher->dispatchTyped(new CardMovedEvent($sourceAddressBookId, $sourceAddressBookRow, $targetAddressBookId, $targetAddressBookRow, $sourceShares, $targetShares, $card));
754
+            return true;
755
+        }, $this->db);
756
+    }
757
+
758
+    /**
759
+     * Deletes a card
760
+     *
761
+     * @param mixed $addressBookId
762
+     * @param string $cardUri
763
+     * @return bool
764
+     */
765
+    public function deleteCard($addressBookId, $cardUri) {
766
+        return $this->atomic(function () use ($addressBookId, $cardUri) {
767
+            $addressBookData = $this->getAddressBookById($addressBookId);
768
+            $shares = $this->getShares($addressBookId);
769
+            $objectRow = $this->getCard($addressBookId, $cardUri);
770
+
771
+            try {
772
+                $cardId = $this->getCardId($addressBookId, $cardUri);
773
+            } catch (\InvalidArgumentException $e) {
774
+                $cardId = null;
775
+            }
776
+            $query = $this->db->getQueryBuilder();
777
+            $ret = $query->delete($this->dbCardsTable)
778
+                ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
779
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
780
+                ->executeStatement();
781
+
782
+            $this->addChange($addressBookId, $cardUri, 3);
783
+
784
+            if ($ret === 1) {
785
+                if ($cardId !== null) {
786
+                    $this->dispatcher->dispatchTyped(new CardDeletedEvent($addressBookId, $addressBookData, $shares, $objectRow));
787
+                    $this->purgeProperties($addressBookId, $cardId);
788
+                }
789
+                return true;
790
+            }
791
+
792
+            return false;
793
+        }, $this->db);
794
+    }
795
+
796
+    /**
797
+     * The getChanges method returns all the changes that have happened, since
798
+     * the specified syncToken in the specified address book.
799
+     *
800
+     * This function should return an array, such as the following:
801
+     *
802
+     * [
803
+     *   'syncToken' => 'The current synctoken',
804
+     *   'added'   => [
805
+     *      'new.txt',
806
+     *   ],
807
+     *   'modified'   => [
808
+     *      'modified.txt',
809
+     *   ],
810
+     *   'deleted' => [
811
+     *      'foo.php.bak',
812
+     *      'old.txt'
813
+     *   ]
814
+     * ];
815
+     *
816
+     * The returned syncToken property should reflect the *current* syncToken
817
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
818
+     * property. This is needed here too, to ensure the operation is atomic.
819
+     *
820
+     * If the $syncToken argument is specified as null, this is an initial
821
+     * sync, and all members should be reported.
822
+     *
823
+     * The modified property is an array of nodenames that have changed since
824
+     * the last token.
825
+     *
826
+     * The deleted property is an array with nodenames, that have been deleted
827
+     * from collection.
828
+     *
829
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
830
+     * 1, you only have to report changes that happened only directly in
831
+     * immediate descendants. If it's 2, it should also include changes from
832
+     * the nodes below the child collections. (grandchildren)
833
+     *
834
+     * The $limit argument allows a client to specify how many results should
835
+     * be returned at most. If the limit is not specified, it should be treated
836
+     * as infinite.
837
+     *
838
+     * If the limit (infinite or not) is higher than you're willing to return,
839
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
840
+     *
841
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
842
+     * return null.
843
+     *
844
+     * The limit is 'suggestive'. You are free to ignore it.
845
+     *
846
+     * @param string $addressBookId
847
+     * @param string $syncToken
848
+     * @param int $syncLevel
849
+     * @param int|null $limit
850
+     * @return array
851
+     */
852
+    public function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
853
+        // Current synctoken
854
+        return $this->atomic(function () use ($addressBookId, $syncToken, $syncLevel, $limit) {
855
+            $qb = $this->db->getQueryBuilder();
856
+            $qb->select('synctoken')
857
+                ->from('addressbooks')
858
+                ->where(
859
+                    $qb->expr()->eq('id', $qb->createNamedParameter($addressBookId))
860
+                );
861
+            $stmt = $qb->executeQuery();
862
+            $currentToken = $stmt->fetchOne();
863
+            $stmt->closeCursor();
864
+
865
+            if (is_null($currentToken)) {
866
+                return [];
867
+            }
868
+
869
+            $result = [
870
+                'syncToken' => $currentToken,
871
+                'added' => [],
872
+                'modified' => [],
873
+                'deleted' => [],
874
+            ];
875
+
876
+            if ($syncToken) {
877
+                $qb = $this->db->getQueryBuilder();
878
+                $qb->select('uri', 'operation')
879
+                    ->from('addressbookchanges')
880
+                    ->where(
881
+                        $qb->expr()->andX(
882
+                            $qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)),
883
+                            $qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)),
884
+                            $qb->expr()->eq('addressbookid', $qb->createNamedParameter($addressBookId))
885
+                        )
886
+                    )->orderBy('synctoken');
887
+
888
+                if (is_int($limit) && $limit > 0) {
889
+                    $qb->setMaxResults($limit);
890
+                }
891
+
892
+                // Fetching all changes
893
+                $stmt = $qb->executeQuery();
894
+
895
+                $changes = [];
896
+
897
+                // This loop ensures that any duplicates are overwritten, only the
898
+                // last change on a node is relevant.
899
+                while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
900
+                    $changes[$row['uri']] = $row['operation'];
901
+                }
902
+                $stmt->closeCursor();
903
+
904
+                foreach ($changes as $uri => $operation) {
905
+                    switch ($operation) {
906
+                        case 1:
907
+                            $result['added'][] = $uri;
908
+                            break;
909
+                        case 2:
910
+                            $result['modified'][] = $uri;
911
+                            break;
912
+                        case 3:
913
+                            $result['deleted'][] = $uri;
914
+                            break;
915
+                    }
916
+                }
917
+            } else {
918
+                $qb = $this->db->getQueryBuilder();
919
+                $qb->select('uri')
920
+                    ->from('cards')
921
+                    ->where(
922
+                        $qb->expr()->eq('addressbookid', $qb->createNamedParameter($addressBookId))
923
+                    );
924
+                // No synctoken supplied, this is the initial sync.
925
+                $stmt = $qb->executeQuery();
926
+                $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
927
+                $stmt->closeCursor();
928
+            }
929
+            return $result;
930
+        }, $this->db);
931
+    }
932
+
933
+    /**
934
+     * Adds a change record to the addressbookchanges table.
935
+     *
936
+     * @param mixed $addressBookId
937
+     * @param string $objectUri
938
+     * @param int $operation 1 = add, 2 = modify, 3 = delete
939
+     * @return void
940
+     */
941
+    protected function addChange(int $addressBookId, string $objectUri, int $operation): void {
942
+        $this->atomic(function () use ($addressBookId, $objectUri, $operation): void {
943
+            $query = $this->db->getQueryBuilder();
944
+            $query->select('synctoken')
945
+                ->from('addressbooks')
946
+                ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)));
947
+            $result = $query->executeQuery();
948
+            $syncToken = (int)$result->fetchOne();
949
+            $result->closeCursor();
950
+
951
+            $query = $this->db->getQueryBuilder();
952
+            $query->insert('addressbookchanges')
953
+                ->values([
954
+                    'uri' => $query->createNamedParameter($objectUri),
955
+                    'synctoken' => $query->createNamedParameter($syncToken),
956
+                    'addressbookid' => $query->createNamedParameter($addressBookId),
957
+                    'operation' => $query->createNamedParameter($operation),
958
+                    'created_at' => time(),
959
+                ])
960
+                ->executeStatement();
961
+
962
+            $query = $this->db->getQueryBuilder();
963
+            $query->update('addressbooks')
964
+                ->set('synctoken', $query->createNamedParameter($syncToken + 1, IQueryBuilder::PARAM_INT))
965
+                ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
966
+                ->executeStatement();
967
+        }, $this->db);
968
+    }
969
+
970
+    /**
971
+     * @param resource|string $cardData
972
+     * @param bool $modified
973
+     * @return string
974
+     */
975
+    private function readBlob($cardData, &$modified = false) {
976
+        if (is_resource($cardData)) {
977
+            $cardData = stream_get_contents($cardData);
978
+        }
979
+
980
+        // Micro optimisation
981
+        // don't loop through
982
+        if (str_starts_with($cardData, 'PHOTO:data:')) {
983
+            return $cardData;
984
+        }
985
+
986
+        $cardDataArray = explode("\r\n", $cardData);
987
+
988
+        $cardDataFiltered = [];
989
+        $removingPhoto = false;
990
+        foreach ($cardDataArray as $line) {
991
+            if (str_starts_with($line, 'PHOTO:data:')
992
+                && !str_starts_with($line, 'PHOTO:data:image/')) {
993
+                // Filter out PHOTO data of non-images
994
+                $removingPhoto = true;
995
+                $modified = true;
996
+                continue;
997
+            }
998
+
999
+            if ($removingPhoto) {
1000
+                if (str_starts_with($line, ' ')) {
1001
+                    continue;
1002
+                }
1003
+                // No leading space means this is a new property
1004
+                $removingPhoto = false;
1005
+            }
1006
+
1007
+            $cardDataFiltered[] = $line;
1008
+        }
1009
+        return implode("\r\n", $cardDataFiltered);
1010
+    }
1011
+
1012
+    /**
1013
+     * @param list<array{href: string, commonName: string, readOnly: bool}> $add
1014
+     * @param list<string> $remove
1015
+     */
1016
+    public function updateShares(IShareable $shareable, array $add, array $remove): void {
1017
+        $this->atomic(function () use ($shareable, $add, $remove): void {
1018
+            $addressBookId = $shareable->getResourceId();
1019
+            $addressBookData = $this->getAddressBookById($addressBookId);
1020
+            $oldShares = $this->getShares($addressBookId);
1021
+
1022
+            $this->sharingBackend->updateShares($shareable, $add, $remove, $oldShares);
1023
+
1024
+            $this->dispatcher->dispatchTyped(new AddressBookShareUpdatedEvent($addressBookId, $addressBookData, $oldShares, $add, $remove));
1025
+        }, $this->db);
1026
+    }
1027
+
1028
+    /**
1029
+     * Search contacts in a specific address-book
1030
+     *
1031
+     * @param int $addressBookId
1032
+     * @param string $pattern which should match within the $searchProperties
1033
+     * @param array $searchProperties defines the properties within the query pattern should match
1034
+     * @param array $options = array() to define the search behavior
1035
+     *                       - 'types' boolean (since 15.0.0) If set to true, fields that come with a TYPE property will be an array
1036
+     *                       - 'escape_like_param' - If set to false wildcards _ and % are not escaped, otherwise they are
1037
+     *                       - 'limit' - Set a numeric limit for the search results
1038
+     *                       - 'offset' - Set the offset for the limited search results
1039
+     *                       - 'wildcard' - Whether the search should use wildcards
1040
+     * @psalm-param array{types?: bool, escape_like_param?: bool, limit?: int, offset?: int, wildcard?: bool} $options
1041
+     * @return array an array of contacts which are arrays of key-value-pairs
1042
+     */
1043
+    public function search($addressBookId, $pattern, $searchProperties, $options = []): array {
1044
+        return $this->atomic(function () use ($addressBookId, $pattern, $searchProperties, $options) {
1045
+            return $this->searchByAddressBookIds([$addressBookId], $pattern, $searchProperties, $options);
1046
+        }, $this->db);
1047
+    }
1048
+
1049
+    /**
1050
+     * Search contacts in all address-books accessible by a user
1051
+     *
1052
+     * @param string $principalUri
1053
+     * @param string $pattern
1054
+     * @param array $searchProperties
1055
+     * @param array $options
1056
+     * @return array
1057
+     */
1058
+    public function searchPrincipalUri(string $principalUri,
1059
+        string $pattern,
1060
+        array $searchProperties,
1061
+        array $options = []): array {
1062
+        return $this->atomic(function () use ($principalUri, $pattern, $searchProperties, $options) {
1063
+            $addressBookIds = array_map(static function ($row):int {
1064
+                return (int)$row['id'];
1065
+            }, $this->getAddressBooksForUser($principalUri));
1066
+
1067
+            return $this->searchByAddressBookIds($addressBookIds, $pattern, $searchProperties, $options);
1068
+        }, $this->db);
1069
+    }
1070
+
1071
+    /**
1072
+     * @param int[] $addressBookIds
1073
+     * @param string $pattern
1074
+     * @param array $searchProperties
1075
+     * @param array $options
1076
+     * @psalm-param array{
1077
+     *   types?: bool,
1078
+     *   escape_like_param?: bool,
1079
+     *   limit?: int,
1080
+     *   offset?: int,
1081
+     *   wildcard?: bool,
1082
+     *   since?: DateTimeFilter|null,
1083
+     *   until?: DateTimeFilter|null,
1084
+     *   person?: string
1085
+     * } $options
1086
+     * @return array
1087
+     */
1088
+    private function searchByAddressBookIds(array $addressBookIds,
1089
+        string $pattern,
1090
+        array $searchProperties,
1091
+        array $options = []): array {
1092
+        if (empty($addressBookIds)) {
1093
+            return [];
1094
+        }
1095
+        $escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
1096
+        $useWildcards = !\array_key_exists('wildcard', $options) || $options['wildcard'] !== false;
1097
+
1098
+        if ($escapePattern) {
1099
+            $searchProperties = array_filter($searchProperties, function ($property) use ($pattern) {
1100
+                if ($property === 'EMAIL' && str_contains($pattern, ' ')) {
1101
+                    // There can be no spaces in emails
1102
+                    return false;
1103
+                }
1104
+
1105
+                if ($property === 'CLOUD' && preg_match('/[^a-zA-Z0-9 :_.@\/\-\']/', $pattern) === 1) {
1106
+                    // There can be no chars in cloud ids which are not valid for user ids plus :/
1107
+                    // worst case: CA61590A-BBBC-423E-84AF-E6DF01455A53@https://my.nxt/srv/
1108
+                    return false;
1109
+                }
1110
+
1111
+                return true;
1112
+            });
1113
+        }
1114
+
1115
+        if (empty($searchProperties)) {
1116
+            return [];
1117
+        }
1118
+
1119
+        $query2 = $this->db->getQueryBuilder();
1120
+        $query2->selectDistinct('cp.cardid')
1121
+            ->from($this->dbCardsPropertiesTable, 'cp')
1122
+            ->where($query2->expr()->in('cp.addressbookid', $query2->createNamedParameter($addressBookIds, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
1123
+            ->andWhere($query2->expr()->in('cp.name', $query2->createNamedParameter($searchProperties, IQueryBuilder::PARAM_STR_ARRAY)));
1124
+
1125
+        // No need for like when the pattern is empty
1126
+        if ($pattern !== '') {
1127
+            if (!$useWildcards) {
1128
+                $query2->andWhere($query2->expr()->eq('cp.value', $query2->createNamedParameter($pattern)));
1129
+            } elseif (!$escapePattern) {
1130
+                $query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter($pattern)));
1131
+            } else {
1132
+                $query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
1133
+            }
1134
+        }
1135
+        if (isset($options['limit'])) {
1136
+            $query2->setMaxResults($options['limit']);
1137
+        }
1138
+        if (isset($options['offset'])) {
1139
+            $query2->setFirstResult($options['offset']);
1140
+        }
1141
+
1142
+        if (isset($options['person'])) {
1143
+            $query2->andWhere($query2->expr()->ilike('cp.value', $query2->createNamedParameter('%' . $this->db->escapeLikeParameter($options['person']) . '%')));
1144
+        }
1145
+        if (isset($options['since']) || isset($options['until'])) {
1146
+            $query2->join('cp', $this->dbCardsPropertiesTable, 'cp_bday', 'cp.cardid = cp_bday.cardid');
1147
+            $query2->andWhere($query2->expr()->eq('cp_bday.name', $query2->createNamedParameter('BDAY')));
1148
+            /**
1149
+             * FIXME Find a way to match only 4 last digits
1150
+             * BDAY can be --1018 without year or 20001019 with it
1151
+             * $bDayOr = [];
1152
+             * if ($options['since'] instanceof DateTimeFilter) {
1153
+             * $bDayOr[] =
1154
+             * $query2->expr()->gte('SUBSTR(cp_bday.value, -4)',
1155
+             * $query2->createNamedParameter($options['since']->get()->format('md'))
1156
+             * );
1157
+             * }
1158
+             * if ($options['until'] instanceof DateTimeFilter) {
1159
+             * $bDayOr[] =
1160
+             * $query2->expr()->lte('SUBSTR(cp_bday.value, -4)',
1161
+             * $query2->createNamedParameter($options['until']->get()->format('md'))
1162
+             * );
1163
+             * }
1164
+             * $query2->andWhere($query2->expr()->orX(...$bDayOr));
1165
+             */
1166
+        }
1167
+
1168
+        $result = $query2->executeQuery();
1169
+        $matches = $result->fetchAll();
1170
+        $result->closeCursor();
1171
+        $matches = array_map(function ($match) {
1172
+            return (int)$match['cardid'];
1173
+        }, $matches);
1174
+
1175
+        $cards = [];
1176
+        $query = $this->db->getQueryBuilder();
1177
+        $query->select('c.addressbookid', 'c.carddata', 'c.uri')
1178
+            ->from($this->dbCardsTable, 'c')
1179
+            ->where($query->expr()->in('c.id', $query->createParameter('matches')));
1180
+
1181
+        foreach (array_chunk($matches, 1000) as $matchesChunk) {
1182
+            $query->setParameter('matches', $matchesChunk, IQueryBuilder::PARAM_INT_ARRAY);
1183
+            $result = $query->executeQuery();
1184
+            $cards = array_merge($cards, $result->fetchAll());
1185
+            $result->closeCursor();
1186
+        }
1187
+
1188
+        return array_map(function ($array) {
1189
+            $array['addressbookid'] = (int)$array['addressbookid'];
1190
+            $modified = false;
1191
+            $array['carddata'] = $this->readBlob($array['carddata'], $modified);
1192
+            if ($modified) {
1193
+                $array['size'] = strlen($array['carddata']);
1194
+            }
1195
+            return $array;
1196
+        }, $cards);
1197
+    }
1198
+
1199
+    /**
1200
+     * @param int $bookId
1201
+     * @param string $name
1202
+     * @return array
1203
+     */
1204
+    public function collectCardProperties($bookId, $name) {
1205
+        $query = $this->db->getQueryBuilder();
1206
+        $result = $query->selectDistinct('value')
1207
+            ->from($this->dbCardsPropertiesTable)
1208
+            ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
1209
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
1210
+            ->executeQuery();
1211
+
1212
+        $all = $result->fetchAll(PDO::FETCH_COLUMN);
1213
+        $result->closeCursor();
1214
+
1215
+        return $all;
1216
+    }
1217
+
1218
+    /**
1219
+     * get URI from a given contact
1220
+     *
1221
+     * @param int $id
1222
+     * @return string
1223
+     */
1224
+    public function getCardUri($id) {
1225
+        $query = $this->db->getQueryBuilder();
1226
+        $query->select('uri')->from($this->dbCardsTable)
1227
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
1228
+            ->setParameter('id', $id);
1229
+
1230
+        $result = $query->executeQuery();
1231
+        $uri = $result->fetch();
1232
+        $result->closeCursor();
1233
+
1234
+        if (!isset($uri['uri'])) {
1235
+            throw new \InvalidArgumentException('Card does not exists: ' . $id);
1236
+        }
1237
+
1238
+        return $uri['uri'];
1239
+    }
1240
+
1241
+    /**
1242
+     * return contact with the given URI
1243
+     *
1244
+     * @param int $addressBookId
1245
+     * @param string $uri
1246
+     * @returns array
1247
+     */
1248
+    public function getContact($addressBookId, $uri) {
1249
+        $result = [];
1250
+        $query = $this->db->getQueryBuilder();
1251
+        $query->select('*')->from($this->dbCardsTable)
1252
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1253
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1254
+        $queryResult = $query->executeQuery();
1255
+        $contact = $queryResult->fetch();
1256
+        $queryResult->closeCursor();
1257
+
1258
+        if (is_array($contact)) {
1259
+            $modified = false;
1260
+            $contact['etag'] = '"' . $contact['etag'] . '"';
1261
+            $contact['carddata'] = $this->readBlob($contact['carddata'], $modified);
1262
+            if ($modified) {
1263
+                $contact['size'] = strlen($contact['carddata']);
1264
+            }
1265
+
1266
+            $result = $contact;
1267
+        }
1268
+
1269
+        return $result;
1270
+    }
1271
+
1272
+    /**
1273
+     * Returns the list of people whom this address book is shared with.
1274
+     *
1275
+     * Every element in this array should have the following properties:
1276
+     *   * href - Often a mailto: address
1277
+     *   * commonName - Optional, for example a first + last name
1278
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
1279
+     *   * readOnly - boolean
1280
+     *
1281
+     * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
1282
+     */
1283
+    public function getShares(int $addressBookId): array {
1284
+        return $this->sharingBackend->getShares($addressBookId);
1285
+    }
1286
+
1287
+    /**
1288
+     * update properties table
1289
+     *
1290
+     * @param int $addressBookId
1291
+     * @param string $cardUri
1292
+     * @param string $vCardSerialized
1293
+     */
1294
+    protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
1295
+        $this->atomic(function () use ($addressBookId, $cardUri, $vCardSerialized): void {
1296
+            $cardId = $this->getCardId($addressBookId, $cardUri);
1297
+            $vCard = $this->readCard($vCardSerialized);
1298
+
1299
+            $this->purgeProperties($addressBookId, $cardId);
1300
+
1301
+            $query = $this->db->getQueryBuilder();
1302
+            $query->insert($this->dbCardsPropertiesTable)
1303
+                ->values(
1304
+                    [
1305
+                        'addressbookid' => $query->createNamedParameter($addressBookId),
1306
+                        'cardid' => $query->createNamedParameter($cardId),
1307
+                        'name' => $query->createParameter('name'),
1308
+                        'value' => $query->createParameter('value'),
1309
+                        'preferred' => $query->createParameter('preferred')
1310
+                    ]
1311
+                );
1312
+
1313
+            foreach ($vCard->children() as $property) {
1314
+                if (!in_array($property->name, self::$indexProperties)) {
1315
+                    continue;
1316
+                }
1317
+                $preferred = 0;
1318
+                foreach ($property->parameters as $parameter) {
1319
+                    if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1320
+                        $preferred = 1;
1321
+                        break;
1322
+                    }
1323
+                }
1324
+                $query->setParameter('name', $property->name);
1325
+                $query->setParameter('value', mb_strcut($property->getValue(), 0, 254));
1326
+                $query->setParameter('preferred', $preferred);
1327
+                $query->executeStatement();
1328
+            }
1329
+        }, $this->db);
1330
+    }
1331
+
1332
+    /**
1333
+     * read vCard data into a vCard object
1334
+     *
1335
+     * @param string $cardData
1336
+     * @return VCard
1337
+     */
1338
+    protected function readCard($cardData) {
1339
+        return Reader::read($cardData);
1340
+    }
1341
+
1342
+    /**
1343
+     * delete all properties from a given card
1344
+     *
1345
+     * @param int $addressBookId
1346
+     * @param int $cardId
1347
+     */
1348
+    protected function purgeProperties($addressBookId, $cardId) {
1349
+        $query = $this->db->getQueryBuilder();
1350
+        $query->delete($this->dbCardsPropertiesTable)
1351
+            ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1352
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1353
+        $query->executeStatement();
1354
+    }
1355
+
1356
+    /**
1357
+     * Get ID from a given contact
1358
+     */
1359
+    protected function getCardId(int $addressBookId, string $uri): int {
1360
+        $query = $this->db->getQueryBuilder();
1361
+        $query->select('id')->from($this->dbCardsTable)
1362
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1363
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1364
+
1365
+        $result = $query->executeQuery();
1366
+        $cardIds = $result->fetch();
1367
+        $result->closeCursor();
1368
+
1369
+        if (!isset($cardIds['id'])) {
1370
+            throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1371
+        }
1372
+
1373
+        return (int)$cardIds['id'];
1374
+    }
1375
+
1376
+    /**
1377
+     * For shared address books the sharee is set in the ACL of the address book
1378
+     *
1379
+     * @param int $addressBookId
1380
+     * @param list<array{privilege: string, principal: string, protected: bool}> $acl
1381
+     * @return list<array{privilege: string, principal: string, protected: bool}>
1382
+     */
1383
+    public function applyShareAcl(int $addressBookId, array $acl): array {
1384
+        $shares = $this->sharingBackend->getShares($addressBookId);
1385
+        return $this->sharingBackend->applyShareAcl($shares, $acl);
1386
+    }
1387
+
1388
+    /**
1389
+     * @throws \InvalidArgumentException
1390
+     */
1391
+    public function pruneOutdatedSyncTokens(int $keep, int $retention): int {
1392
+        if ($keep < 0) {
1393
+            throw new \InvalidArgumentException();
1394
+        }
1395
+
1396
+        $query = $this->db->getQueryBuilder();
1397
+        $query->select($query->func()->max('id'))
1398
+            ->from('addressbookchanges');
1399
+
1400
+        $result = $query->executeQuery();
1401
+        $maxId = (int)$result->fetchOne();
1402
+        $result->closeCursor();
1403
+        if (!$maxId || $maxId < $keep) {
1404
+            return 0;
1405
+        }
1406
+
1407
+        $query = $this->db->getQueryBuilder();
1408
+        $query->delete('addressbookchanges')
1409
+            ->where(
1410
+                $query->expr()->lte('id', $query->createNamedParameter($maxId - $keep, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
1411
+                $query->expr()->lte('created_at', $query->createNamedParameter($retention)),
1412
+            );
1413
+        return $query->executeStatement();
1414
+    }
1415
+
1416
+    private function convertPrincipal(string $principalUri, bool $toV2): string {
1417
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1418
+            [, $name] = \Sabre\Uri\split($principalUri);
1419
+            if ($toV2 === true) {
1420
+                return "principals/users/$name";
1421
+            }
1422
+            return "principals/$name";
1423
+        }
1424
+        return $principalUri;
1425
+    }
1426
+
1427
+    private function addOwnerPrincipal(array &$addressbookInfo): void {
1428
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1429
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1430
+        if (isset($addressbookInfo[$ownerPrincipalKey])) {
1431
+            $uri = $addressbookInfo[$ownerPrincipalKey];
1432
+        } else {
1433
+            $uri = $addressbookInfo['principaluri'];
1434
+        }
1435
+
1436
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1437
+        if (isset($principalInformation['{DAV:}displayname'])) {
1438
+            $addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1439
+        }
1440
+    }
1441
+
1442
+    /**
1443
+     * Extract UID from vcard
1444
+     *
1445
+     * @param string $cardData the vcard raw data
1446
+     * @return string the uid
1447
+     * @throws BadRequest if no UID is available or vcard is empty
1448
+     */
1449
+    private function getUID(string $cardData): string {
1450
+        if ($cardData !== '') {
1451
+            $vCard = Reader::read($cardData);
1452
+            if ($vCard->UID) {
1453
+                $uid = $vCard->UID->getValue();
1454
+                return $uid;
1455
+            }
1456
+            // should already be handled, but just in case
1457
+            throw new BadRequest('vCards on CardDAV servers MUST have a UID property');
1458
+        }
1459
+        // should already be handled, but just in case
1460
+        throw new BadRequest('vCard can not be empty');
1461
+    }
1462 1462
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 1 patch
Indentation   +3581 added lines, -3581 removed lines patch added patch discarded remove patch
@@ -106,3585 +106,3585 @@
 block discarded – undo
106 106
  * }
107 107
  */
108 108
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
109
-	use TTransactional;
110
-
111
-	public const CALENDAR_TYPE_CALENDAR = 0;
112
-	public const CALENDAR_TYPE_SUBSCRIPTION = 1;
113
-
114
-	public const PERSONAL_CALENDAR_URI = 'personal';
115
-	public const PERSONAL_CALENDAR_NAME = 'Personal';
116
-
117
-	public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
118
-	public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
119
-
120
-	/**
121
-	 * We need to specify a max date, because we need to stop *somewhere*
122
-	 *
123
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
124
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
125
-	 * in 2038-01-19 to avoid problems when the date is converted
126
-	 * to a unix timestamp.
127
-	 */
128
-	public const MAX_DATE = '2038-01-01';
129
-
130
-	public const ACCESS_PUBLIC = 4;
131
-	public const CLASSIFICATION_PUBLIC = 0;
132
-	public const CLASSIFICATION_PRIVATE = 1;
133
-	public const CLASSIFICATION_CONFIDENTIAL = 2;
134
-
135
-	/**
136
-	 * List of CalDAV properties, and how they map to database field names and their type
137
-	 * Add your own properties by simply adding on to this array.
138
-	 *
139
-	 * @var array
140
-	 * @psalm-var array<string, string[]>
141
-	 */
142
-	public array $propertyMap = [
143
-		'{DAV:}displayname' => ['displayname', 'string'],
144
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => ['description', 'string'],
145
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone' => ['timezone', 'string'],
146
-		'{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
147
-		'{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
148
-		'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => ['deleted_at', 'int'],
149
-	];
150
-
151
-	/**
152
-	 * List of subscription properties, and how they map to database field names.
153
-	 *
154
-	 * @var array
155
-	 */
156
-	public array $subscriptionPropertyMap = [
157
-		'{DAV:}displayname' => ['displayname', 'string'],
158
-		'{http://apple.com/ns/ical/}refreshrate' => ['refreshrate', 'string'],
159
-		'{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
160
-		'{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
161
-		'{http://calendarserver.org/ns/}subscribed-strip-todos' => ['striptodos', 'bool'],
162
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms' => ['stripalarms', 'string'],
163
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => ['stripattachments', 'string'],
164
-	];
165
-
166
-	/**
167
-	 * properties to index
168
-	 *
169
-	 * This list has to be kept in sync with ICalendarQuery::SEARCH_PROPERTY_*
170
-	 *
171
-	 * @see \OCP\Calendar\ICalendarQuery
172
-	 */
173
-	private const INDEXED_PROPERTIES = [
174
-		'CATEGORIES',
175
-		'COMMENT',
176
-		'DESCRIPTION',
177
-		'LOCATION',
178
-		'RESOURCES',
179
-		'STATUS',
180
-		'SUMMARY',
181
-		'ATTENDEE',
182
-		'CONTACT',
183
-		'ORGANIZER'
184
-	];
185
-
186
-	/** @var array parameters to index */
187
-	public static array $indexParameters = [
188
-		'ATTENDEE' => ['CN'],
189
-		'ORGANIZER' => ['CN'],
190
-	];
191
-
192
-	/**
193
-	 * @var string[] Map of uid => display name
194
-	 */
195
-	protected array $userDisplayNames;
196
-
197
-	private string $dbObjectsTable = 'calendarobjects';
198
-	private string $dbObjectPropertiesTable = 'calendarobjects_props';
199
-	private string $dbObjectInvitationsTable = 'calendar_invitations';
200
-	private array $cachedObjects = [];
201
-
202
-	public function __construct(
203
-		private IDBConnection $db,
204
-		private Principal $principalBackend,
205
-		private IUserManager $userManager,
206
-		private ISecureRandom $random,
207
-		private LoggerInterface $logger,
208
-		private IEventDispatcher $dispatcher,
209
-		private IConfig $config,
210
-		private Sharing\Backend $calendarSharingBackend,
211
-		private bool $legacyEndpoint = false,
212
-	) {
213
-	}
214
-
215
-	/**
216
-	 * Return the number of calendars owned by the given principal.
217
-	 *
218
-	 * Calendars shared with the given principal are not counted!
219
-	 *
220
-	 * By default, this excludes the automatically generated birthday calendar.
221
-	 */
222
-	public function getCalendarsForUserCount(string $principalUri, bool $excludeBirthday = true): int {
223
-		$principalUri = $this->convertPrincipal($principalUri, true);
224
-		$query = $this->db->getQueryBuilder();
225
-		$query->select($query->func()->count('*'))
226
-			->from('calendars');
227
-
228
-		if ($principalUri === '') {
229
-			$query->where($query->expr()->emptyString('principaluri'));
230
-		} else {
231
-			$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
232
-		}
233
-
234
-		if ($excludeBirthday) {
235
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
236
-		}
237
-
238
-		$result = $query->executeQuery();
239
-		$column = (int)$result->fetchOne();
240
-		$result->closeCursor();
241
-		return $column;
242
-	}
243
-
244
-	/**
245
-	 * Return the number of subscriptions for a principal
246
-	 */
247
-	public function getSubscriptionsForUserCount(string $principalUri): int {
248
-		$principalUri = $this->convertPrincipal($principalUri, true);
249
-		$query = $this->db->getQueryBuilder();
250
-		$query->select($query->func()->count('*'))
251
-			->from('calendarsubscriptions');
252
-
253
-		if ($principalUri === '') {
254
-			$query->where($query->expr()->emptyString('principaluri'));
255
-		} else {
256
-			$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
257
-		}
258
-
259
-		$result = $query->executeQuery();
260
-		$column = (int)$result->fetchOne();
261
-		$result->closeCursor();
262
-		return $column;
263
-	}
264
-
265
-	/**
266
-	 * @return array{id: int, deleted_at: int}[]
267
-	 */
268
-	public function getDeletedCalendars(int $deletedBefore): array {
269
-		$qb = $this->db->getQueryBuilder();
270
-		$qb->select(['id', 'deleted_at'])
271
-			->from('calendars')
272
-			->where($qb->expr()->isNotNull('deleted_at'))
273
-			->andWhere($qb->expr()->lt('deleted_at', $qb->createNamedParameter($deletedBefore)));
274
-		$result = $qb->executeQuery();
275
-		$calendars = [];
276
-		while (($row = $result->fetch()) !== false) {
277
-			$calendars[] = [
278
-				'id' => (int)$row['id'],
279
-				'deleted_at' => (int)$row['deleted_at'],
280
-			];
281
-		}
282
-		$result->closeCursor();
283
-		return $calendars;
284
-	}
285
-
286
-	/**
287
-	 * Returns a list of calendars for a principal.
288
-	 *
289
-	 * Every project is an array with the following keys:
290
-	 *  * id, a unique id that will be used by other functions to modify the
291
-	 *    calendar. This can be the same as the uri or a database key.
292
-	 *  * uri, which the basename of the uri with which the calendar is
293
-	 *    accessed.
294
-	 *  * principaluri. The owner of the calendar. Almost always the same as
295
-	 *    principalUri passed to this method.
296
-	 *
297
-	 * Furthermore it can contain webdav properties in clark notation. A very
298
-	 * common one is '{DAV:}displayname'.
299
-	 *
300
-	 * Many clients also require:
301
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
302
-	 * For this property, you can just return an instance of
303
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
304
-	 *
305
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
306
-	 * ACL will automatically be put in read-only mode.
307
-	 *
308
-	 * @param string $principalUri
309
-	 * @return array
310
-	 */
311
-	public function getCalendarsForUser($principalUri) {
312
-		return $this->atomic(function () use ($principalUri) {
313
-			$principalUriOriginal = $principalUri;
314
-			$principalUri = $this->convertPrincipal($principalUri, true);
315
-			$fields = array_column($this->propertyMap, 0);
316
-			$fields[] = 'id';
317
-			$fields[] = 'uri';
318
-			$fields[] = 'synctoken';
319
-			$fields[] = 'components';
320
-			$fields[] = 'principaluri';
321
-			$fields[] = 'transparent';
322
-
323
-			// Making fields a comma-delimited list
324
-			$query = $this->db->getQueryBuilder();
325
-			$query->select($fields)
326
-				->from('calendars')
327
-				->orderBy('calendarorder', 'ASC');
328
-
329
-			if ($principalUri === '') {
330
-				$query->where($query->expr()->emptyString('principaluri'));
331
-			} else {
332
-				$query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
333
-			}
334
-
335
-			$result = $query->executeQuery();
336
-
337
-			$calendars = [];
338
-			while ($row = $result->fetch()) {
339
-				$row['principaluri'] = (string)$row['principaluri'];
340
-				$components = [];
341
-				if ($row['components']) {
342
-					$components = explode(',', $row['components']);
343
-				}
344
-
345
-				$calendar = [
346
-					'id' => $row['id'],
347
-					'uri' => $row['uri'],
348
-					'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
349
-					'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
350
-					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
351
-					'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
352
-					'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
353
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
354
-				];
355
-
356
-				$calendar = $this->rowToCalendar($row, $calendar);
357
-				$calendar = $this->addOwnerPrincipalToCalendar($calendar);
358
-				$calendar = $this->addResourceTypeToCalendar($row, $calendar);
359
-
360
-				if (!isset($calendars[$calendar['id']])) {
361
-					$calendars[$calendar['id']] = $calendar;
362
-				}
363
-			}
364
-			$result->closeCursor();
365
-
366
-			// query for shared calendars
367
-			$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
368
-			$principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
369
-			$principals[] = $principalUri;
370
-
371
-			$fields = array_column($this->propertyMap, 0);
372
-			$fields = array_map(function (string $field) {
373
-				return 'a.' . $field;
374
-			}, $fields);
375
-			$fields[] = 'a.id';
376
-			$fields[] = 'a.uri';
377
-			$fields[] = 'a.synctoken';
378
-			$fields[] = 'a.components';
379
-			$fields[] = 'a.principaluri';
380
-			$fields[] = 'a.transparent';
381
-			$fields[] = 's.access';
382
-
383
-			$select = $this->db->getQueryBuilder();
384
-			$subSelect = $this->db->getQueryBuilder();
385
-
386
-			$subSelect->select('resourceid')
387
-				->from('dav_shares', 'd')
388
-				->where($subSelect->expr()->eq('d.access', $select->createNamedParameter(Backend::ACCESS_UNSHARED, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
389
-				->andWhere($subSelect->expr()->in('d.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY));
390
-
391
-			$select->select($fields)
392
-				->from('dav_shares', 's')
393
-				->join('s', 'calendars', 'a', $select->expr()->eq('s.resourceid', 'a.id', IQueryBuilder::PARAM_INT))
394
-				->where($select->expr()->in('s.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
395
-				->andWhere($select->expr()->eq('s.type', $select->createNamedParameter('calendar', IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR))
396
-				->andWhere($select->expr()->notIn('a.id', $select->createFunction($subSelect->getSQL()), IQueryBuilder::PARAM_INT_ARRAY));
397
-
398
-			$results = $select->executeQuery();
399
-
400
-			$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
401
-			while ($row = $results->fetch()) {
402
-				$row['principaluri'] = (string)$row['principaluri'];
403
-				if ($row['principaluri'] === $principalUri) {
404
-					continue;
405
-				}
406
-
407
-				$readOnly = (int)$row['access'] === Backend::ACCESS_READ;
408
-				if (isset($calendars[$row['id']])) {
409
-					if ($readOnly) {
410
-						// New share can not have more permissions than the old one.
411
-						continue;
412
-					}
413
-					if (isset($calendars[$row['id']][$readOnlyPropertyName])
414
-						&& $calendars[$row['id']][$readOnlyPropertyName] === 0) {
415
-						// Old share is already read-write, no more permissions can be gained
416
-						continue;
417
-					}
418
-				}
419
-
420
-				[, $name] = Uri\split($row['principaluri']);
421
-				$uri = $row['uri'] . '_shared_by_' . $name;
422
-				$row['displayname'] = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? ($name ?? '')) . ')';
423
-				$components = [];
424
-				if ($row['components']) {
425
-					$components = explode(',', $row['components']);
426
-				}
427
-				$calendar = [
428
-					'id' => $row['id'],
429
-					'uri' => $uri,
430
-					'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
431
-					'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
432
-					'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
433
-					'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
434
-					'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
435
-					'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
436
-					$readOnlyPropertyName => $readOnly,
437
-				];
438
-
439
-				$calendar = $this->rowToCalendar($row, $calendar);
440
-				$calendar = $this->addOwnerPrincipalToCalendar($calendar);
441
-				$calendar = $this->addResourceTypeToCalendar($row, $calendar);
442
-
443
-				$calendars[$calendar['id']] = $calendar;
444
-			}
445
-			$result->closeCursor();
446
-
447
-			return array_values($calendars);
448
-		}, $this->db);
449
-	}
450
-
451
-	/**
452
-	 * @param $principalUri
453
-	 * @return array
454
-	 */
455
-	public function getUsersOwnCalendars($principalUri) {
456
-		$principalUri = $this->convertPrincipal($principalUri, true);
457
-		$fields = array_column($this->propertyMap, 0);
458
-		$fields[] = 'id';
459
-		$fields[] = 'uri';
460
-		$fields[] = 'synctoken';
461
-		$fields[] = 'components';
462
-		$fields[] = 'principaluri';
463
-		$fields[] = 'transparent';
464
-		// Making fields a comma-delimited list
465
-		$query = $this->db->getQueryBuilder();
466
-		$query->select($fields)->from('calendars')
467
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
468
-			->orderBy('calendarorder', 'ASC');
469
-		$stmt = $query->executeQuery();
470
-		$calendars = [];
471
-		while ($row = $stmt->fetch()) {
472
-			$row['principaluri'] = (string)$row['principaluri'];
473
-			$components = [];
474
-			if ($row['components']) {
475
-				$components = explode(',', $row['components']);
476
-			}
477
-			$calendar = [
478
-				'id' => $row['id'],
479
-				'uri' => $row['uri'],
480
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
481
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
482
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
483
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
484
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
485
-			];
486
-
487
-			$calendar = $this->rowToCalendar($row, $calendar);
488
-			$calendar = $this->addOwnerPrincipalToCalendar($calendar);
489
-			$calendar = $this->addResourceTypeToCalendar($row, $calendar);
490
-
491
-			if (!isset($calendars[$calendar['id']])) {
492
-				$calendars[$calendar['id']] = $calendar;
493
-			}
494
-		}
495
-		$stmt->closeCursor();
496
-		return array_values($calendars);
497
-	}
498
-
499
-	/**
500
-	 * @return array
501
-	 */
502
-	public function getPublicCalendars() {
503
-		$fields = array_column($this->propertyMap, 0);
504
-		$fields[] = 'a.id';
505
-		$fields[] = 'a.uri';
506
-		$fields[] = 'a.synctoken';
507
-		$fields[] = 'a.components';
508
-		$fields[] = 'a.principaluri';
509
-		$fields[] = 'a.transparent';
510
-		$fields[] = 's.access';
511
-		$fields[] = 's.publicuri';
512
-		$calendars = [];
513
-		$query = $this->db->getQueryBuilder();
514
-		$result = $query->select($fields)
515
-			->from('dav_shares', 's')
516
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
517
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
518
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
519
-			->executeQuery();
520
-
521
-		while ($row = $result->fetch()) {
522
-			$row['principaluri'] = (string)$row['principaluri'];
523
-			[, $name] = Uri\split($row['principaluri']);
524
-			$row['displayname'] = $row['displayname'] . "($name)";
525
-			$components = [];
526
-			if ($row['components']) {
527
-				$components = explode(',', $row['components']);
528
-			}
529
-			$calendar = [
530
-				'id' => $row['id'],
531
-				'uri' => $row['publicuri'],
532
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
533
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
534
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
535
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
536
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
537
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
538
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
539
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
540
-			];
541
-
542
-			$calendar = $this->rowToCalendar($row, $calendar);
543
-			$calendar = $this->addOwnerPrincipalToCalendar($calendar);
544
-			$calendar = $this->addResourceTypeToCalendar($row, $calendar);
545
-
546
-			if (!isset($calendars[$calendar['id']])) {
547
-				$calendars[$calendar['id']] = $calendar;
548
-			}
549
-		}
550
-		$result->closeCursor();
551
-
552
-		return array_values($calendars);
553
-	}
554
-
555
-	/**
556
-	 * @param string $uri
557
-	 * @return array
558
-	 * @throws NotFound
559
-	 */
560
-	public function getPublicCalendar($uri) {
561
-		$fields = array_column($this->propertyMap, 0);
562
-		$fields[] = 'a.id';
563
-		$fields[] = 'a.uri';
564
-		$fields[] = 'a.synctoken';
565
-		$fields[] = 'a.components';
566
-		$fields[] = 'a.principaluri';
567
-		$fields[] = 'a.transparent';
568
-		$fields[] = 's.access';
569
-		$fields[] = 's.publicuri';
570
-		$query = $this->db->getQueryBuilder();
571
-		$result = $query->select($fields)
572
-			->from('dav_shares', 's')
573
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
574
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
575
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
576
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
577
-			->executeQuery();
578
-
579
-		$row = $result->fetch();
580
-
581
-		$result->closeCursor();
582
-
583
-		if ($row === false) {
584
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
585
-		}
586
-
587
-		$row['principaluri'] = (string)$row['principaluri'];
588
-		[, $name] = Uri\split($row['principaluri']);
589
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
590
-		$components = [];
591
-		if ($row['components']) {
592
-			$components = explode(',', $row['components']);
593
-		}
594
-		$calendar = [
595
-			'id' => $row['id'],
596
-			'uri' => $row['publicuri'],
597
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
598
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
599
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
600
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
601
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
602
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
603
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
604
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
605
-		];
606
-
607
-		$calendar = $this->rowToCalendar($row, $calendar);
608
-		$calendar = $this->addOwnerPrincipalToCalendar($calendar);
609
-		$calendar = $this->addResourceTypeToCalendar($row, $calendar);
610
-
611
-		return $calendar;
612
-	}
613
-
614
-	/**
615
-	 * @param string $principal
616
-	 * @param string $uri
617
-	 * @return array|null
618
-	 */
619
-	public function getCalendarByUri($principal, $uri) {
620
-		$fields = array_column($this->propertyMap, 0);
621
-		$fields[] = 'id';
622
-		$fields[] = 'uri';
623
-		$fields[] = 'synctoken';
624
-		$fields[] = 'components';
625
-		$fields[] = 'principaluri';
626
-		$fields[] = 'transparent';
627
-
628
-		// Making fields a comma-delimited list
629
-		$query = $this->db->getQueryBuilder();
630
-		$query->select($fields)->from('calendars')
631
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
632
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
633
-			->setMaxResults(1);
634
-		$stmt = $query->executeQuery();
635
-
636
-		$row = $stmt->fetch();
637
-		$stmt->closeCursor();
638
-		if ($row === false) {
639
-			return null;
640
-		}
641
-
642
-		$row['principaluri'] = (string)$row['principaluri'];
643
-		$components = [];
644
-		if ($row['components']) {
645
-			$components = explode(',', $row['components']);
646
-		}
647
-
648
-		$calendar = [
649
-			'id' => $row['id'],
650
-			'uri' => $row['uri'],
651
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
652
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
653
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
654
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
655
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
656
-		];
657
-
658
-		$calendar = $this->rowToCalendar($row, $calendar);
659
-		$calendar = $this->addOwnerPrincipalToCalendar($calendar);
660
-		$calendar = $this->addResourceTypeToCalendar($row, $calendar);
661
-
662
-		return $calendar;
663
-	}
664
-
665
-	/**
666
-	 * @psalm-return CalendarInfo|null
667
-	 * @return array|null
668
-	 */
669
-	public function getCalendarById(int $calendarId): ?array {
670
-		$fields = array_column($this->propertyMap, 0);
671
-		$fields[] = 'id';
672
-		$fields[] = 'uri';
673
-		$fields[] = 'synctoken';
674
-		$fields[] = 'components';
675
-		$fields[] = 'principaluri';
676
-		$fields[] = 'transparent';
677
-
678
-		// Making fields a comma-delimited list
679
-		$query = $this->db->getQueryBuilder();
680
-		$query->select($fields)->from('calendars')
681
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
682
-			->setMaxResults(1);
683
-		$stmt = $query->executeQuery();
684
-
685
-		$row = $stmt->fetch();
686
-		$stmt->closeCursor();
687
-		if ($row === false) {
688
-			return null;
689
-		}
690
-
691
-		$row['principaluri'] = (string)$row['principaluri'];
692
-		$components = [];
693
-		if ($row['components']) {
694
-			$components = explode(',', $row['components']);
695
-		}
696
-
697
-		$calendar = [
698
-			'id' => $row['id'],
699
-			'uri' => $row['uri'],
700
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
701
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
702
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?? 0,
703
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
704
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
705
-		];
706
-
707
-		$calendar = $this->rowToCalendar($row, $calendar);
708
-		$calendar = $this->addOwnerPrincipalToCalendar($calendar);
709
-		$calendar = $this->addResourceTypeToCalendar($row, $calendar);
710
-
711
-		return $calendar;
712
-	}
713
-
714
-	/**
715
-	 * @param $subscriptionId
716
-	 */
717
-	public function getSubscriptionById($subscriptionId) {
718
-		$fields = array_column($this->subscriptionPropertyMap, 0);
719
-		$fields[] = 'id';
720
-		$fields[] = 'uri';
721
-		$fields[] = 'source';
722
-		$fields[] = 'synctoken';
723
-		$fields[] = 'principaluri';
724
-		$fields[] = 'lastmodified';
725
-
726
-		$query = $this->db->getQueryBuilder();
727
-		$query->select($fields)
728
-			->from('calendarsubscriptions')
729
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
730
-			->orderBy('calendarorder', 'asc');
731
-		$stmt = $query->executeQuery();
732
-
733
-		$row = $stmt->fetch();
734
-		$stmt->closeCursor();
735
-		if ($row === false) {
736
-			return null;
737
-		}
738
-
739
-		$row['principaluri'] = (string)$row['principaluri'];
740
-		$subscription = [
741
-			'id' => $row['id'],
742
-			'uri' => $row['uri'],
743
-			'principaluri' => $row['principaluri'],
744
-			'source' => $row['source'],
745
-			'lastmodified' => $row['lastmodified'],
746
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
747
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
748
-		];
749
-
750
-		return $this->rowToSubscription($row, $subscription);
751
-	}
752
-
753
-	public function getSubscriptionByUri(string $principal, string $uri): ?array {
754
-		$fields = array_column($this->subscriptionPropertyMap, 0);
755
-		$fields[] = 'id';
756
-		$fields[] = 'uri';
757
-		$fields[] = 'source';
758
-		$fields[] = 'synctoken';
759
-		$fields[] = 'principaluri';
760
-		$fields[] = 'lastmodified';
761
-
762
-		$query = $this->db->getQueryBuilder();
763
-		$query->select($fields)
764
-			->from('calendarsubscriptions')
765
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
766
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
767
-			->setMaxResults(1);
768
-		$stmt = $query->executeQuery();
769
-
770
-		$row = $stmt->fetch();
771
-		$stmt->closeCursor();
772
-		if ($row === false) {
773
-			return null;
774
-		}
775
-
776
-		$row['principaluri'] = (string)$row['principaluri'];
777
-		$subscription = [
778
-			'id' => $row['id'],
779
-			'uri' => $row['uri'],
780
-			'principaluri' => $row['principaluri'],
781
-			'source' => $row['source'],
782
-			'lastmodified' => $row['lastmodified'],
783
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
784
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
785
-		];
786
-
787
-		return $this->rowToSubscription($row, $subscription);
788
-	}
789
-
790
-	/**
791
-	 * Creates a new calendar for a principal.
792
-	 *
793
-	 * If the creation was a success, an id must be returned that can be used to reference
794
-	 * this calendar in other methods, such as updateCalendar.
795
-	 *
796
-	 * @param string $principalUri
797
-	 * @param string $calendarUri
798
-	 * @param array $properties
799
-	 * @return int
800
-	 *
801
-	 * @throws CalendarException
802
-	 */
803
-	public function createCalendar($principalUri, $calendarUri, array $properties) {
804
-		if (strlen($calendarUri) > 255) {
805
-			throw new CalendarException('URI too long. Calendar not created');
806
-		}
807
-
808
-		$values = [
809
-			'principaluri' => $this->convertPrincipal($principalUri, true),
810
-			'uri' => $calendarUri,
811
-			'synctoken' => 1,
812
-			'transparent' => 0,
813
-			'components' => 'VEVENT,VTODO,VJOURNAL',
814
-			'displayname' => $calendarUri
815
-		];
816
-
817
-		// Default value
818
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
819
-		if (isset($properties[$sccs])) {
820
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
821
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
822
-			}
823
-			$values['components'] = implode(',', $properties[$sccs]->getValue());
824
-		} elseif (isset($properties['components'])) {
825
-			// Allow to provide components internally without having
826
-			// to create a SupportedCalendarComponentSet object
827
-			$values['components'] = $properties['components'];
828
-		}
829
-
830
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
831
-		if (isset($properties[$transp])) {
832
-			$values['transparent'] = (int)($properties[$transp]->getValue() === 'transparent');
833
-		}
834
-
835
-		foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
836
-			if (isset($properties[$xmlName])) {
837
-				$values[$dbName] = $properties[$xmlName];
838
-			}
839
-		}
840
-
841
-		[$calendarId, $calendarData] = $this->atomic(function () use ($values) {
842
-			$query = $this->db->getQueryBuilder();
843
-			$query->insert('calendars');
844
-			foreach ($values as $column => $value) {
845
-				$query->setValue($column, $query->createNamedParameter($value));
846
-			}
847
-			$query->executeStatement();
848
-			$calendarId = $query->getLastInsertId();
849
-
850
-			$calendarData = $this->getCalendarById($calendarId);
851
-			return [$calendarId, $calendarData];
852
-		}, $this->db);
853
-
854
-		$this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
855
-
856
-		return $calendarId;
857
-	}
858
-
859
-	/**
860
-	 * Updates properties for a calendar.
861
-	 *
862
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
863
-	 * To do the actual updates, you must tell this object which properties
864
-	 * you're going to process with the handle() method.
865
-	 *
866
-	 * Calling the handle method is like telling the PropPatch object "I
867
-	 * promise I can handle updating this property".
868
-	 *
869
-	 * Read the PropPatch documentation for more info and examples.
870
-	 *
871
-	 * @param mixed $calendarId
872
-	 * @param PropPatch $propPatch
873
-	 * @return void
874
-	 */
875
-	public function updateCalendar($calendarId, PropPatch $propPatch) {
876
-		$supportedProperties = array_keys($this->propertyMap);
877
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
878
-
879
-		$propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
880
-			$newValues = [];
881
-			foreach ($mutations as $propertyName => $propertyValue) {
882
-				switch ($propertyName) {
883
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
884
-						$fieldName = 'transparent';
885
-						$newValues[$fieldName] = (int)($propertyValue->getValue() === 'transparent');
886
-						break;
887
-					default:
888
-						$fieldName = $this->propertyMap[$propertyName][0];
889
-						$newValues[$fieldName] = $propertyValue;
890
-						break;
891
-				}
892
-			}
893
-			[$calendarData, $shares] = $this->atomic(function () use ($calendarId, $newValues) {
894
-				$query = $this->db->getQueryBuilder();
895
-				$query->update('calendars');
896
-				foreach ($newValues as $fieldName => $value) {
897
-					$query->set($fieldName, $query->createNamedParameter($value));
898
-				}
899
-				$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
900
-				$query->executeStatement();
901
-
902
-				$this->addChanges($calendarId, [''], 2);
903
-
904
-				$calendarData = $this->getCalendarById($calendarId);
905
-				$shares = $this->getShares($calendarId);
906
-				return [$calendarData, $shares];
907
-			}, $this->db);
908
-
909
-			$this->dispatcher->dispatchTyped(new CalendarUpdatedEvent($calendarId, $calendarData, $shares, $mutations));
910
-
911
-			return true;
912
-		});
913
-	}
914
-
915
-	/**
916
-	 * Delete a calendar and all it's objects
917
-	 *
918
-	 * @param mixed $calendarId
919
-	 * @return void
920
-	 */
921
-	public function deleteCalendar($calendarId, bool $forceDeletePermanently = false) {
922
-		$this->atomic(function () use ($calendarId, $forceDeletePermanently): void {
923
-			// The calendar is deleted right away if this is either enforced by the caller
924
-			// or the special contacts birthday calendar or when the preference of an empty
925
-			// retention (0 seconds) is set, which signals a disabled trashbin.
926
-			$calendarData = $this->getCalendarById($calendarId);
927
-			$isBirthdayCalendar = isset($calendarData['uri']) && $calendarData['uri'] === BirthdayService::BIRTHDAY_CALENDAR_URI;
928
-			$trashbinDisabled = $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0';
929
-			if ($forceDeletePermanently || $isBirthdayCalendar || $trashbinDisabled) {
930
-				$calendarData = $this->getCalendarById($calendarId);
931
-				$shares = $this->getShares($calendarId);
932
-
933
-				$this->purgeCalendarInvitations($calendarId);
934
-
935
-				$qbDeleteCalendarObjectProps = $this->db->getQueryBuilder();
936
-				$qbDeleteCalendarObjectProps->delete($this->dbObjectPropertiesTable)
937
-					->where($qbDeleteCalendarObjectProps->expr()->eq('calendarid', $qbDeleteCalendarObjectProps->createNamedParameter($calendarId)))
938
-					->andWhere($qbDeleteCalendarObjectProps->expr()->eq('calendartype', $qbDeleteCalendarObjectProps->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
939
-					->executeStatement();
940
-
941
-				$qbDeleteCalendarObjects = $this->db->getQueryBuilder();
942
-				$qbDeleteCalendarObjects->delete('calendarobjects')
943
-					->where($qbDeleteCalendarObjects->expr()->eq('calendarid', $qbDeleteCalendarObjects->createNamedParameter($calendarId)))
944
-					->andWhere($qbDeleteCalendarObjects->expr()->eq('calendartype', $qbDeleteCalendarObjects->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
945
-					->executeStatement();
946
-
947
-				$qbDeleteCalendarChanges = $this->db->getQueryBuilder();
948
-				$qbDeleteCalendarChanges->delete('calendarchanges')
949
-					->where($qbDeleteCalendarChanges->expr()->eq('calendarid', $qbDeleteCalendarChanges->createNamedParameter($calendarId)))
950
-					->andWhere($qbDeleteCalendarChanges->expr()->eq('calendartype', $qbDeleteCalendarChanges->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
951
-					->executeStatement();
952
-
953
-				$this->calendarSharingBackend->deleteAllShares($calendarId);
954
-
955
-				$qbDeleteCalendar = $this->db->getQueryBuilder();
956
-				$qbDeleteCalendar->delete('calendars')
957
-					->where($qbDeleteCalendar->expr()->eq('id', $qbDeleteCalendar->createNamedParameter($calendarId)))
958
-					->executeStatement();
959
-
960
-				// Only dispatch if we actually deleted anything
961
-				if ($calendarData) {
962
-					$this->dispatcher->dispatchTyped(new CalendarDeletedEvent($calendarId, $calendarData, $shares));
963
-				}
964
-			} else {
965
-				$qbMarkCalendarDeleted = $this->db->getQueryBuilder();
966
-				$qbMarkCalendarDeleted->update('calendars')
967
-					->set('deleted_at', $qbMarkCalendarDeleted->createNamedParameter(time()))
968
-					->where($qbMarkCalendarDeleted->expr()->eq('id', $qbMarkCalendarDeleted->createNamedParameter($calendarId)))
969
-					->executeStatement();
970
-
971
-				$calendarData = $this->getCalendarById($calendarId);
972
-				$shares = $this->getShares($calendarId);
973
-				if ($calendarData) {
974
-					$this->dispatcher->dispatchTyped(new CalendarMovedToTrashEvent(
975
-						$calendarId,
976
-						$calendarData,
977
-						$shares
978
-					));
979
-				}
980
-			}
981
-		}, $this->db);
982
-	}
983
-
984
-	public function restoreCalendar(int $id): void {
985
-		$this->atomic(function () use ($id): void {
986
-			$qb = $this->db->getQueryBuilder();
987
-			$update = $qb->update('calendars')
988
-				->set('deleted_at', $qb->createNamedParameter(null))
989
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
990
-			$update->executeStatement();
991
-
992
-			$calendarData = $this->getCalendarById($id);
993
-			$shares = $this->getShares($id);
994
-			if ($calendarData === null) {
995
-				throw new RuntimeException('Calendar data that was just written can\'t be read back. Check your database configuration.');
996
-			}
997
-			$this->dispatcher->dispatchTyped(new CalendarRestoredEvent(
998
-				$id,
999
-				$calendarData,
1000
-				$shares
1001
-			));
1002
-		}, $this->db);
1003
-	}
1004
-
1005
-	/**
1006
-	 * Returns all calendar entries as a stream of data
1007
-	 *
1008
-	 * @since 32.0.0
1009
-	 *
1010
-	 * @return Generator<array>
1011
-	 */
1012
-	public function exportCalendar(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR, ?CalendarExportOptions $options = null): Generator {
1013
-		// extract options
1014
-		$rangeStart = $options?->getRangeStart();
1015
-		$rangeCount = $options?->getRangeCount();
1016
-		// construct query
1017
-		$qb = $this->db->getQueryBuilder();
1018
-		$qb->select('*')
1019
-			->from('calendarobjects')
1020
-			->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1021
-			->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1022
-			->andWhere($qb->expr()->isNull('deleted_at'));
1023
-		if ($rangeStart !== null) {
1024
-			$qb->andWhere($qb->expr()->gt('uid', $qb->createNamedParameter($rangeStart)));
1025
-		}
1026
-		if ($rangeCount !== null) {
1027
-			$qb->setMaxResults($rangeCount);
1028
-		}
1029
-		if ($rangeStart !== null || $rangeCount !== null) {
1030
-			$qb->orderBy('uid', 'ASC');
1031
-		}
1032
-		$rs = $qb->executeQuery();
1033
-		// iterate through results
1034
-		try {
1035
-			while (($row = $rs->fetch()) !== false) {
1036
-				yield $row;
1037
-			}
1038
-		} finally {
1039
-			$rs->closeCursor();
1040
-		}
1041
-	}
1042
-
1043
-	/**
1044
-	 * Returns all calendar objects with limited metadata for a calendar
1045
-	 *
1046
-	 * Every item contains an array with the following keys:
1047
-	 *   * id - the table row id
1048
-	 *   * etag - An arbitrary string
1049
-	 *   * uri - a unique key which will be used to construct the uri. This can
1050
-	 *     be any arbitrary string.
1051
-	 *   * calendardata - The iCalendar-compatible calendar data
1052
-	 *
1053
-	 * @param mixed $calendarId
1054
-	 * @param int $calendarType
1055
-	 * @return array
1056
-	 */
1057
-	public function getLimitedCalendarObjects(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1058
-		$query = $this->db->getQueryBuilder();
1059
-		$query->select(['id','uid', 'etag', 'uri', 'calendardata'])
1060
-			->from('calendarobjects')
1061
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1062
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1063
-			->andWhere($query->expr()->isNull('deleted_at'));
1064
-		$stmt = $query->executeQuery();
1065
-
1066
-		$result = [];
1067
-		while (($row = $stmt->fetch()) !== false) {
1068
-			$result[$row['uid']] = [
1069
-				'id' => $row['id'],
1070
-				'etag' => $row['etag'],
1071
-				'uri' => $row['uri'],
1072
-				'calendardata' => $row['calendardata'],
1073
-			];
1074
-		}
1075
-		$stmt->closeCursor();
1076
-
1077
-		return $result;
1078
-	}
1079
-
1080
-	/**
1081
-	 * Delete all of an user's shares
1082
-	 *
1083
-	 * @param string $principaluri
1084
-	 * @return void
1085
-	 */
1086
-	public function deleteAllSharesByUser($principaluri) {
1087
-		$this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
1088
-	}
1089
-
1090
-	/**
1091
-	 * Returns all calendar objects within a calendar.
1092
-	 *
1093
-	 * Every item contains an array with the following keys:
1094
-	 *   * calendardata - The iCalendar-compatible calendar data
1095
-	 *   * uri - a unique key which will be used to construct the uri. This can
1096
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
1097
-	 *     good idea. This is only the basename, or filename, not the full
1098
-	 *     path.
1099
-	 *   * lastmodified - a timestamp of the last modification time
1100
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
1101
-	 *   '"abcdef"')
1102
-	 *   * size - The size of the calendar objects, in bytes.
1103
-	 *   * component - optional, a string containing the type of object, such
1104
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
1105
-	 *     the Content-Type header.
1106
-	 *
1107
-	 * Note that the etag is optional, but it's highly encouraged to return for
1108
-	 * speed reasons.
1109
-	 *
1110
-	 * The calendardata is also optional. If it's not returned
1111
-	 * 'getCalendarObject' will be called later, which *is* expected to return
1112
-	 * calendardata.
1113
-	 *
1114
-	 * If neither etag or size are specified, the calendardata will be
1115
-	 * used/fetched to determine these numbers. If both are specified the
1116
-	 * amount of times this is needed is reduced by a great degree.
1117
-	 *
1118
-	 * @param mixed $calendarId
1119
-	 * @param int $calendarType
1120
-	 * @return array
1121
-	 */
1122
-	public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1123
-		$query = $this->db->getQueryBuilder();
1124
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
1125
-			->from('calendarobjects')
1126
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1127
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1128
-			->andWhere($query->expr()->isNull('deleted_at'));
1129
-		$stmt = $query->executeQuery();
1130
-
1131
-		$result = [];
1132
-		while (($row = $stmt->fetch()) !== false) {
1133
-			$result[] = [
1134
-				'id' => $row['id'],
1135
-				'uri' => $row['uri'],
1136
-				'lastmodified' => $row['lastmodified'],
1137
-				'etag' => '"' . $row['etag'] . '"',
1138
-				'calendarid' => $row['calendarid'],
1139
-				'size' => (int)$row['size'],
1140
-				'component' => strtolower($row['componenttype']),
1141
-				'classification' => (int)$row['classification']
1142
-			];
1143
-		}
1144
-		$stmt->closeCursor();
1145
-
1146
-		return $result;
1147
-	}
1148
-
1149
-	public function getDeletedCalendarObjects(int $deletedBefore): array {
1150
-		$query = $this->db->getQueryBuilder();
1151
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.calendartype', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1152
-			->from('calendarobjects', 'co')
1153
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1154
-			->where($query->expr()->isNotNull('co.deleted_at'))
1155
-			->andWhere($query->expr()->lt('co.deleted_at', $query->createNamedParameter($deletedBefore)));
1156
-		$stmt = $query->executeQuery();
1157
-
1158
-		$result = [];
1159
-		while (($row = $stmt->fetch()) !== false) {
1160
-			$result[] = [
1161
-				'id' => $row['id'],
1162
-				'uri' => $row['uri'],
1163
-				'lastmodified' => $row['lastmodified'],
1164
-				'etag' => '"' . $row['etag'] . '"',
1165
-				'calendarid' => (int)$row['calendarid'],
1166
-				'calendartype' => (int)$row['calendartype'],
1167
-				'size' => (int)$row['size'],
1168
-				'component' => strtolower($row['componenttype']),
1169
-				'classification' => (int)$row['classification'],
1170
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1171
-			];
1172
-		}
1173
-		$stmt->closeCursor();
1174
-
1175
-		return $result;
1176
-	}
1177
-
1178
-	/**
1179
-	 * Return all deleted calendar objects by the given principal that are not
1180
-	 * in deleted calendars.
1181
-	 *
1182
-	 * @param string $principalUri
1183
-	 * @return array
1184
-	 * @throws Exception
1185
-	 */
1186
-	public function getDeletedCalendarObjectsByPrincipal(string $principalUri): array {
1187
-		$query = $this->db->getQueryBuilder();
1188
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1189
-			->selectAlias('c.uri', 'calendaruri')
1190
-			->from('calendarobjects', 'co')
1191
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1192
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1193
-			->andWhere($query->expr()->isNotNull('co.deleted_at'))
1194
-			->andWhere($query->expr()->isNull('c.deleted_at'));
1195
-		$stmt = $query->executeQuery();
1196
-
1197
-		$result = [];
1198
-		while ($row = $stmt->fetch()) {
1199
-			$result[] = [
1200
-				'id' => $row['id'],
1201
-				'uri' => $row['uri'],
1202
-				'lastmodified' => $row['lastmodified'],
1203
-				'etag' => '"' . $row['etag'] . '"',
1204
-				'calendarid' => $row['calendarid'],
1205
-				'calendaruri' => $row['calendaruri'],
1206
-				'size' => (int)$row['size'],
1207
-				'component' => strtolower($row['componenttype']),
1208
-				'classification' => (int)$row['classification'],
1209
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1210
-			];
1211
-		}
1212
-		$stmt->closeCursor();
1213
-
1214
-		return $result;
1215
-	}
1216
-
1217
-	/**
1218
-	 * Returns information from a single calendar object, based on it's object
1219
-	 * uri.
1220
-	 *
1221
-	 * The object uri is only the basename, or filename and not a full path.
1222
-	 *
1223
-	 * The returned array must have the same keys as getCalendarObjects. The
1224
-	 * 'calendardata' object is required here though, while it's not required
1225
-	 * for getCalendarObjects.
1226
-	 *
1227
-	 * This method must return null if the object did not exist.
1228
-	 *
1229
-	 * @param mixed $calendarId
1230
-	 * @param string $objectUri
1231
-	 * @param int $calendarType
1232
-	 * @return array|null
1233
-	 */
1234
-	public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1235
-		$key = $calendarId . '::' . $objectUri . '::' . $calendarType;
1236
-		if (isset($this->cachedObjects[$key])) {
1237
-			return $this->cachedObjects[$key];
1238
-		}
1239
-		$query = $this->db->getQueryBuilder();
1240
-		$query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1241
-			->from('calendarobjects')
1242
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1243
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1244
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1245
-		$stmt = $query->executeQuery();
1246
-		$row = $stmt->fetch();
1247
-		$stmt->closeCursor();
1248
-
1249
-		if (!$row) {
1250
-			return null;
1251
-		}
1252
-
1253
-		$object = $this->rowToCalendarObject($row);
1254
-		$this->cachedObjects[$key] = $object;
1255
-		return $object;
1256
-	}
1257
-
1258
-	private function rowToCalendarObject(array $row): array {
1259
-		return [
1260
-			'id' => $row['id'],
1261
-			'uri' => $row['uri'],
1262
-			'uid' => $row['uid'],
1263
-			'lastmodified' => $row['lastmodified'],
1264
-			'etag' => '"' . $row['etag'] . '"',
1265
-			'calendarid' => $row['calendarid'],
1266
-			'size' => (int)$row['size'],
1267
-			'calendardata' => $this->readBlob($row['calendardata']),
1268
-			'component' => strtolower($row['componenttype']),
1269
-			'classification' => (int)$row['classification'],
1270
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1271
-		];
1272
-	}
1273
-
1274
-	/**
1275
-	 * Returns a list of calendar objects.
1276
-	 *
1277
-	 * This method should work identical to getCalendarObject, but instead
1278
-	 * return all the calendar objects in the list as an array.
1279
-	 *
1280
-	 * If the backend supports this, it may allow for some speed-ups.
1281
-	 *
1282
-	 * @param mixed $calendarId
1283
-	 * @param string[] $uris
1284
-	 * @param int $calendarType
1285
-	 * @return array
1286
-	 */
1287
-	public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1288
-		if (empty($uris)) {
1289
-			return [];
1290
-		}
1291
-
1292
-		$chunks = array_chunk($uris, 100);
1293
-		$objects = [];
1294
-
1295
-		$query = $this->db->getQueryBuilder();
1296
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1297
-			->from('calendarobjects')
1298
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1299
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1300
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1301
-			->andWhere($query->expr()->isNull('deleted_at'));
1302
-
1303
-		foreach ($chunks as $uris) {
1304
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1305
-			$result = $query->executeQuery();
1306
-
1307
-			while ($row = $result->fetch()) {
1308
-				$objects[] = [
1309
-					'id' => $row['id'],
1310
-					'uri' => $row['uri'],
1311
-					'lastmodified' => $row['lastmodified'],
1312
-					'etag' => '"' . $row['etag'] . '"',
1313
-					'calendarid' => $row['calendarid'],
1314
-					'size' => (int)$row['size'],
1315
-					'calendardata' => $this->readBlob($row['calendardata']),
1316
-					'component' => strtolower($row['componenttype']),
1317
-					'classification' => (int)$row['classification']
1318
-				];
1319
-			}
1320
-			$result->closeCursor();
1321
-		}
1322
-
1323
-		return $objects;
1324
-	}
1325
-
1326
-	/**
1327
-	 * Creates a new calendar object.
1328
-	 *
1329
-	 * The object uri is only the basename, or filename and not a full path.
1330
-	 *
1331
-	 * It is possible return an etag from this function, which will be used in
1332
-	 * the response to this PUT request. Note that the ETag must be surrounded
1333
-	 * by double-quotes.
1334
-	 *
1335
-	 * However, you should only really return this ETag if you don't mangle the
1336
-	 * calendar-data. If the result of a subsequent GET to this object is not
1337
-	 * the exact same as this request body, you should omit the ETag.
1338
-	 *
1339
-	 * @param mixed $calendarId
1340
-	 * @param string $objectUri
1341
-	 * @param string $calendarData
1342
-	 * @param int $calendarType
1343
-	 * @return string
1344
-	 */
1345
-	public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1346
-		$this->cachedObjects = [];
1347
-		$extraData = $this->getDenormalizedData($calendarData);
1348
-
1349
-		return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1350
-			// Try to detect duplicates
1351
-			$qb = $this->db->getQueryBuilder();
1352
-			$qb->select($qb->func()->count('*'))
1353
-				->from('calendarobjects')
1354
-				->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1355
-				->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($extraData['uid'])))
1356
-				->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1357
-				->andWhere($qb->expr()->isNull('deleted_at'));
1358
-			$result = $qb->executeQuery();
1359
-			$count = (int)$result->fetchOne();
1360
-			$result->closeCursor();
1361
-
1362
-			if ($count !== 0) {
1363
-				throw new BadRequest('Calendar object with uid already exists in this calendar collection.');
1364
-			}
1365
-			// For a more specific error message we also try to explicitly look up the UID but as a deleted entry
1366
-			$qbDel = $this->db->getQueryBuilder();
1367
-			$qbDel->select('*')
1368
-				->from('calendarobjects')
1369
-				->where($qbDel->expr()->eq('calendarid', $qbDel->createNamedParameter($calendarId)))
1370
-				->andWhere($qbDel->expr()->eq('uid', $qbDel->createNamedParameter($extraData['uid'])))
1371
-				->andWhere($qbDel->expr()->eq('calendartype', $qbDel->createNamedParameter($calendarType)))
1372
-				->andWhere($qbDel->expr()->isNotNull('deleted_at'));
1373
-			$result = $qbDel->executeQuery();
1374
-			$found = $result->fetch();
1375
-			$result->closeCursor();
1376
-			if ($found !== false) {
1377
-				// the object existed previously but has been deleted
1378
-				// remove the trashbin entry and continue as if it was a new object
1379
-				$this->deleteCalendarObject($calendarId, $found['uri']);
1380
-			}
1381
-
1382
-			$query = $this->db->getQueryBuilder();
1383
-			$query->insert('calendarobjects')
1384
-				->values([
1385
-					'calendarid' => $query->createNamedParameter($calendarId),
1386
-					'uri' => $query->createNamedParameter($objectUri),
1387
-					'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1388
-					'lastmodified' => $query->createNamedParameter(time()),
1389
-					'etag' => $query->createNamedParameter($extraData['etag']),
1390
-					'size' => $query->createNamedParameter($extraData['size']),
1391
-					'componenttype' => $query->createNamedParameter($extraData['componentType']),
1392
-					'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1393
-					'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1394
-					'classification' => $query->createNamedParameter($extraData['classification']),
1395
-					'uid' => $query->createNamedParameter($extraData['uid']),
1396
-					'calendartype' => $query->createNamedParameter($calendarType),
1397
-				])
1398
-				->executeStatement();
1399
-
1400
-			$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1401
-			$this->addChanges($calendarId, [$objectUri], 1, $calendarType);
1402
-
1403
-			$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1404
-			assert($objectRow !== null);
1405
-
1406
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1407
-				$calendarRow = $this->getCalendarById($calendarId);
1408
-				$shares = $this->getShares($calendarId);
1409
-
1410
-				$this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1411
-			} else {
1412
-				$subscriptionRow = $this->getSubscriptionById($calendarId);
1413
-
1414
-				$this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1415
-			}
1416
-
1417
-			return '"' . $extraData['etag'] . '"';
1418
-		}, $this->db);
1419
-	}
1420
-
1421
-	/**
1422
-	 * Updates an existing calendarobject, based on it's uri.
1423
-	 *
1424
-	 * The object uri is only the basename, or filename and not a full path.
1425
-	 *
1426
-	 * It is possible return an etag from this function, which will be used in
1427
-	 * the response to this PUT request. Note that the ETag must be surrounded
1428
-	 * by double-quotes.
1429
-	 *
1430
-	 * However, you should only really return this ETag if you don't mangle the
1431
-	 * calendar-data. If the result of a subsequent GET to this object is not
1432
-	 * the exact same as this request body, you should omit the ETag.
1433
-	 *
1434
-	 * @param mixed $calendarId
1435
-	 * @param string $objectUri
1436
-	 * @param string $calendarData
1437
-	 * @param int $calendarType
1438
-	 * @return string
1439
-	 */
1440
-	public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1441
-		$this->cachedObjects = [];
1442
-		$extraData = $this->getDenormalizedData($calendarData);
1443
-
1444
-		return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1445
-			$query = $this->db->getQueryBuilder();
1446
-			$query->update('calendarobjects')
1447
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1448
-				->set('lastmodified', $query->createNamedParameter(time()))
1449
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1450
-				->set('size', $query->createNamedParameter($extraData['size']))
1451
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1452
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1453
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1454
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1455
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1456
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1457
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1458
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1459
-				->executeStatement();
1460
-
1461
-			$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1462
-			$this->addChanges($calendarId, [$objectUri], 2, $calendarType);
1463
-
1464
-			$objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1465
-			if (is_array($objectRow)) {
1466
-				if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1467
-					$calendarRow = $this->getCalendarById($calendarId);
1468
-					$shares = $this->getShares($calendarId);
1469
-
1470
-					$this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1471
-				} else {
1472
-					$subscriptionRow = $this->getSubscriptionById($calendarId);
1473
-
1474
-					$this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1475
-				}
1476
-			}
1477
-
1478
-			return '"' . $extraData['etag'] . '"';
1479
-		}, $this->db);
1480
-	}
1481
-
1482
-	/**
1483
-	 * Moves a calendar object from calendar to calendar.
1484
-	 *
1485
-	 * @param string $sourcePrincipalUri
1486
-	 * @param int $sourceObjectId
1487
-	 * @param string $targetPrincipalUri
1488
-	 * @param int $targetCalendarId
1489
-	 * @param string $tragetObjectUri
1490
-	 * @param int $calendarType
1491
-	 * @return bool
1492
-	 * @throws Exception
1493
-	 */
1494
-	public function moveCalendarObject(string $sourcePrincipalUri, int $sourceObjectId, string $targetPrincipalUri, int $targetCalendarId, string $tragetObjectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR): bool {
1495
-		$this->cachedObjects = [];
1496
-		return $this->atomic(function () use ($sourcePrincipalUri, $sourceObjectId, $targetPrincipalUri, $targetCalendarId, $tragetObjectUri, $calendarType) {
1497
-			$object = $this->getCalendarObjectById($sourcePrincipalUri, $sourceObjectId);
1498
-			if (empty($object)) {
1499
-				return false;
1500
-			}
1501
-
1502
-			$sourceCalendarId = $object['calendarid'];
1503
-			$sourceObjectUri = $object['uri'];
1504
-
1505
-			$query = $this->db->getQueryBuilder();
1506
-			$query->update('calendarobjects')
1507
-				->set('calendarid', $query->createNamedParameter($targetCalendarId, IQueryBuilder::PARAM_INT))
1508
-				->set('uri', $query->createNamedParameter($tragetObjectUri, IQueryBuilder::PARAM_STR))
1509
-				->where($query->expr()->eq('id', $query->createNamedParameter($sourceObjectId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
1510
-				->executeStatement();
1511
-
1512
-			$this->purgeProperties($sourceCalendarId, $sourceObjectId);
1513
-			$this->updateProperties($targetCalendarId, $tragetObjectUri, $object['calendardata'], $calendarType);
1514
-
1515
-			$this->addChanges($sourceCalendarId, [$sourceObjectUri], 3, $calendarType);
1516
-			$this->addChanges($targetCalendarId, [$tragetObjectUri], 1, $calendarType);
1517
-
1518
-			$object = $this->getCalendarObjectById($targetPrincipalUri, $sourceObjectId);
1519
-			// Calendar Object wasn't found - possibly because it was deleted in the meantime by a different client
1520
-			if (empty($object)) {
1521
-				return false;
1522
-			}
1523
-
1524
-			$targetCalendarRow = $this->getCalendarById($targetCalendarId);
1525
-			// the calendar this event is being moved to does not exist any longer
1526
-			if (empty($targetCalendarRow)) {
1527
-				return false;
1528
-			}
1529
-
1530
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1531
-				$sourceShares = $this->getShares($sourceCalendarId);
1532
-				$targetShares = $this->getShares($targetCalendarId);
1533
-				$sourceCalendarRow = $this->getCalendarById($sourceCalendarId);
1534
-				$this->dispatcher->dispatchTyped(new CalendarObjectMovedEvent($sourceCalendarId, $sourceCalendarRow, $targetCalendarId, $targetCalendarRow, $sourceShares, $targetShares, $object));
1535
-			}
1536
-			return true;
1537
-		}, $this->db);
1538
-	}
1539
-
1540
-	/**
1541
-	 * Deletes an existing calendar object.
1542
-	 *
1543
-	 * The object uri is only the basename, or filename and not a full path.
1544
-	 *
1545
-	 * @param mixed $calendarId
1546
-	 * @param string $objectUri
1547
-	 * @param int $calendarType
1548
-	 * @param bool $forceDeletePermanently
1549
-	 * @return void
1550
-	 */
1551
-	public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
1552
-		$this->cachedObjects = [];
1553
-		$this->atomic(function () use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently): void {
1554
-			$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1555
-
1556
-			if ($data === null) {
1557
-				// Nothing to delete
1558
-				return;
1559
-			}
1560
-
1561
-			if ($forceDeletePermanently || $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0') {
1562
-				$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1563
-				$stmt->execute([$calendarId, $objectUri, $calendarType]);
1564
-
1565
-				$this->purgeProperties($calendarId, $data['id']);
1566
-
1567
-				$this->purgeObjectInvitations($data['uid']);
1568
-
1569
-				if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1570
-					$calendarRow = $this->getCalendarById($calendarId);
1571
-					$shares = $this->getShares($calendarId);
1572
-
1573
-					$this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent($calendarId, $calendarRow, $shares, $data));
1574
-				} else {
1575
-					$subscriptionRow = $this->getSubscriptionById($calendarId);
1576
-
1577
-					$this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent($calendarId, $subscriptionRow, [], $data));
1578
-				}
1579
-			} else {
1580
-				$pathInfo = pathinfo($data['uri']);
1581
-				if (!empty($pathInfo['extension'])) {
1582
-					// Append a suffix to "free" the old URI for recreation
1583
-					$newUri = sprintf(
1584
-						'%s-deleted.%s',
1585
-						$pathInfo['filename'],
1586
-						$pathInfo['extension']
1587
-					);
1588
-				} else {
1589
-					$newUri = sprintf(
1590
-						'%s-deleted',
1591
-						$pathInfo['filename']
1592
-					);
1593
-				}
1594
-
1595
-				// Try to detect conflicts before the DB does
1596
-				// As unlikely as it seems, this can happen when the user imports, then deletes, imports and deletes again
1597
-				$newObject = $this->getCalendarObject($calendarId, $newUri, $calendarType);
1598
-				if ($newObject !== null) {
1599
-					throw new Forbidden("A calendar object with URI $newUri already exists in calendar $calendarId, therefore this object can't be moved into the trashbin");
1600
-				}
1601
-
1602
-				$qb = $this->db->getQueryBuilder();
1603
-				$markObjectDeletedQuery = $qb->update('calendarobjects')
1604
-					->set('deleted_at', $qb->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
1605
-					->set('uri', $qb->createNamedParameter($newUri))
1606
-					->where(
1607
-						$qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
1608
-						$qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
1609
-						$qb->expr()->eq('uri', $qb->createNamedParameter($objectUri))
1610
-					);
1611
-				$markObjectDeletedQuery->executeStatement();
1612
-
1613
-				$calendarData = $this->getCalendarById($calendarId);
1614
-				if ($calendarData !== null) {
1615
-					$this->dispatcher->dispatchTyped(
1616
-						new CalendarObjectMovedToTrashEvent(
1617
-							$calendarId,
1618
-							$calendarData,
1619
-							$this->getShares($calendarId),
1620
-							$data
1621
-						)
1622
-					);
1623
-				}
1624
-			}
1625
-
1626
-			$this->addChanges($calendarId, [$objectUri], 3, $calendarType);
1627
-		}, $this->db);
1628
-	}
1629
-
1630
-	/**
1631
-	 * @param mixed $objectData
1632
-	 *
1633
-	 * @throws Forbidden
1634
-	 */
1635
-	public function restoreCalendarObject(array $objectData): void {
1636
-		$this->cachedObjects = [];
1637
-		$this->atomic(function () use ($objectData): void {
1638
-			$id = (int)$objectData['id'];
1639
-			$restoreUri = str_replace('-deleted.ics', '.ics', $objectData['uri']);
1640
-			$targetObject = $this->getCalendarObject(
1641
-				$objectData['calendarid'],
1642
-				$restoreUri
1643
-			);
1644
-			if ($targetObject !== null) {
1645
-				throw new Forbidden("Can not restore calendar $id because a calendar object with the URI $restoreUri already exists");
1646
-			}
1647
-
1648
-			$qb = $this->db->getQueryBuilder();
1649
-			$update = $qb->update('calendarobjects')
1650
-				->set('uri', $qb->createNamedParameter($restoreUri))
1651
-				->set('deleted_at', $qb->createNamedParameter(null))
1652
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1653
-			$update->executeStatement();
1654
-
1655
-			// Make sure this change is tracked in the changes table
1656
-			$qb2 = $this->db->getQueryBuilder();
1657
-			$selectObject = $qb2->select('calendardata', 'uri', 'calendarid', 'calendartype')
1658
-				->selectAlias('componenttype', 'component')
1659
-				->from('calendarobjects')
1660
-				->where($qb2->expr()->eq('id', $qb2->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1661
-			$result = $selectObject->executeQuery();
1662
-			$row = $result->fetch();
1663
-			$result->closeCursor();
1664
-			if ($row === false) {
1665
-				// Welp, this should possibly not have happened, but let's ignore
1666
-				return;
1667
-			}
1668
-			$this->addChanges($row['calendarid'], [$row['uri']], 1, (int)$row['calendartype']);
1669
-
1670
-			$calendarRow = $this->getCalendarById((int)$row['calendarid']);
1671
-			if ($calendarRow === null) {
1672
-				throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
1673
-			}
1674
-			$this->dispatcher->dispatchTyped(
1675
-				new CalendarObjectRestoredEvent(
1676
-					(int)$objectData['calendarid'],
1677
-					$calendarRow,
1678
-					$this->getShares((int)$row['calendarid']),
1679
-					$row
1680
-				)
1681
-			);
1682
-		}, $this->db);
1683
-	}
1684
-
1685
-	/**
1686
-	 * Performs a calendar-query on the contents of this calendar.
1687
-	 *
1688
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1689
-	 * calendar-query it is possible for a client to request a specific set of
1690
-	 * object, based on contents of iCalendar properties, date-ranges and
1691
-	 * iCalendar component types (VTODO, VEVENT).
1692
-	 *
1693
-	 * This method should just return a list of (relative) urls that match this
1694
-	 * query.
1695
-	 *
1696
-	 * The list of filters are specified as an array. The exact array is
1697
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1698
-	 *
1699
-	 * Note that it is extremely likely that getCalendarObject for every path
1700
-	 * returned from this method will be called almost immediately after. You
1701
-	 * may want to anticipate this to speed up these requests.
1702
-	 *
1703
-	 * This method provides a default implementation, which parses *all* the
1704
-	 * iCalendar objects in the specified calendar.
1705
-	 *
1706
-	 * This default may well be good enough for personal use, and calendars
1707
-	 * that aren't very large. But if you anticipate high usage, big calendars
1708
-	 * or high loads, you are strongly advised to optimize certain paths.
1709
-	 *
1710
-	 * The best way to do so is override this method and to optimize
1711
-	 * specifically for 'common filters'.
1712
-	 *
1713
-	 * Requests that are extremely common are:
1714
-	 *   * requests for just VEVENTS
1715
-	 *   * requests for just VTODO
1716
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1717
-	 *
1718
-	 * ..and combinations of these requests. It may not be worth it to try to
1719
-	 * handle every possible situation and just rely on the (relatively
1720
-	 * easy to use) CalendarQueryValidator to handle the rest.
1721
-	 *
1722
-	 * Note that especially time-range-filters may be difficult to parse. A
1723
-	 * time-range filter specified on a VEVENT must for instance also handle
1724
-	 * recurrence rules correctly.
1725
-	 * A good example of how to interpret all these filters can also simply
1726
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1727
-	 * as possible, so it gives you a good idea on what type of stuff you need
1728
-	 * to think of.
1729
-	 *
1730
-	 * @param mixed $calendarId
1731
-	 * @param array $filters
1732
-	 * @param int $calendarType
1733
-	 * @return array
1734
-	 */
1735
-	public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1736
-		$componentType = null;
1737
-		$requirePostFilter = true;
1738
-		$timeRange = null;
1739
-
1740
-		// if no filters were specified, we don't need to filter after a query
1741
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1742
-			$requirePostFilter = false;
1743
-		}
1744
-
1745
-		// Figuring out if there's a component filter
1746
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1747
-			$componentType = $filters['comp-filters'][0]['name'];
1748
-
1749
-			// Checking if we need post-filters
1750
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1751
-				$requirePostFilter = false;
1752
-			}
1753
-			// There was a time-range filter
1754
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
1755
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1756
-
1757
-				// If start time OR the end time is not specified, we can do a
1758
-				// 100% accurate mysql query.
1759
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1760
-					$requirePostFilter = false;
1761
-				}
1762
-			}
1763
-		}
1764
-		$query = $this->db->getQueryBuilder();
1765
-		$query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1766
-			->from('calendarobjects')
1767
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1768
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1769
-			->andWhere($query->expr()->isNull('deleted_at'));
1770
-
1771
-		if ($componentType) {
1772
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1773
-		}
1774
-
1775
-		if ($timeRange && $timeRange['start']) {
1776
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1777
-		}
1778
-		if ($timeRange && $timeRange['end']) {
1779
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1780
-		}
1781
-
1782
-		$stmt = $query->executeQuery();
1783
-
1784
-		$result = [];
1785
-		while ($row = $stmt->fetch()) {
1786
-			// if we leave it as a blob we can't read it both from the post filter and the rowToCalendarObject
1787
-			if (isset($row['calendardata'])) {
1788
-				$row['calendardata'] = $this->readBlob($row['calendardata']);
1789
-			}
1790
-
1791
-			if ($requirePostFilter) {
1792
-				// validateFilterForObject will parse the calendar data
1793
-				// catch parsing errors
1794
-				try {
1795
-					$matches = $this->validateFilterForObject($row, $filters);
1796
-				} catch (ParseException $ex) {
1797
-					$this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1798
-						'app' => 'dav',
1799
-						'exception' => $ex,
1800
-					]);
1801
-					continue;
1802
-				} catch (InvalidDataException $ex) {
1803
-					$this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1804
-						'app' => 'dav',
1805
-						'exception' => $ex,
1806
-					]);
1807
-					continue;
1808
-				} catch (MaxInstancesExceededException $ex) {
1809
-					$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'], [
1810
-						'app' => 'dav',
1811
-						'exception' => $ex,
1812
-					]);
1813
-					continue;
1814
-				}
1815
-
1816
-				if (!$matches) {
1817
-					continue;
1818
-				}
1819
-			}
1820
-			$result[] = $row['uri'];
1821
-			$key = $calendarId . '::' . $row['uri'] . '::' . $calendarType;
1822
-			$this->cachedObjects[$key] = $this->rowToCalendarObject($row);
1823
-		}
1824
-
1825
-		return $result;
1826
-	}
1827
-
1828
-	/**
1829
-	 * custom Nextcloud search extension for CalDAV
1830
-	 *
1831
-	 * TODO - this should optionally cover cached calendar objects as well
1832
-	 *
1833
-	 * @param string $principalUri
1834
-	 * @param array $filters
1835
-	 * @param integer|null $limit
1836
-	 * @param integer|null $offset
1837
-	 * @return array
1838
-	 */
1839
-	public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1840
-		return $this->atomic(function () use ($principalUri, $filters, $limit, $offset) {
1841
-			$calendars = $this->getCalendarsForUser($principalUri);
1842
-			$ownCalendars = [];
1843
-			$sharedCalendars = [];
1844
-
1845
-			$uriMapper = [];
1846
-
1847
-			foreach ($calendars as $calendar) {
1848
-				if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1849
-					$ownCalendars[] = $calendar['id'];
1850
-				} else {
1851
-					$sharedCalendars[] = $calendar['id'];
1852
-				}
1853
-				$uriMapper[$calendar['id']] = $calendar['uri'];
1854
-			}
1855
-			if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1856
-				return [];
1857
-			}
1858
-
1859
-			$query = $this->db->getQueryBuilder();
1860
-			// Calendar id expressions
1861
-			$calendarExpressions = [];
1862
-			foreach ($ownCalendars as $id) {
1863
-				$calendarExpressions[] = $query->expr()->andX(
1864
-					$query->expr()->eq('c.calendarid',
1865
-						$query->createNamedParameter($id)),
1866
-					$query->expr()->eq('c.calendartype',
1867
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1868
-			}
1869
-			foreach ($sharedCalendars as $id) {
1870
-				$calendarExpressions[] = $query->expr()->andX(
1871
-					$query->expr()->eq('c.calendarid',
1872
-						$query->createNamedParameter($id)),
1873
-					$query->expr()->eq('c.classification',
1874
-						$query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1875
-					$query->expr()->eq('c.calendartype',
1876
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1877
-			}
1878
-
1879
-			if (count($calendarExpressions) === 1) {
1880
-				$calExpr = $calendarExpressions[0];
1881
-			} else {
1882
-				$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1883
-			}
1884
-
1885
-			// Component expressions
1886
-			$compExpressions = [];
1887
-			foreach ($filters['comps'] as $comp) {
1888
-				$compExpressions[] = $query->expr()
1889
-					->eq('c.componenttype', $query->createNamedParameter($comp));
1890
-			}
1891
-
1892
-			if (count($compExpressions) === 1) {
1893
-				$compExpr = $compExpressions[0];
1894
-			} else {
1895
-				$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1896
-			}
1897
-
1898
-			if (!isset($filters['props'])) {
1899
-				$filters['props'] = [];
1900
-			}
1901
-			if (!isset($filters['params'])) {
1902
-				$filters['params'] = [];
1903
-			}
1904
-
1905
-			$propParamExpressions = [];
1906
-			foreach ($filters['props'] as $prop) {
1907
-				$propParamExpressions[] = $query->expr()->andX(
1908
-					$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1909
-					$query->expr()->isNull('i.parameter')
1910
-				);
1911
-			}
1912
-			foreach ($filters['params'] as $param) {
1913
-				$propParamExpressions[] = $query->expr()->andX(
1914
-					$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1915
-					$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1916
-				);
1917
-			}
1918
-
1919
-			if (count($propParamExpressions) === 1) {
1920
-				$propParamExpr = $propParamExpressions[0];
1921
-			} else {
1922
-				$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1923
-			}
1924
-
1925
-			$query->select(['c.calendarid', 'c.uri'])
1926
-				->from($this->dbObjectPropertiesTable, 'i')
1927
-				->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1928
-				->where($calExpr)
1929
-				->andWhere($compExpr)
1930
-				->andWhere($propParamExpr)
1931
-				->andWhere($query->expr()->iLike('i.value',
1932
-					$query->createNamedParameter('%' . $this->db->escapeLikeParameter($filters['search-term']) . '%')))
1933
-				->andWhere($query->expr()->isNull('deleted_at'));
1934
-
1935
-			if ($offset) {
1936
-				$query->setFirstResult($offset);
1937
-			}
1938
-			if ($limit) {
1939
-				$query->setMaxResults($limit);
1940
-			}
1941
-
1942
-			$stmt = $query->executeQuery();
1943
-
1944
-			$result = [];
1945
-			while ($row = $stmt->fetch()) {
1946
-				$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1947
-				if (!in_array($path, $result)) {
1948
-					$result[] = $path;
1949
-				}
1950
-			}
1951
-
1952
-			return $result;
1953
-		}, $this->db);
1954
-	}
1955
-
1956
-	/**
1957
-	 * used for Nextcloud's calendar API
1958
-	 *
1959
-	 * @param array $calendarInfo
1960
-	 * @param string $pattern
1961
-	 * @param array $searchProperties
1962
-	 * @param array $options
1963
-	 * @param integer|null $limit
1964
-	 * @param integer|null $offset
1965
-	 *
1966
-	 * @return array
1967
-	 */
1968
-	public function search(
1969
-		array $calendarInfo,
1970
-		$pattern,
1971
-		array $searchProperties,
1972
-		array $options,
1973
-		$limit,
1974
-		$offset,
1975
-	) {
1976
-		$outerQuery = $this->db->getQueryBuilder();
1977
-		$innerQuery = $this->db->getQueryBuilder();
1978
-
1979
-		if (isset($calendarInfo['source'])) {
1980
-			$calendarType = self::CALENDAR_TYPE_SUBSCRIPTION;
1981
-		} else {
1982
-			$calendarType = self::CALENDAR_TYPE_CALENDAR;
1983
-		}
1984
-
1985
-		$innerQuery->selectDistinct('op.objectid')
1986
-			->from($this->dbObjectPropertiesTable, 'op')
1987
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
1988
-				$outerQuery->createNamedParameter($calendarInfo['id'])))
1989
-			->andWhere($innerQuery->expr()->eq('op.calendartype',
1990
-				$outerQuery->createNamedParameter($calendarType)));
1991
-
1992
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1993
-			->from('calendarobjects', 'c')
1994
-			->where($outerQuery->expr()->isNull('deleted_at'));
1995
-
1996
-		// only return public items for shared calendars for now
1997
-		if (isset($calendarInfo['{http://owncloud.org/ns}owner-principal']) === false || $calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1998
-			$outerQuery->andWhere($outerQuery->expr()->eq('c.classification',
1999
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2000
-		}
2001
-
2002
-		if (!empty($searchProperties)) {
2003
-			$or = [];
2004
-			foreach ($searchProperties as $searchProperty) {
2005
-				$or[] = $innerQuery->expr()->eq('op.name',
2006
-					$outerQuery->createNamedParameter($searchProperty));
2007
-			}
2008
-			$innerQuery->andWhere($innerQuery->expr()->orX(...$or));
2009
-		}
2010
-
2011
-		if ($pattern !== '') {
2012
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
2013
-				$outerQuery->createNamedParameter('%'
2014
-					. $this->db->escapeLikeParameter($pattern) . '%')));
2015
-		}
2016
-
2017
-		$start = null;
2018
-		$end = null;
2019
-
2020
-		$hasLimit = is_int($limit);
2021
-		$hasTimeRange = false;
2022
-
2023
-		if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2024
-			/** @var DateTimeInterface $start */
2025
-			$start = $options['timerange']['start'];
2026
-			$outerQuery->andWhere(
2027
-				$outerQuery->expr()->gt(
2028
-					'lastoccurence',
2029
-					$outerQuery->createNamedParameter($start->getTimestamp())
2030
-				)
2031
-			);
2032
-			$hasTimeRange = true;
2033
-		}
2034
-
2035
-		if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2036
-			/** @var DateTimeInterface $end */
2037
-			$end = $options['timerange']['end'];
2038
-			$outerQuery->andWhere(
2039
-				$outerQuery->expr()->lt(
2040
-					'firstoccurence',
2041
-					$outerQuery->createNamedParameter($end->getTimestamp())
2042
-				)
2043
-			);
2044
-			$hasTimeRange = true;
2045
-		}
2046
-
2047
-		if (isset($options['uid'])) {
2048
-			$outerQuery->andWhere($outerQuery->expr()->eq('uid', $outerQuery->createNamedParameter($options['uid'])));
2049
-		}
2050
-
2051
-		if (!empty($options['types'])) {
2052
-			$or = [];
2053
-			foreach ($options['types'] as $type) {
2054
-				$or[] = $outerQuery->expr()->eq('componenttype',
2055
-					$outerQuery->createNamedParameter($type));
2056
-			}
2057
-			$outerQuery->andWhere($outerQuery->expr()->orX(...$or));
2058
-		}
2059
-
2060
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id', $outerQuery->createFunction($innerQuery->getSQL())));
2061
-
2062
-		// Without explicit order by its undefined in which order the SQL server returns the events.
2063
-		// For the pagination with hasLimit and hasTimeRange, a stable ordering is helpful.
2064
-		$outerQuery->addOrderBy('id');
2065
-
2066
-		$offset = (int)$offset;
2067
-		$outerQuery->setFirstResult($offset);
2068
-
2069
-		$calendarObjects = [];
2070
-
2071
-		if ($hasLimit && $hasTimeRange) {
2072
-			/**
2073
-			 * Event recurrences are evaluated at runtime because the database only knows the first and last occurrence.
2074
-			 *
2075
-			 * Given, a user created 8 events with a yearly reoccurrence and two for events tomorrow.
2076
-			 * The upcoming event widget asks the CalDAV backend for 7 events within the next 14 days.
2077
-			 *
2078
-			 * If limit 7 is applied to the SQL query, we find the 7 events with a yearly reoccurrence
2079
-			 * and discard the events after evaluating the reoccurrence rules because they are not due within
2080
-			 * the next 14 days and end up with an empty result even if there are two events to show.
2081
-			 *
2082
-			 * The workaround for search requests with a limit and time range is asking for more row than requested
2083
-			 * and retrying if we have not reached the limit.
2084
-			 *
2085
-			 * 25 rows and 3 retries is entirely arbitrary.
2086
-			 */
2087
-			$maxResults = (int)max($limit, 25);
2088
-			$outerQuery->setMaxResults($maxResults);
2089
-
2090
-			for ($attempt = $objectsCount = 0; $attempt < 3 && $objectsCount < $limit; $attempt++) {
2091
-				$objectsCount = array_push($calendarObjects, ...$this->searchCalendarObjects($outerQuery, $start, $end));
2092
-				$outerQuery->setFirstResult($offset += $maxResults);
2093
-			}
2094
-
2095
-			$calendarObjects = array_slice($calendarObjects, 0, $limit, false);
2096
-		} else {
2097
-			$outerQuery->setMaxResults($limit);
2098
-			$calendarObjects = $this->searchCalendarObjects($outerQuery, $start, $end);
2099
-		}
2100
-
2101
-		$calendarObjects = array_map(function ($o) use ($options) {
2102
-			$calendarData = Reader::read($o['calendardata']);
2103
-
2104
-			// Expand recurrences if an explicit time range is requested
2105
-			if ($calendarData instanceof VCalendar
2106
-				&& isset($options['timerange']['start'], $options['timerange']['end'])) {
2107
-				$calendarData = $calendarData->expand(
2108
-					$options['timerange']['start'],
2109
-					$options['timerange']['end'],
2110
-				);
2111
-			}
2112
-
2113
-			$comps = $calendarData->getComponents();
2114
-			$objects = [];
2115
-			$timezones = [];
2116
-			foreach ($comps as $comp) {
2117
-				if ($comp instanceof VTimeZone) {
2118
-					$timezones[] = $comp;
2119
-				} else {
2120
-					$objects[] = $comp;
2121
-				}
2122
-			}
2123
-
2124
-			return [
2125
-				'id' => $o['id'],
2126
-				'type' => $o['componenttype'],
2127
-				'uid' => $o['uid'],
2128
-				'uri' => $o['uri'],
2129
-				'objects' => array_map(function ($c) {
2130
-					return $this->transformSearchData($c);
2131
-				}, $objects),
2132
-				'timezones' => array_map(function ($c) {
2133
-					return $this->transformSearchData($c);
2134
-				}, $timezones),
2135
-			];
2136
-		}, $calendarObjects);
2137
-
2138
-		usort($calendarObjects, function (array $a, array $b) {
2139
-			/** @var DateTimeImmutable $startA */
2140
-			$startA = $a['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2141
-			/** @var DateTimeImmutable $startB */
2142
-			$startB = $b['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2143
-
2144
-			return $startA->getTimestamp() <=> $startB->getTimestamp();
2145
-		});
2146
-
2147
-		return $calendarObjects;
2148
-	}
2149
-
2150
-	private function searchCalendarObjects(IQueryBuilder $query, ?DateTimeInterface $start, ?DateTimeInterface $end): array {
2151
-		$calendarObjects = [];
2152
-		$filterByTimeRange = ($start instanceof DateTimeInterface) || ($end instanceof DateTimeInterface);
2153
-
2154
-		$result = $query->executeQuery();
2155
-
2156
-		while (($row = $result->fetch()) !== false) {
2157
-			if ($filterByTimeRange === false) {
2158
-				// No filter required
2159
-				$calendarObjects[] = $row;
2160
-				continue;
2161
-			}
2162
-
2163
-			try {
2164
-				$isValid = $this->validateFilterForObject($row, [
2165
-					'name' => 'VCALENDAR',
2166
-					'comp-filters' => [
2167
-						[
2168
-							'name' => 'VEVENT',
2169
-							'comp-filters' => [],
2170
-							'prop-filters' => [],
2171
-							'is-not-defined' => false,
2172
-							'time-range' => [
2173
-								'start' => $start,
2174
-								'end' => $end,
2175
-							],
2176
-						],
2177
-					],
2178
-					'prop-filters' => [],
2179
-					'is-not-defined' => false,
2180
-					'time-range' => null,
2181
-				]);
2182
-			} catch (MaxInstancesExceededException $ex) {
2183
-				$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'], [
2184
-					'app' => 'dav',
2185
-					'exception' => $ex,
2186
-				]);
2187
-				continue;
2188
-			}
2189
-
2190
-			if (is_resource($row['calendardata'])) {
2191
-				// Put the stream back to the beginning so it can be read another time
2192
-				rewind($row['calendardata']);
2193
-			}
2194
-
2195
-			if ($isValid) {
2196
-				$calendarObjects[] = $row;
2197
-			}
2198
-		}
2199
-
2200
-		$result->closeCursor();
2201
-
2202
-		return $calendarObjects;
2203
-	}
2204
-
2205
-	/**
2206
-	 * @param Component $comp
2207
-	 * @return array
2208
-	 */
2209
-	private function transformSearchData(Component $comp) {
2210
-		$data = [];
2211
-		/** @var Component[] $subComponents */
2212
-		$subComponents = $comp->getComponents();
2213
-		/** @var Property[] $properties */
2214
-		$properties = array_filter($comp->children(), function ($c) {
2215
-			return $c instanceof Property;
2216
-		});
2217
-		$validationRules = $comp->getValidationRules();
2218
-
2219
-		foreach ($subComponents as $subComponent) {
2220
-			$name = $subComponent->name;
2221
-			if (!isset($data[$name])) {
2222
-				$data[$name] = [];
2223
-			}
2224
-			$data[$name][] = $this->transformSearchData($subComponent);
2225
-		}
2226
-
2227
-		foreach ($properties as $property) {
2228
-			$name = $property->name;
2229
-			if (!isset($validationRules[$name])) {
2230
-				$validationRules[$name] = '*';
2231
-			}
2232
-
2233
-			$rule = $validationRules[$property->name];
2234
-			if ($rule === '+' || $rule === '*') { // multiple
2235
-				if (!isset($data[$name])) {
2236
-					$data[$name] = [];
2237
-				}
2238
-
2239
-				$data[$name][] = $this->transformSearchProperty($property);
2240
-			} else { // once
2241
-				$data[$name] = $this->transformSearchProperty($property);
2242
-			}
2243
-		}
2244
-
2245
-		return $data;
2246
-	}
2247
-
2248
-	/**
2249
-	 * @param Property $prop
2250
-	 * @return array
2251
-	 */
2252
-	private function transformSearchProperty(Property $prop) {
2253
-		// No need to check Date, as it extends DateTime
2254
-		if ($prop instanceof Property\ICalendar\DateTime) {
2255
-			$value = $prop->getDateTime();
2256
-		} else {
2257
-			$value = $prop->getValue();
2258
-		}
2259
-
2260
-		return [
2261
-			$value,
2262
-			$prop->parameters()
2263
-		];
2264
-	}
2265
-
2266
-	/**
2267
-	 * @param string $principalUri
2268
-	 * @param string $pattern
2269
-	 * @param array $componentTypes
2270
-	 * @param array $searchProperties
2271
-	 * @param array $searchParameters
2272
-	 * @param array $options
2273
-	 * @return array
2274
-	 */
2275
-	public function searchPrincipalUri(string $principalUri,
2276
-		string $pattern,
2277
-		array $componentTypes,
2278
-		array $searchProperties,
2279
-		array $searchParameters,
2280
-		array $options = [],
2281
-	): array {
2282
-		return $this->atomic(function () use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
2283
-			$escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
2284
-
2285
-			$calendarObjectIdQuery = $this->db->getQueryBuilder();
2286
-			$calendarOr = [];
2287
-			$searchOr = [];
2288
-
2289
-			// Fetch calendars and subscription
2290
-			$calendars = $this->getCalendarsForUser($principalUri);
2291
-			$subscriptions = $this->getSubscriptionsForUser($principalUri);
2292
-			foreach ($calendars as $calendar) {
2293
-				$calendarAnd = $calendarObjectIdQuery->expr()->andX(
2294
-					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])),
2295
-					$calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)),
2296
-				);
2297
-
2298
-				// If it's shared, limit search to public events
2299
-				if (isset($calendar['{http://owncloud.org/ns}owner-principal'])
2300
-					&& $calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
2301
-					$calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2302
-				}
2303
-
2304
-				$calendarOr[] = $calendarAnd;
2305
-			}
2306
-			foreach ($subscriptions as $subscription) {
2307
-				$subscriptionAnd = $calendarObjectIdQuery->expr()->andX(
2308
-					$calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])),
2309
-					$calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)),
2310
-				);
2311
-
2312
-				// If it's shared, limit search to public events
2313
-				if (isset($subscription['{http://owncloud.org/ns}owner-principal'])
2314
-					&& $subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
2315
-					$subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2316
-				}
2317
-
2318
-				$calendarOr[] = $subscriptionAnd;
2319
-			}
2320
-
2321
-			foreach ($searchProperties as $property) {
2322
-				$propertyAnd = $calendarObjectIdQuery->expr()->andX(
2323
-					$calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2324
-					$calendarObjectIdQuery->expr()->isNull('cob.parameter'),
2325
-				);
2326
-
2327
-				$searchOr[] = $propertyAnd;
2328
-			}
2329
-			foreach ($searchParameters as $property => $parameter) {
2330
-				$parameterAnd = $calendarObjectIdQuery->expr()->andX(
2331
-					$calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2332
-					$calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)),
2333
-				);
2334
-
2335
-				$searchOr[] = $parameterAnd;
2336
-			}
2337
-
2338
-			if (empty($calendarOr)) {
2339
-				return [];
2340
-			}
2341
-			if (empty($searchOr)) {
2342
-				return [];
2343
-			}
2344
-
2345
-			$calendarObjectIdQuery->selectDistinct('cob.objectid')
2346
-				->from($this->dbObjectPropertiesTable, 'cob')
2347
-				->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
2348
-				->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
2349
-				->andWhere($calendarObjectIdQuery->expr()->orX(...$calendarOr))
2350
-				->andWhere($calendarObjectIdQuery->expr()->orX(...$searchOr))
2351
-				->andWhere($calendarObjectIdQuery->expr()->isNull('deleted_at'));
2352
-
2353
-			if ($pattern !== '') {
2354
-				if (!$escapePattern) {
2355
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
2356
-				} else {
2357
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
2358
-				}
2359
-			}
2360
-
2361
-			if (isset($options['limit'])) {
2362
-				$calendarObjectIdQuery->setMaxResults($options['limit']);
2363
-			}
2364
-			if (isset($options['offset'])) {
2365
-				$calendarObjectIdQuery->setFirstResult($options['offset']);
2366
-			}
2367
-			if (isset($options['timerange'])) {
2368
-				if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2369
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->gt(
2370
-						'lastoccurence',
2371
-						$calendarObjectIdQuery->createNamedParameter($options['timerange']['start']->getTimeStamp()),
2372
-					));
2373
-				}
2374
-				if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2375
-					$calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->lt(
2376
-						'firstoccurence',
2377
-						$calendarObjectIdQuery->createNamedParameter($options['timerange']['end']->getTimeStamp()),
2378
-					));
2379
-				}
2380
-			}
2381
-
2382
-			$result = $calendarObjectIdQuery->executeQuery();
2383
-			$matches = [];
2384
-			while (($row = $result->fetch()) !== false) {
2385
-				$matches[] = (int)$row['objectid'];
2386
-			}
2387
-			$result->closeCursor();
2388
-
2389
-			$query = $this->db->getQueryBuilder();
2390
-			$query->select('calendardata', 'uri', 'calendarid', 'calendartype')
2391
-				->from('calendarobjects')
2392
-				->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
2393
-
2394
-			$result = $query->executeQuery();
2395
-			$calendarObjects = [];
2396
-			while (($array = $result->fetch()) !== false) {
2397
-				$array['calendarid'] = (int)$array['calendarid'];
2398
-				$array['calendartype'] = (int)$array['calendartype'];
2399
-				$array['calendardata'] = $this->readBlob($array['calendardata']);
2400
-
2401
-				$calendarObjects[] = $array;
2402
-			}
2403
-			$result->closeCursor();
2404
-			return $calendarObjects;
2405
-		}, $this->db);
2406
-	}
2407
-
2408
-	/**
2409
-	 * Searches through all of a users calendars and calendar objects to find
2410
-	 * an object with a specific UID.
2411
-	 *
2412
-	 * This method should return the path to this object, relative to the
2413
-	 * calendar home, so this path usually only contains two parts:
2414
-	 *
2415
-	 * calendarpath/objectpath.ics
2416
-	 *
2417
-	 * If the uid is not found, return null.
2418
-	 *
2419
-	 * This method should only consider * objects that the principal owns, so
2420
-	 * any calendars owned by other principals that also appear in this
2421
-	 * collection should be ignored.
2422
-	 *
2423
-	 * @param string $principalUri
2424
-	 * @param string $uid
2425
-	 * @return string|null
2426
-	 */
2427
-	public function getCalendarObjectByUID($principalUri, $uid) {
2428
-		$query = $this->db->getQueryBuilder();
2429
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
2430
-			->from('calendarobjects', 'co')
2431
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
2432
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2433
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
2434
-			->andWhere($query->expr()->isNull('co.deleted_at'));
2435
-		$stmt = $query->executeQuery();
2436
-		$row = $stmt->fetch();
2437
-		$stmt->closeCursor();
2438
-		if ($row) {
2439
-			return $row['calendaruri'] . '/' . $row['objecturi'];
2440
-		}
2441
-
2442
-		return null;
2443
-	}
2444
-
2445
-	public function getCalendarObjectById(string $principalUri, int $id): ?array {
2446
-		$query = $this->db->getQueryBuilder();
2447
-		$query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.calendardata', 'co.componenttype', 'co.classification', 'co.deleted_at'])
2448
-			->selectAlias('c.uri', 'calendaruri')
2449
-			->from('calendarobjects', 'co')
2450
-			->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
2451
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2452
-			->andWhere($query->expr()->eq('co.id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
2453
-		$stmt = $query->executeQuery();
2454
-		$row = $stmt->fetch();
2455
-		$stmt->closeCursor();
2456
-
2457
-		if (!$row) {
2458
-			return null;
2459
-		}
2460
-
2461
-		return [
2462
-			'id' => $row['id'],
2463
-			'uri' => $row['uri'],
2464
-			'lastmodified' => $row['lastmodified'],
2465
-			'etag' => '"' . $row['etag'] . '"',
2466
-			'calendarid' => $row['calendarid'],
2467
-			'calendaruri' => $row['calendaruri'],
2468
-			'size' => (int)$row['size'],
2469
-			'calendardata' => $this->readBlob($row['calendardata']),
2470
-			'component' => strtolower($row['componenttype']),
2471
-			'classification' => (int)$row['classification'],
2472
-			'deleted_at' => isset($row['deleted_at']) ? ((int)$row['deleted_at']) : null,
2473
-		];
2474
-	}
2475
-
2476
-	/**
2477
-	 * The getChanges method returns all the changes that have happened, since
2478
-	 * the specified syncToken in the specified calendar.
2479
-	 *
2480
-	 * This function should return an array, such as the following:
2481
-	 *
2482
-	 * [
2483
-	 *   'syncToken' => 'The current synctoken',
2484
-	 *   'added'   => [
2485
-	 *      'new.txt',
2486
-	 *   ],
2487
-	 *   'modified'   => [
2488
-	 *      'modified.txt',
2489
-	 *   ],
2490
-	 *   'deleted' => [
2491
-	 *      'foo.php.bak',
2492
-	 *      'old.txt'
2493
-	 *   ]
2494
-	 * );
2495
-	 *
2496
-	 * The returned syncToken property should reflect the *current* syncToken
2497
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
2498
-	 * property This is * needed here too, to ensure the operation is atomic.
2499
-	 *
2500
-	 * If the $syncToken argument is specified as null, this is an initial
2501
-	 * sync, and all members should be reported.
2502
-	 *
2503
-	 * The modified property is an array of nodenames that have changed since
2504
-	 * the last token.
2505
-	 *
2506
-	 * The deleted property is an array with nodenames, that have been deleted
2507
-	 * from collection.
2508
-	 *
2509
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
2510
-	 * 1, you only have to report changes that happened only directly in
2511
-	 * immediate descendants. If it's 2, it should also include changes from
2512
-	 * the nodes below the child collections. (grandchildren)
2513
-	 *
2514
-	 * The $limit argument allows a client to specify how many results should
2515
-	 * be returned at most. If the limit is not specified, it should be treated
2516
-	 * as infinite.
2517
-	 *
2518
-	 * If the limit (infinite or not) is higher than you're willing to return,
2519
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
2520
-	 *
2521
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
2522
-	 * return null.
2523
-	 *
2524
-	 * The limit is 'suggestive'. You are free to ignore it.
2525
-	 *
2526
-	 * @param string $calendarId
2527
-	 * @param string $syncToken
2528
-	 * @param int $syncLevel
2529
-	 * @param int|null $limit
2530
-	 * @param int $calendarType
2531
-	 * @return ?array
2532
-	 */
2533
-	public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2534
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2535
-
2536
-		return $this->atomic(function () use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
2537
-			// Current synctoken
2538
-			$qb = $this->db->getQueryBuilder();
2539
-			$qb->select('synctoken')
2540
-				->from($table)
2541
-				->where(
2542
-					$qb->expr()->eq('id', $qb->createNamedParameter($calendarId))
2543
-				);
2544
-			$stmt = $qb->executeQuery();
2545
-			$currentToken = $stmt->fetchOne();
2546
-			$initialSync = !is_numeric($syncToken);
2547
-
2548
-			if ($currentToken === false) {
2549
-				return null;
2550
-			}
2551
-
2552
-			// evaluate if this is a initial sync and construct appropriate command
2553
-			if ($initialSync) {
2554
-				$qb = $this->db->getQueryBuilder();
2555
-				$qb->select('uri')
2556
-					->from('calendarobjects')
2557
-					->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2558
-					->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2559
-					->andWhere($qb->expr()->isNull('deleted_at'));
2560
-			} else {
2561
-				$qb = $this->db->getQueryBuilder();
2562
-				$qb->select('uri', $qb->func()->max('operation'))
2563
-					->from('calendarchanges')
2564
-					->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2565
-					->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2566
-					->andWhere($qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)))
2567
-					->andWhere($qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)))
2568
-					->groupBy('uri');
2569
-			}
2570
-			// evaluate if limit exists
2571
-			if (is_numeric($limit)) {
2572
-				$qb->setMaxResults($limit);
2573
-			}
2574
-			// execute command
2575
-			$stmt = $qb->executeQuery();
2576
-			// build results
2577
-			$result = ['syncToken' => $currentToken, 'added' => [], 'modified' => [], 'deleted' => []];
2578
-			// retrieve results
2579
-			if ($initialSync) {
2580
-				$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
2581
-			} else {
2582
-				// \PDO::FETCH_NUM is needed due to the inconsistent field names
2583
-				// produced by doctrine for MAX() with different databases
2584
-				while ($entry = $stmt->fetch(\PDO::FETCH_NUM)) {
2585
-					// assign uri (column 0) to appropriate mutation based on operation (column 1)
2586
-					// forced (int) is needed as doctrine with OCI returns the operation field as string not integer
2587
-					match ((int)$entry[1]) {
2588
-						1 => $result['added'][] = $entry[0],
2589
-						2 => $result['modified'][] = $entry[0],
2590
-						3 => $result['deleted'][] = $entry[0],
2591
-						default => $this->logger->debug('Unknown calendar change operation detected')
2592
-					};
2593
-				}
2594
-			}
2595
-			$stmt->closeCursor();
2596
-
2597
-			return $result;
2598
-		}, $this->db);
2599
-	}
2600
-
2601
-	/**
2602
-	 * Returns a list of subscriptions for a principal.
2603
-	 *
2604
-	 * Every subscription is an array with the following keys:
2605
-	 *  * id, a unique id that will be used by other functions to modify the
2606
-	 *    subscription. This can be the same as the uri or a database key.
2607
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
2608
-	 *  * principaluri. The owner of the subscription. Almost always the same as
2609
-	 *    principalUri passed to this method.
2610
-	 *
2611
-	 * Furthermore, all the subscription info must be returned too:
2612
-	 *
2613
-	 * 1. {DAV:}displayname
2614
-	 * 2. {http://apple.com/ns/ical/}refreshrate
2615
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
2616
-	 *    should not be stripped).
2617
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
2618
-	 *    should not be stripped).
2619
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
2620
-	 *    attachments should not be stripped).
2621
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
2622
-	 *     Sabre\DAV\Property\Href).
2623
-	 * 7. {http://apple.com/ns/ical/}calendar-color
2624
-	 * 8. {http://apple.com/ns/ical/}calendar-order
2625
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
2626
-	 *    (should just be an instance of
2627
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
2628
-	 *    default components).
2629
-	 *
2630
-	 * @param string $principalUri
2631
-	 * @return array
2632
-	 */
2633
-	public function getSubscriptionsForUser($principalUri) {
2634
-		$fields = array_column($this->subscriptionPropertyMap, 0);
2635
-		$fields[] = 'id';
2636
-		$fields[] = 'uri';
2637
-		$fields[] = 'source';
2638
-		$fields[] = 'principaluri';
2639
-		$fields[] = 'lastmodified';
2640
-		$fields[] = 'synctoken';
2641
-
2642
-		$query = $this->db->getQueryBuilder();
2643
-		$query->select($fields)
2644
-			->from('calendarsubscriptions')
2645
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2646
-			->orderBy('calendarorder', 'asc');
2647
-		$stmt = $query->executeQuery();
2648
-
2649
-		$subscriptions = [];
2650
-		while ($row = $stmt->fetch()) {
2651
-			$subscription = [
2652
-				'id' => $row['id'],
2653
-				'uri' => $row['uri'],
2654
-				'principaluri' => $row['principaluri'],
2655
-				'source' => $row['source'],
2656
-				'lastmodified' => $row['lastmodified'],
2657
-
2658
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2659
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
2660
-			];
2661
-
2662
-			$subscriptions[] = $this->rowToSubscription($row, $subscription);
2663
-		}
2664
-
2665
-		return $subscriptions;
2666
-	}
2667
-
2668
-	/**
2669
-	 * Creates a new subscription for a principal.
2670
-	 *
2671
-	 * If the creation was a success, an id must be returned that can be used to reference
2672
-	 * this subscription in other methods, such as updateSubscription.
2673
-	 *
2674
-	 * @param string $principalUri
2675
-	 * @param string $uri
2676
-	 * @param array $properties
2677
-	 * @return mixed
2678
-	 */
2679
-	public function createSubscription($principalUri, $uri, array $properties) {
2680
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2681
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2682
-		}
2683
-
2684
-		$values = [
2685
-			'principaluri' => $principalUri,
2686
-			'uri' => $uri,
2687
-			'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2688
-			'lastmodified' => time(),
2689
-		];
2690
-
2691
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2692
-
2693
-		foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
2694
-			if (array_key_exists($xmlName, $properties)) {
2695
-				$values[$dbName] = $properties[$xmlName];
2696
-				if (in_array($dbName, $propertiesBoolean)) {
2697
-					$values[$dbName] = true;
2698
-				}
2699
-			}
2700
-		}
2701
-
2702
-		[$subscriptionId, $subscriptionRow] = $this->atomic(function () use ($values) {
2703
-			$valuesToInsert = [];
2704
-			$query = $this->db->getQueryBuilder();
2705
-			foreach (array_keys($values) as $name) {
2706
-				$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2707
-			}
2708
-			$query->insert('calendarsubscriptions')
2709
-				->values($valuesToInsert)
2710
-				->executeStatement();
2711
-
2712
-			$subscriptionId = $query->getLastInsertId();
2713
-
2714
-			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2715
-			return [$subscriptionId, $subscriptionRow];
2716
-		}, $this->db);
2717
-
2718
-		$this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow));
2719
-
2720
-		return $subscriptionId;
2721
-	}
2722
-
2723
-	/**
2724
-	 * Updates a subscription
2725
-	 *
2726
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2727
-	 * To do the actual updates, you must tell this object which properties
2728
-	 * you're going to process with the handle() method.
2729
-	 *
2730
-	 * Calling the handle method is like telling the PropPatch object "I
2731
-	 * promise I can handle updating this property".
2732
-	 *
2733
-	 * Read the PropPatch documentation for more info and examples.
2734
-	 *
2735
-	 * @param mixed $subscriptionId
2736
-	 * @param PropPatch $propPatch
2737
-	 * @return void
2738
-	 */
2739
-	public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2740
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
2741
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
2742
-
2743
-		$propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2744
-			$newValues = [];
2745
-
2746
-			foreach ($mutations as $propertyName => $propertyValue) {
2747
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
2748
-					$newValues['source'] = $propertyValue->getHref();
2749
-				} else {
2750
-					$fieldName = $this->subscriptionPropertyMap[$propertyName][0];
2751
-					$newValues[$fieldName] = $propertyValue;
2752
-				}
2753
-			}
2754
-
2755
-			$subscriptionRow = $this->atomic(function () use ($subscriptionId, $newValues) {
2756
-				$query = $this->db->getQueryBuilder();
2757
-				$query->update('calendarsubscriptions')
2758
-					->set('lastmodified', $query->createNamedParameter(time()));
2759
-				foreach ($newValues as $fieldName => $value) {
2760
-					$query->set($fieldName, $query->createNamedParameter($value));
2761
-				}
2762
-				$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2763
-					->executeStatement();
2764
-
2765
-				return $this->getSubscriptionById($subscriptionId);
2766
-			}, $this->db);
2767
-
2768
-			$this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2769
-
2770
-			return true;
2771
-		});
2772
-	}
2773
-
2774
-	/**
2775
-	 * Deletes a subscription.
2776
-	 *
2777
-	 * @param mixed $subscriptionId
2778
-	 * @return void
2779
-	 */
2780
-	public function deleteSubscription($subscriptionId) {
2781
-		$this->atomic(function () use ($subscriptionId): void {
2782
-			$subscriptionRow = $this->getSubscriptionById($subscriptionId);
2783
-
2784
-			$query = $this->db->getQueryBuilder();
2785
-			$query->delete('calendarsubscriptions')
2786
-				->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2787
-				->executeStatement();
2788
-
2789
-			$query = $this->db->getQueryBuilder();
2790
-			$query->delete('calendarobjects')
2791
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2792
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2793
-				->executeStatement();
2794
-
2795
-			$query->delete('calendarchanges')
2796
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2797
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2798
-				->executeStatement();
2799
-
2800
-			$query->delete($this->dbObjectPropertiesTable)
2801
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2802
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2803
-				->executeStatement();
2804
-
2805
-			if ($subscriptionRow) {
2806
-				$this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2807
-			}
2808
-		}, $this->db);
2809
-	}
2810
-
2811
-	/**
2812
-	 * Returns a single scheduling object for the inbox collection.
2813
-	 *
2814
-	 * The returned array should contain the following elements:
2815
-	 *   * uri - A unique basename for the object. This will be used to
2816
-	 *           construct a full uri.
2817
-	 *   * calendardata - The iCalendar object
2818
-	 *   * lastmodified - The last modification date. Can be an int for a unix
2819
-	 *                    timestamp, or a PHP DateTime object.
2820
-	 *   * etag - A unique token that must change if the object changed.
2821
-	 *   * size - The size of the object, in bytes.
2822
-	 *
2823
-	 * @param string $principalUri
2824
-	 * @param string $objectUri
2825
-	 * @return array
2826
-	 */
2827
-	public function getSchedulingObject($principalUri, $objectUri) {
2828
-		$query = $this->db->getQueryBuilder();
2829
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2830
-			->from('schedulingobjects')
2831
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2832
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2833
-			->executeQuery();
2834
-
2835
-		$row = $stmt->fetch();
2836
-
2837
-		if (!$row) {
2838
-			return null;
2839
-		}
2840
-
2841
-		return [
2842
-			'uri' => $row['uri'],
2843
-			'calendardata' => $row['calendardata'],
2844
-			'lastmodified' => $row['lastmodified'],
2845
-			'etag' => '"' . $row['etag'] . '"',
2846
-			'size' => (int)$row['size'],
2847
-		];
2848
-	}
2849
-
2850
-	/**
2851
-	 * Returns all scheduling objects for the inbox collection.
2852
-	 *
2853
-	 * These objects should be returned as an array. Every item in the array
2854
-	 * should follow the same structure as returned from getSchedulingObject.
2855
-	 *
2856
-	 * The main difference is that 'calendardata' is optional.
2857
-	 *
2858
-	 * @param string $principalUri
2859
-	 * @return array
2860
-	 */
2861
-	public function getSchedulingObjects($principalUri) {
2862
-		$query = $this->db->getQueryBuilder();
2863
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2864
-			->from('schedulingobjects')
2865
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2866
-			->executeQuery();
2867
-
2868
-		$results = [];
2869
-		while (($row = $stmt->fetch()) !== false) {
2870
-			$results[] = [
2871
-				'calendardata' => $row['calendardata'],
2872
-				'uri' => $row['uri'],
2873
-				'lastmodified' => $row['lastmodified'],
2874
-				'etag' => '"' . $row['etag'] . '"',
2875
-				'size' => (int)$row['size'],
2876
-			];
2877
-		}
2878
-		$stmt->closeCursor();
2879
-
2880
-		return $results;
2881
-	}
2882
-
2883
-	/**
2884
-	 * Deletes a scheduling object from the inbox collection.
2885
-	 *
2886
-	 * @param string $principalUri
2887
-	 * @param string $objectUri
2888
-	 * @return void
2889
-	 */
2890
-	public function deleteSchedulingObject($principalUri, $objectUri) {
2891
-		$this->cachedObjects = [];
2892
-		$query = $this->db->getQueryBuilder();
2893
-		$query->delete('schedulingobjects')
2894
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2895
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2896
-			->executeStatement();
2897
-	}
2898
-
2899
-	/**
2900
-	 * Deletes all scheduling objects last modified before $modifiedBefore from the inbox collection.
2901
-	 *
2902
-	 * @param int $modifiedBefore
2903
-	 * @param int $limit
2904
-	 * @return void
2905
-	 */
2906
-	public function deleteOutdatedSchedulingObjects(int $modifiedBefore, int $limit): void {
2907
-		$query = $this->db->getQueryBuilder();
2908
-		$query->select('id')
2909
-			->from('schedulingobjects')
2910
-			->where($query->expr()->lt('lastmodified', $query->createNamedParameter($modifiedBefore)))
2911
-			->setMaxResults($limit);
2912
-		$result = $query->executeQuery();
2913
-		$count = $result->rowCount();
2914
-		if ($count === 0) {
2915
-			return;
2916
-		}
2917
-		$ids = array_map(static function (array $id) {
2918
-			return (int)$id[0];
2919
-		}, $result->fetchAll(\PDO::FETCH_NUM));
2920
-		$result->closeCursor();
2921
-
2922
-		$numDeleted = 0;
2923
-		$deleteQuery = $this->db->getQueryBuilder();
2924
-		$deleteQuery->delete('schedulingobjects')
2925
-			->where($deleteQuery->expr()->in('id', $deleteQuery->createParameter('ids'), IQueryBuilder::PARAM_INT_ARRAY));
2926
-		foreach (array_chunk($ids, 1000) as $chunk) {
2927
-			$deleteQuery->setParameter('ids', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
2928
-			$numDeleted += $deleteQuery->executeStatement();
2929
-		}
2930
-
2931
-		if ($numDeleted === $limit) {
2932
-			$this->logger->info("Deleted $limit scheduling objects, continuing with next batch");
2933
-			$this->deleteOutdatedSchedulingObjects($modifiedBefore, $limit);
2934
-		}
2935
-	}
2936
-
2937
-	/**
2938
-	 * Creates a new scheduling object. This should land in a users' inbox.
2939
-	 *
2940
-	 * @param string $principalUri
2941
-	 * @param string $objectUri
2942
-	 * @param string $objectData
2943
-	 * @return void
2944
-	 */
2945
-	public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2946
-		$this->cachedObjects = [];
2947
-		$query = $this->db->getQueryBuilder();
2948
-		$query->insert('schedulingobjects')
2949
-			->values([
2950
-				'principaluri' => $query->createNamedParameter($principalUri),
2951
-				'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2952
-				'uri' => $query->createNamedParameter($objectUri),
2953
-				'lastmodified' => $query->createNamedParameter(time()),
2954
-				'etag' => $query->createNamedParameter(md5($objectData)),
2955
-				'size' => $query->createNamedParameter(strlen($objectData))
2956
-			])
2957
-			->executeStatement();
2958
-	}
2959
-
2960
-	/**
2961
-	 * Adds a change record to the calendarchanges table.
2962
-	 *
2963
-	 * @param mixed $calendarId
2964
-	 * @param string[] $objectUris
2965
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2966
-	 * @param int $calendarType
2967
-	 * @return void
2968
-	 */
2969
-	protected function addChanges(int $calendarId, array $objectUris, int $operation, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
2970
-		$this->cachedObjects = [];
2971
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2972
-
2973
-		$this->atomic(function () use ($calendarId, $objectUris, $operation, $calendarType, $table): void {
2974
-			$query = $this->db->getQueryBuilder();
2975
-			$query->select('synctoken')
2976
-				->from($table)
2977
-				->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2978
-			$result = $query->executeQuery();
2979
-			$syncToken = (int)$result->fetchOne();
2980
-			$result->closeCursor();
2981
-
2982
-			$query = $this->db->getQueryBuilder();
2983
-			$query->insert('calendarchanges')
2984
-				->values([
2985
-					'uri' => $query->createParameter('uri'),
2986
-					'synctoken' => $query->createNamedParameter($syncToken),
2987
-					'calendarid' => $query->createNamedParameter($calendarId),
2988
-					'operation' => $query->createNamedParameter($operation),
2989
-					'calendartype' => $query->createNamedParameter($calendarType),
2990
-					'created_at' => $query->createNamedParameter(time()),
2991
-				]);
2992
-			foreach ($objectUris as $uri) {
2993
-				$query->setParameter('uri', $uri);
2994
-				$query->executeStatement();
2995
-			}
2996
-
2997
-			$query = $this->db->getQueryBuilder();
2998
-			$query->update($table)
2999
-				->set('synctoken', $query->createNamedParameter($syncToken + 1, IQueryBuilder::PARAM_INT))
3000
-				->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
3001
-				->executeStatement();
3002
-		}, $this->db);
3003
-	}
3004
-
3005
-	public function restoreChanges(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
3006
-		$this->cachedObjects = [];
3007
-
3008
-		$this->atomic(function () use ($calendarId, $calendarType): void {
3009
-			$qbAdded = $this->db->getQueryBuilder();
3010
-			$qbAdded->select('uri')
3011
-				->from('calendarobjects')
3012
-				->where(
3013
-					$qbAdded->expr()->andX(
3014
-						$qbAdded->expr()->eq('calendarid', $qbAdded->createNamedParameter($calendarId)),
3015
-						$qbAdded->expr()->eq('calendartype', $qbAdded->createNamedParameter($calendarType)),
3016
-						$qbAdded->expr()->isNull('deleted_at'),
3017
-					)
3018
-				);
3019
-			$resultAdded = $qbAdded->executeQuery();
3020
-			$addedUris = $resultAdded->fetchAll(\PDO::FETCH_COLUMN);
3021
-			$resultAdded->closeCursor();
3022
-			// Track everything as changed
3023
-			// Tracking the creation is not necessary because \OCA\DAV\CalDAV\CalDavBackend::getChangesForCalendar
3024
-			// only returns the last change per object.
3025
-			$this->addChanges($calendarId, $addedUris, 2, $calendarType);
3026
-
3027
-			$qbDeleted = $this->db->getQueryBuilder();
3028
-			$qbDeleted->select('uri')
3029
-				->from('calendarobjects')
3030
-				->where(
3031
-					$qbDeleted->expr()->andX(
3032
-						$qbDeleted->expr()->eq('calendarid', $qbDeleted->createNamedParameter($calendarId)),
3033
-						$qbDeleted->expr()->eq('calendartype', $qbDeleted->createNamedParameter($calendarType)),
3034
-						$qbDeleted->expr()->isNotNull('deleted_at'),
3035
-					)
3036
-				);
3037
-			$resultDeleted = $qbDeleted->executeQuery();
3038
-			$deletedUris = array_map(function (string $uri) {
3039
-				return str_replace('-deleted.ics', '.ics', $uri);
3040
-			}, $resultDeleted->fetchAll(\PDO::FETCH_COLUMN));
3041
-			$resultDeleted->closeCursor();
3042
-			$this->addChanges($calendarId, $deletedUris, 3, $calendarType);
3043
-		}, $this->db);
3044
-	}
3045
-
3046
-	/**
3047
-	 * Parses some information from calendar objects, used for optimized
3048
-	 * calendar-queries.
3049
-	 *
3050
-	 * Returns an array with the following keys:
3051
-	 *   * etag - An md5 checksum of the object without the quotes.
3052
-	 *   * size - Size of the object in bytes
3053
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
3054
-	 *   * firstOccurence
3055
-	 *   * lastOccurence
3056
-	 *   * uid - value of the UID property
3057
-	 *
3058
-	 * @param string $calendarData
3059
-	 * @return array
3060
-	 */
3061
-	public function getDenormalizedData(string $calendarData): array {
3062
-		$vObject = Reader::read($calendarData);
3063
-		$vEvents = [];
3064
-		$componentType = null;
3065
-		$component = null;
3066
-		$firstOccurrence = null;
3067
-		$lastOccurrence = null;
3068
-		$uid = null;
3069
-		$classification = self::CLASSIFICATION_PUBLIC;
3070
-		$hasDTSTART = false;
3071
-		foreach ($vObject->getComponents() as $component) {
3072
-			if ($component->name !== 'VTIMEZONE') {
3073
-				// Finding all VEVENTs, and track them
3074
-				if ($component->name === 'VEVENT') {
3075
-					$vEvents[] = $component;
3076
-					if ($component->DTSTART) {
3077
-						$hasDTSTART = true;
3078
-					}
3079
-				}
3080
-				// Track first component type and uid
3081
-				if ($uid === null) {
3082
-					$componentType = $component->name;
3083
-					$uid = (string)$component->UID;
3084
-				}
3085
-			}
3086
-		}
3087
-		if (!$componentType) {
3088
-			throw new BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
3089
-		}
3090
-
3091
-		if ($hasDTSTART) {
3092
-			$component = $vEvents[0];
3093
-
3094
-			// Finding the last occurrence is a bit harder
3095
-			if (!isset($component->RRULE) && count($vEvents) === 1) {
3096
-				$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
3097
-				if (isset($component->DTEND)) {
3098
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
3099
-				} elseif (isset($component->DURATION)) {
3100
-					$endDate = clone $component->DTSTART->getDateTime();
3101
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
3102
-					$lastOccurrence = $endDate->getTimeStamp();
3103
-				} elseif (!$component->DTSTART->hasTime()) {
3104
-					$endDate = clone $component->DTSTART->getDateTime();
3105
-					$endDate->modify('+1 day');
3106
-					$lastOccurrence = $endDate->getTimeStamp();
3107
-				} else {
3108
-					$lastOccurrence = $firstOccurrence;
3109
-				}
3110
-			} else {
3111
-				try {
3112
-					$it = new EventIterator($vEvents);
3113
-				} catch (NoInstancesException $e) {
3114
-					$this->logger->debug('Caught no instance exception for calendar data. This usually indicates invalid calendar data.', [
3115
-						'app' => 'dav',
3116
-						'exception' => $e,
3117
-					]);
3118
-					throw new Forbidden($e->getMessage());
3119
-				}
3120
-				$maxDate = new DateTime(self::MAX_DATE);
3121
-				$firstOccurrence = $it->getDtStart()->getTimestamp();
3122
-				if ($it->isInfinite()) {
3123
-					$lastOccurrence = $maxDate->getTimestamp();
3124
-				} else {
3125
-					$end = $it->getDtEnd();
3126
-					while ($it->valid() && $end < $maxDate) {
3127
-						$end = $it->getDtEnd();
3128
-						$it->next();
3129
-					}
3130
-					$lastOccurrence = $end->getTimestamp();
3131
-				}
3132
-			}
3133
-		}
3134
-
3135
-		if ($component->CLASS) {
3136
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
3137
-			switch ($component->CLASS->getValue()) {
3138
-				case 'PUBLIC':
3139
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
3140
-					break;
3141
-				case 'CONFIDENTIAL':
3142
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
3143
-					break;
3144
-			}
3145
-		}
3146
-		return [
3147
-			'etag' => md5($calendarData),
3148
-			'size' => strlen($calendarData),
3149
-			'componentType' => $componentType,
3150
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
3151
-			'lastOccurence' => is_null($lastOccurrence) ? null : max(0, $lastOccurrence),
3152
-			'uid' => $uid,
3153
-			'classification' => $classification
3154
-		];
3155
-	}
3156
-
3157
-	/**
3158
-	 * @param $cardData
3159
-	 * @return bool|string
3160
-	 */
3161
-	private function readBlob($cardData) {
3162
-		if (is_resource($cardData)) {
3163
-			return stream_get_contents($cardData);
3164
-		}
3165
-
3166
-		return $cardData;
3167
-	}
3168
-
3169
-	/**
3170
-	 * @param list<array{href: string, commonName: string, readOnly: bool}> $add
3171
-	 * @param list<string> $remove
3172
-	 */
3173
-	public function updateShares(IShareable $shareable, array $add, array $remove): void {
3174
-		$this->atomic(function () use ($shareable, $add, $remove): void {
3175
-			$calendarId = $shareable->getResourceId();
3176
-			$calendarRow = $this->getCalendarById($calendarId);
3177
-			if ($calendarRow === null) {
3178
-				throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $calendarId);
3179
-			}
3180
-			$oldShares = $this->getShares($calendarId);
3181
-
3182
-			$this->calendarSharingBackend->updateShares($shareable, $add, $remove, $oldShares);
3183
-
3184
-			$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent($calendarId, $calendarRow, $oldShares, $add, $remove));
3185
-		}, $this->db);
3186
-	}
3187
-
3188
-	/**
3189
-	 * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
3190
-	 */
3191
-	public function getShares(int $resourceId): array {
3192
-		return $this->calendarSharingBackend->getShares($resourceId);
3193
-	}
3194
-
3195
-	public function preloadShares(array $resourceIds): void {
3196
-		$this->calendarSharingBackend->preloadShares($resourceIds);
3197
-	}
3198
-
3199
-	/**
3200
-	 * @param boolean $value
3201
-	 * @param Calendar $calendar
3202
-	 * @return string|null
3203
-	 */
3204
-	public function setPublishStatus($value, $calendar) {
3205
-		return $this->atomic(function () use ($value, $calendar) {
3206
-			$calendarId = $calendar->getResourceId();
3207
-			$calendarData = $this->getCalendarById($calendarId);
3208
-
3209
-			$query = $this->db->getQueryBuilder();
3210
-			if ($value) {
3211
-				$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
3212
-				$query->insert('dav_shares')
3213
-					->values([
3214
-						'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
3215
-						'type' => $query->createNamedParameter('calendar'),
3216
-						'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
3217
-						'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
3218
-						'publicuri' => $query->createNamedParameter($publicUri)
3219
-					]);
3220
-				$query->executeStatement();
3221
-
3222
-				$this->dispatcher->dispatchTyped(new CalendarPublishedEvent($calendarId, $calendarData, $publicUri));
3223
-				return $publicUri;
3224
-			}
3225
-			$query->delete('dav_shares')
3226
-				->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3227
-				->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
3228
-			$query->executeStatement();
3229
-
3230
-			$this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent($calendarId, $calendarData));
3231
-			return null;
3232
-		}, $this->db);
3233
-	}
3234
-
3235
-	/**
3236
-	 * @param Calendar $calendar
3237
-	 * @return mixed
3238
-	 */
3239
-	public function getPublishStatus($calendar) {
3240
-		$query = $this->db->getQueryBuilder();
3241
-		$result = $query->select('publicuri')
3242
-			->from('dav_shares')
3243
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3244
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
3245
-			->executeQuery();
3246
-
3247
-		$row = $result->fetch();
3248
-		$result->closeCursor();
3249
-		return $row ? reset($row) : false;
3250
-	}
3251
-
3252
-	/**
3253
-	 * @param int $resourceId
3254
-	 * @param list<array{privilege: string, principal: string, protected: bool}> $acl
3255
-	 * @return list<array{privilege: string, principal: string, protected: bool}>
3256
-	 */
3257
-	public function applyShareAcl(int $resourceId, array $acl): array {
3258
-		$shares = $this->calendarSharingBackend->getShares($resourceId);
3259
-		return $this->calendarSharingBackend->applyShareAcl($shares, $acl);
3260
-	}
3261
-
3262
-	/**
3263
-	 * update properties table
3264
-	 *
3265
-	 * @param int $calendarId
3266
-	 * @param string $objectUri
3267
-	 * @param string $calendarData
3268
-	 * @param int $calendarType
3269
-	 */
3270
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
3271
-		$this->cachedObjects = [];
3272
-		$this->atomic(function () use ($calendarId, $objectUri, $calendarData, $calendarType): void {
3273
-			$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
3274
-
3275
-			try {
3276
-				$vCalendar = $this->readCalendarData($calendarData);
3277
-			} catch (\Exception $ex) {
3278
-				return;
3279
-			}
3280
-
3281
-			$this->purgeProperties($calendarId, $objectId);
3282
-
3283
-			$query = $this->db->getQueryBuilder();
3284
-			$query->insert($this->dbObjectPropertiesTable)
3285
-				->values(
3286
-					[
3287
-						'calendarid' => $query->createNamedParameter($calendarId),
3288
-						'calendartype' => $query->createNamedParameter($calendarType),
3289
-						'objectid' => $query->createNamedParameter($objectId),
3290
-						'name' => $query->createParameter('name'),
3291
-						'parameter' => $query->createParameter('parameter'),
3292
-						'value' => $query->createParameter('value'),
3293
-					]
3294
-				);
3295
-
3296
-			$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
3297
-			foreach ($vCalendar->getComponents() as $component) {
3298
-				if (!in_array($component->name, $indexComponents)) {
3299
-					continue;
3300
-				}
3301
-
3302
-				foreach ($component->children() as $property) {
3303
-					if (in_array($property->name, self::INDEXED_PROPERTIES, true)) {
3304
-						$value = $property->getValue();
3305
-						// is this a shitty db?
3306
-						if (!$this->db->supports4ByteText()) {
3307
-							$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3308
-						}
3309
-						$value = mb_strcut($value, 0, 254);
3310
-
3311
-						$query->setParameter('name', $property->name);
3312
-						$query->setParameter('parameter', null);
3313
-						$query->setParameter('value', mb_strcut($value, 0, 254));
3314
-						$query->executeStatement();
3315
-					}
3316
-
3317
-					if (array_key_exists($property->name, self::$indexParameters)) {
3318
-						$parameters = $property->parameters();
3319
-						$indexedParametersForProperty = self::$indexParameters[$property->name];
3320
-
3321
-						foreach ($parameters as $key => $value) {
3322
-							if (in_array($key, $indexedParametersForProperty)) {
3323
-								// is this a shitty db?
3324
-								if ($this->db->supports4ByteText()) {
3325
-									$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3326
-								}
3327
-
3328
-								$query->setParameter('name', $property->name);
3329
-								$query->setParameter('parameter', mb_strcut($key, 0, 254));
3330
-								$query->setParameter('value', mb_strcut($value, 0, 254));
3331
-								$query->executeStatement();
3332
-							}
3333
-						}
3334
-					}
3335
-				}
3336
-			}
3337
-		}, $this->db);
3338
-	}
3339
-
3340
-	/**
3341
-	 * deletes all birthday calendars
3342
-	 */
3343
-	public function deleteAllBirthdayCalendars() {
3344
-		$this->atomic(function (): void {
3345
-			$query = $this->db->getQueryBuilder();
3346
-			$result = $query->select(['id'])->from('calendars')
3347
-				->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
3348
-				->executeQuery();
3349
-
3350
-			while (($row = $result->fetch()) !== false) {
3351
-				$this->deleteCalendar(
3352
-					$row['id'],
3353
-					true // No data to keep in the trashbin, if the user re-enables then we regenerate
3354
-				);
3355
-			}
3356
-			$result->closeCursor();
3357
-		}, $this->db);
3358
-	}
3359
-
3360
-	/**
3361
-	 * @param $subscriptionId
3362
-	 */
3363
-	public function purgeAllCachedEventsForSubscription($subscriptionId) {
3364
-		$this->atomic(function () use ($subscriptionId): void {
3365
-			$query = $this->db->getQueryBuilder();
3366
-			$query->select('uri')
3367
-				->from('calendarobjects')
3368
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3369
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
3370
-			$stmt = $query->executeQuery();
3371
-
3372
-			$uris = [];
3373
-			while (($row = $stmt->fetch()) !== false) {
3374
-				$uris[] = $row['uri'];
3375
-			}
3376
-			$stmt->closeCursor();
3377
-
3378
-			$query = $this->db->getQueryBuilder();
3379
-			$query->delete('calendarobjects')
3380
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3381
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3382
-				->executeStatement();
3383
-
3384
-			$query = $this->db->getQueryBuilder();
3385
-			$query->delete('calendarchanges')
3386
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3387
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3388
-				->executeStatement();
3389
-
3390
-			$query = $this->db->getQueryBuilder();
3391
-			$query->delete($this->dbObjectPropertiesTable)
3392
-				->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3393
-				->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3394
-				->executeStatement();
3395
-
3396
-			$this->addChanges($subscriptionId, $uris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3397
-		}, $this->db);
3398
-	}
3399
-
3400
-	/**
3401
-	 * @param int $subscriptionId
3402
-	 * @param array<int> $calendarObjectIds
3403
-	 * @param array<string> $calendarObjectUris
3404
-	 */
3405
-	public function purgeCachedEventsForSubscription(int $subscriptionId, array $calendarObjectIds, array $calendarObjectUris): void {
3406
-		if (empty($calendarObjectUris)) {
3407
-			return;
3408
-		}
3409
-
3410
-		$this->atomic(function () use ($subscriptionId, $calendarObjectIds, $calendarObjectUris): void {
3411
-			foreach (array_chunk($calendarObjectIds, 1000) as $chunk) {
3412
-				$query = $this->db->getQueryBuilder();
3413
-				$query->delete($this->dbObjectPropertiesTable)
3414
-					->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3415
-					->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3416
-					->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3417
-					->executeStatement();
3418
-
3419
-				$query = $this->db->getQueryBuilder();
3420
-				$query->delete('calendarobjects')
3421
-					->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3422
-					->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3423
-					->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3424
-					->executeStatement();
3425
-			}
3426
-
3427
-			foreach (array_chunk($calendarObjectUris, 1000) as $chunk) {
3428
-				$query = $this->db->getQueryBuilder();
3429
-				$query->delete('calendarchanges')
3430
-					->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3431
-					->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3432
-					->andWhere($query->expr()->in('uri', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
3433
-					->executeStatement();
3434
-			}
3435
-			$this->addChanges($subscriptionId, $calendarObjectUris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3436
-		}, $this->db);
3437
-	}
3438
-
3439
-	/**
3440
-	 * Move a calendar from one user to another
3441
-	 *
3442
-	 * @param string $uriName
3443
-	 * @param string $uriOrigin
3444
-	 * @param string $uriDestination
3445
-	 * @param string $newUriName (optional) the new uriName
3446
-	 */
3447
-	public function moveCalendar($uriName, $uriOrigin, $uriDestination, $newUriName = null) {
3448
-		$query = $this->db->getQueryBuilder();
3449
-		$query->update('calendars')
3450
-			->set('principaluri', $query->createNamedParameter($uriDestination))
3451
-			->set('uri', $query->createNamedParameter($newUriName ?: $uriName))
3452
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
3453
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
3454
-			->executeStatement();
3455
-	}
3456
-
3457
-	/**
3458
-	 * read VCalendar data into a VCalendar object
3459
-	 *
3460
-	 * @param string $objectData
3461
-	 * @return VCalendar
3462
-	 */
3463
-	protected function readCalendarData($objectData) {
3464
-		return Reader::read($objectData);
3465
-	}
3466
-
3467
-	/**
3468
-	 * delete all properties from a given calendar object
3469
-	 *
3470
-	 * @param int $calendarId
3471
-	 * @param int $objectId
3472
-	 */
3473
-	protected function purgeProperties($calendarId, $objectId) {
3474
-		$this->cachedObjects = [];
3475
-		$query = $this->db->getQueryBuilder();
3476
-		$query->delete($this->dbObjectPropertiesTable)
3477
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
3478
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
3479
-		$query->executeStatement();
3480
-	}
3481
-
3482
-	/**
3483
-	 * get ID from a given calendar object
3484
-	 *
3485
-	 * @param int $calendarId
3486
-	 * @param string $uri
3487
-	 * @param int $calendarType
3488
-	 * @return int
3489
-	 */
3490
-	protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
3491
-		$query = $this->db->getQueryBuilder();
3492
-		$query->select('id')
3493
-			->from('calendarobjects')
3494
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
3495
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
3496
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
3497
-
3498
-		$result = $query->executeQuery();
3499
-		$objectIds = $result->fetch();
3500
-		$result->closeCursor();
3501
-
3502
-		if (!isset($objectIds['id'])) {
3503
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
3504
-		}
3505
-
3506
-		return (int)$objectIds['id'];
3507
-	}
3508
-
3509
-	/**
3510
-	 * @throws \InvalidArgumentException
3511
-	 */
3512
-	public function pruneOutdatedSyncTokens(int $keep, int $retention): int {
3513
-		if ($keep < 0) {
3514
-			throw new \InvalidArgumentException();
3515
-		}
3516
-
3517
-		$query = $this->db->getQueryBuilder();
3518
-		$query->select($query->func()->max('id'))
3519
-			->from('calendarchanges');
3520
-
3521
-		$result = $query->executeQuery();
3522
-		$maxId = (int)$result->fetchOne();
3523
-		$result->closeCursor();
3524
-		if (!$maxId || $maxId < $keep) {
3525
-			return 0;
3526
-		}
3527
-
3528
-		$query = $this->db->getQueryBuilder();
3529
-		$query->delete('calendarchanges')
3530
-			->where(
3531
-				$query->expr()->lte('id', $query->createNamedParameter($maxId - $keep, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
3532
-				$query->expr()->lte('created_at', $query->createNamedParameter($retention)),
3533
-			);
3534
-		return $query->executeStatement();
3535
-	}
3536
-
3537
-	/**
3538
-	 * return legacy endpoint principal name to new principal name
3539
-	 *
3540
-	 * @param $principalUri
3541
-	 * @param $toV2
3542
-	 * @return string
3543
-	 */
3544
-	private function convertPrincipal($principalUri, $toV2) {
3545
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
3546
-			[, $name] = Uri\split($principalUri);
3547
-			if ($toV2 === true) {
3548
-				return "principals/users/$name";
3549
-			}
3550
-			return "principals/$name";
3551
-		}
3552
-		return $principalUri;
3553
-	}
3554
-
3555
-	/**
3556
-	 * adds information about an owner to the calendar data
3557
-	 *
3558
-	 */
3559
-	private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
3560
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
3561
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
3562
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
3563
-			$uri = $calendarInfo[$ownerPrincipalKey];
3564
-		} else {
3565
-			$uri = $calendarInfo['principaluri'];
3566
-		}
3567
-
3568
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
3569
-		if (isset($principalInformation['{DAV:}displayname'])) {
3570
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
3571
-		}
3572
-		return $calendarInfo;
3573
-	}
3574
-
3575
-	private function addResourceTypeToCalendar(array $row, array $calendar): array {
3576
-		if (isset($row['deleted_at'])) {
3577
-			// Columns is set and not null -> this is a deleted calendar
3578
-			// we send a custom resourcetype to hide the deleted calendar
3579
-			// from ordinary DAV clients, but the Calendar app will know
3580
-			// how to handle this special resource.
3581
-			$calendar['{DAV:}resourcetype'] = new DAV\Xml\Property\ResourceType([
3582
-				'{DAV:}collection',
3583
-				sprintf('{%s}deleted-calendar', \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD),
3584
-			]);
3585
-		}
3586
-		return $calendar;
3587
-	}
3588
-
3589
-	/**
3590
-	 * Amend the calendar info with database row data
3591
-	 *
3592
-	 * @param array $row
3593
-	 * @param array $calendar
3594
-	 *
3595
-	 * @return array
3596
-	 */
3597
-	private function rowToCalendar($row, array $calendar): array {
3598
-		foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
3599
-			$value = $row[$dbName];
3600
-			if ($value !== null) {
3601
-				settype($value, $type);
3602
-			}
3603
-			$calendar[$xmlName] = $value;
3604
-		}
3605
-		return $calendar;
3606
-	}
3607
-
3608
-	/**
3609
-	 * Amend the subscription info with database row data
3610
-	 *
3611
-	 * @param array $row
3612
-	 * @param array $subscription
3613
-	 *
3614
-	 * @return array
3615
-	 */
3616
-	private function rowToSubscription($row, array $subscription): array {
3617
-		foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
3618
-			$value = $row[$dbName];
3619
-			if ($value !== null) {
3620
-				settype($value, $type);
3621
-			}
3622
-			$subscription[$xmlName] = $value;
3623
-		}
3624
-		return $subscription;
3625
-	}
3626
-
3627
-	/**
3628
-	 * delete all invitations from a given calendar
3629
-	 *
3630
-	 * @since 31.0.0
3631
-	 *
3632
-	 * @param int $calendarId
3633
-	 *
3634
-	 * @return void
3635
-	 */
3636
-	protected function purgeCalendarInvitations(int $calendarId): void {
3637
-		// select all calendar object uid's
3638
-		$cmd = $this->db->getQueryBuilder();
3639
-		$cmd->select('uid')
3640
-			->from($this->dbObjectsTable)
3641
-			->where($cmd->expr()->eq('calendarid', $cmd->createNamedParameter($calendarId)));
3642
-		$allIds = $cmd->executeQuery()->fetchAll(\PDO::FETCH_COLUMN);
3643
-		// delete all links that match object uid's
3644
-		$cmd = $this->db->getQueryBuilder();
3645
-		$cmd->delete($this->dbObjectInvitationsTable)
3646
-			->where($cmd->expr()->in('uid', $cmd->createParameter('uids'), IQueryBuilder::PARAM_STR_ARRAY));
3647
-		foreach (array_chunk($allIds, 1000) as $chunkIds) {
3648
-			$cmd->setParameter('uids', $chunkIds, IQueryBuilder::PARAM_STR_ARRAY);
3649
-			$cmd->executeStatement();
3650
-		}
3651
-	}
3652
-
3653
-	/**
3654
-	 * Delete all invitations from a given calendar event
3655
-	 *
3656
-	 * @since 31.0.0
3657
-	 *
3658
-	 * @param string $eventId UID of the event
3659
-	 *
3660
-	 * @return void
3661
-	 */
3662
-	protected function purgeObjectInvitations(string $eventId): void {
3663
-		$cmd = $this->db->getQueryBuilder();
3664
-		$cmd->delete($this->dbObjectInvitationsTable)
3665
-			->where($cmd->expr()->eq('uid', $cmd->createNamedParameter($eventId, IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR));
3666
-		$cmd->executeStatement();
3667
-	}
3668
-
3669
-	public function unshare(IShareable $shareable, string $principal): void {
3670
-		$this->atomic(function () use ($shareable, $principal): void {
3671
-			$calendarData = $this->getCalendarById($shareable->getResourceId());
3672
-			if ($calendarData === null) {
3673
-				throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $shareable->getResourceId());
3674
-			}
3675
-
3676
-			$oldShares = $this->getShares($shareable->getResourceId());
3677
-			$unshare = $this->calendarSharingBackend->unshare($shareable, $principal);
3678
-
3679
-			if ($unshare) {
3680
-				$this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent(
3681
-					$shareable->getResourceId(),
3682
-					$calendarData,
3683
-					$oldShares,
3684
-					[],
3685
-					[$principal]
3686
-				));
3687
-			}
3688
-		}, $this->db);
3689
-	}
109
+    use TTransactional;
110
+
111
+    public const CALENDAR_TYPE_CALENDAR = 0;
112
+    public const CALENDAR_TYPE_SUBSCRIPTION = 1;
113
+
114
+    public const PERSONAL_CALENDAR_URI = 'personal';
115
+    public const PERSONAL_CALENDAR_NAME = 'Personal';
116
+
117
+    public const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
118
+    public const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
119
+
120
+    /**
121
+     * We need to specify a max date, because we need to stop *somewhere*
122
+     *
123
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
124
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
125
+     * in 2038-01-19 to avoid problems when the date is converted
126
+     * to a unix timestamp.
127
+     */
128
+    public const MAX_DATE = '2038-01-01';
129
+
130
+    public const ACCESS_PUBLIC = 4;
131
+    public const CLASSIFICATION_PUBLIC = 0;
132
+    public const CLASSIFICATION_PRIVATE = 1;
133
+    public const CLASSIFICATION_CONFIDENTIAL = 2;
134
+
135
+    /**
136
+     * List of CalDAV properties, and how they map to database field names and their type
137
+     * Add your own properties by simply adding on to this array.
138
+     *
139
+     * @var array
140
+     * @psalm-var array<string, string[]>
141
+     */
142
+    public array $propertyMap = [
143
+        '{DAV:}displayname' => ['displayname', 'string'],
144
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => ['description', 'string'],
145
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => ['timezone', 'string'],
146
+        '{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
147
+        '{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
148
+        '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => ['deleted_at', 'int'],
149
+    ];
150
+
151
+    /**
152
+     * List of subscription properties, and how they map to database field names.
153
+     *
154
+     * @var array
155
+     */
156
+    public array $subscriptionPropertyMap = [
157
+        '{DAV:}displayname' => ['displayname', 'string'],
158
+        '{http://apple.com/ns/ical/}refreshrate' => ['refreshrate', 'string'],
159
+        '{http://apple.com/ns/ical/}calendar-order' => ['calendarorder', 'int'],
160
+        '{http://apple.com/ns/ical/}calendar-color' => ['calendarcolor', 'string'],
161
+        '{http://calendarserver.org/ns/}subscribed-strip-todos' => ['striptodos', 'bool'],
162
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms' => ['stripalarms', 'string'],
163
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => ['stripattachments', 'string'],
164
+    ];
165
+
166
+    /**
167
+     * properties to index
168
+     *
169
+     * This list has to be kept in sync with ICalendarQuery::SEARCH_PROPERTY_*
170
+     *
171
+     * @see \OCP\Calendar\ICalendarQuery
172
+     */
173
+    private const INDEXED_PROPERTIES = [
174
+        'CATEGORIES',
175
+        'COMMENT',
176
+        'DESCRIPTION',
177
+        'LOCATION',
178
+        'RESOURCES',
179
+        'STATUS',
180
+        'SUMMARY',
181
+        'ATTENDEE',
182
+        'CONTACT',
183
+        'ORGANIZER'
184
+    ];
185
+
186
+    /** @var array parameters to index */
187
+    public static array $indexParameters = [
188
+        'ATTENDEE' => ['CN'],
189
+        'ORGANIZER' => ['CN'],
190
+    ];
191
+
192
+    /**
193
+     * @var string[] Map of uid => display name
194
+     */
195
+    protected array $userDisplayNames;
196
+
197
+    private string $dbObjectsTable = 'calendarobjects';
198
+    private string $dbObjectPropertiesTable = 'calendarobjects_props';
199
+    private string $dbObjectInvitationsTable = 'calendar_invitations';
200
+    private array $cachedObjects = [];
201
+
202
+    public function __construct(
203
+        private IDBConnection $db,
204
+        private Principal $principalBackend,
205
+        private IUserManager $userManager,
206
+        private ISecureRandom $random,
207
+        private LoggerInterface $logger,
208
+        private IEventDispatcher $dispatcher,
209
+        private IConfig $config,
210
+        private Sharing\Backend $calendarSharingBackend,
211
+        private bool $legacyEndpoint = false,
212
+    ) {
213
+    }
214
+
215
+    /**
216
+     * Return the number of calendars owned by the given principal.
217
+     *
218
+     * Calendars shared with the given principal are not counted!
219
+     *
220
+     * By default, this excludes the automatically generated birthday calendar.
221
+     */
222
+    public function getCalendarsForUserCount(string $principalUri, bool $excludeBirthday = true): int {
223
+        $principalUri = $this->convertPrincipal($principalUri, true);
224
+        $query = $this->db->getQueryBuilder();
225
+        $query->select($query->func()->count('*'))
226
+            ->from('calendars');
227
+
228
+        if ($principalUri === '') {
229
+            $query->where($query->expr()->emptyString('principaluri'));
230
+        } else {
231
+            $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
232
+        }
233
+
234
+        if ($excludeBirthday) {
235
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
236
+        }
237
+
238
+        $result = $query->executeQuery();
239
+        $column = (int)$result->fetchOne();
240
+        $result->closeCursor();
241
+        return $column;
242
+    }
243
+
244
+    /**
245
+     * Return the number of subscriptions for a principal
246
+     */
247
+    public function getSubscriptionsForUserCount(string $principalUri): int {
248
+        $principalUri = $this->convertPrincipal($principalUri, true);
249
+        $query = $this->db->getQueryBuilder();
250
+        $query->select($query->func()->count('*'))
251
+            ->from('calendarsubscriptions');
252
+
253
+        if ($principalUri === '') {
254
+            $query->where($query->expr()->emptyString('principaluri'));
255
+        } else {
256
+            $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
257
+        }
258
+
259
+        $result = $query->executeQuery();
260
+        $column = (int)$result->fetchOne();
261
+        $result->closeCursor();
262
+        return $column;
263
+    }
264
+
265
+    /**
266
+     * @return array{id: int, deleted_at: int}[]
267
+     */
268
+    public function getDeletedCalendars(int $deletedBefore): array {
269
+        $qb = $this->db->getQueryBuilder();
270
+        $qb->select(['id', 'deleted_at'])
271
+            ->from('calendars')
272
+            ->where($qb->expr()->isNotNull('deleted_at'))
273
+            ->andWhere($qb->expr()->lt('deleted_at', $qb->createNamedParameter($deletedBefore)));
274
+        $result = $qb->executeQuery();
275
+        $calendars = [];
276
+        while (($row = $result->fetch()) !== false) {
277
+            $calendars[] = [
278
+                'id' => (int)$row['id'],
279
+                'deleted_at' => (int)$row['deleted_at'],
280
+            ];
281
+        }
282
+        $result->closeCursor();
283
+        return $calendars;
284
+    }
285
+
286
+    /**
287
+     * Returns a list of calendars for a principal.
288
+     *
289
+     * Every project is an array with the following keys:
290
+     *  * id, a unique id that will be used by other functions to modify the
291
+     *    calendar. This can be the same as the uri or a database key.
292
+     *  * uri, which the basename of the uri with which the calendar is
293
+     *    accessed.
294
+     *  * principaluri. The owner of the calendar. Almost always the same as
295
+     *    principalUri passed to this method.
296
+     *
297
+     * Furthermore it can contain webdav properties in clark notation. A very
298
+     * common one is '{DAV:}displayname'.
299
+     *
300
+     * Many clients also require:
301
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
302
+     * For this property, you can just return an instance of
303
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
304
+     *
305
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
306
+     * ACL will automatically be put in read-only mode.
307
+     *
308
+     * @param string $principalUri
309
+     * @return array
310
+     */
311
+    public function getCalendarsForUser($principalUri) {
312
+        return $this->atomic(function () use ($principalUri) {
313
+            $principalUriOriginal = $principalUri;
314
+            $principalUri = $this->convertPrincipal($principalUri, true);
315
+            $fields = array_column($this->propertyMap, 0);
316
+            $fields[] = 'id';
317
+            $fields[] = 'uri';
318
+            $fields[] = 'synctoken';
319
+            $fields[] = 'components';
320
+            $fields[] = 'principaluri';
321
+            $fields[] = 'transparent';
322
+
323
+            // Making fields a comma-delimited list
324
+            $query = $this->db->getQueryBuilder();
325
+            $query->select($fields)
326
+                ->from('calendars')
327
+                ->orderBy('calendarorder', 'ASC');
328
+
329
+            if ($principalUri === '') {
330
+                $query->where($query->expr()->emptyString('principaluri'));
331
+            } else {
332
+                $query->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
333
+            }
334
+
335
+            $result = $query->executeQuery();
336
+
337
+            $calendars = [];
338
+            while ($row = $result->fetch()) {
339
+                $row['principaluri'] = (string)$row['principaluri'];
340
+                $components = [];
341
+                if ($row['components']) {
342
+                    $components = explode(',', $row['components']);
343
+                }
344
+
345
+                $calendar = [
346
+                    'id' => $row['id'],
347
+                    'uri' => $row['uri'],
348
+                    'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
349
+                    '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
350
+                    '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
351
+                    '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
352
+                    '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
353
+                    '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
354
+                ];
355
+
356
+                $calendar = $this->rowToCalendar($row, $calendar);
357
+                $calendar = $this->addOwnerPrincipalToCalendar($calendar);
358
+                $calendar = $this->addResourceTypeToCalendar($row, $calendar);
359
+
360
+                if (!isset($calendars[$calendar['id']])) {
361
+                    $calendars[$calendar['id']] = $calendar;
362
+                }
363
+            }
364
+            $result->closeCursor();
365
+
366
+            // query for shared calendars
367
+            $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
368
+            $principals = array_merge($principals, $this->principalBackend->getCircleMembership($principalUriOriginal));
369
+            $principals[] = $principalUri;
370
+
371
+            $fields = array_column($this->propertyMap, 0);
372
+            $fields = array_map(function (string $field) {
373
+                return 'a.' . $field;
374
+            }, $fields);
375
+            $fields[] = 'a.id';
376
+            $fields[] = 'a.uri';
377
+            $fields[] = 'a.synctoken';
378
+            $fields[] = 'a.components';
379
+            $fields[] = 'a.principaluri';
380
+            $fields[] = 'a.transparent';
381
+            $fields[] = 's.access';
382
+
383
+            $select = $this->db->getQueryBuilder();
384
+            $subSelect = $this->db->getQueryBuilder();
385
+
386
+            $subSelect->select('resourceid')
387
+                ->from('dav_shares', 'd')
388
+                ->where($subSelect->expr()->eq('d.access', $select->createNamedParameter(Backend::ACCESS_UNSHARED, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
389
+                ->andWhere($subSelect->expr()->in('d.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY));
390
+
391
+            $select->select($fields)
392
+                ->from('dav_shares', 's')
393
+                ->join('s', 'calendars', 'a', $select->expr()->eq('s.resourceid', 'a.id', IQueryBuilder::PARAM_INT))
394
+                ->where($select->expr()->in('s.principaluri', $select->createNamedParameter($principals, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
395
+                ->andWhere($select->expr()->eq('s.type', $select->createNamedParameter('calendar', IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR))
396
+                ->andWhere($select->expr()->notIn('a.id', $select->createFunction($subSelect->getSQL()), IQueryBuilder::PARAM_INT_ARRAY));
397
+
398
+            $results = $select->executeQuery();
399
+
400
+            $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
401
+            while ($row = $results->fetch()) {
402
+                $row['principaluri'] = (string)$row['principaluri'];
403
+                if ($row['principaluri'] === $principalUri) {
404
+                    continue;
405
+                }
406
+
407
+                $readOnly = (int)$row['access'] === Backend::ACCESS_READ;
408
+                if (isset($calendars[$row['id']])) {
409
+                    if ($readOnly) {
410
+                        // New share can not have more permissions than the old one.
411
+                        continue;
412
+                    }
413
+                    if (isset($calendars[$row['id']][$readOnlyPropertyName])
414
+                        && $calendars[$row['id']][$readOnlyPropertyName] === 0) {
415
+                        // Old share is already read-write, no more permissions can be gained
416
+                        continue;
417
+                    }
418
+                }
419
+
420
+                [, $name] = Uri\split($row['principaluri']);
421
+                $uri = $row['uri'] . '_shared_by_' . $name;
422
+                $row['displayname'] = $row['displayname'] . ' (' . ($this->userManager->getDisplayName($name) ?? ($name ?? '')) . ')';
423
+                $components = [];
424
+                if ($row['components']) {
425
+                    $components = explode(',', $row['components']);
426
+                }
427
+                $calendar = [
428
+                    'id' => $row['id'],
429
+                    'uri' => $uri,
430
+                    'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
431
+                    '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
432
+                    '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
433
+                    '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
434
+                    '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
435
+                    '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
436
+                    $readOnlyPropertyName => $readOnly,
437
+                ];
438
+
439
+                $calendar = $this->rowToCalendar($row, $calendar);
440
+                $calendar = $this->addOwnerPrincipalToCalendar($calendar);
441
+                $calendar = $this->addResourceTypeToCalendar($row, $calendar);
442
+
443
+                $calendars[$calendar['id']] = $calendar;
444
+            }
445
+            $result->closeCursor();
446
+
447
+            return array_values($calendars);
448
+        }, $this->db);
449
+    }
450
+
451
+    /**
452
+     * @param $principalUri
453
+     * @return array
454
+     */
455
+    public function getUsersOwnCalendars($principalUri) {
456
+        $principalUri = $this->convertPrincipal($principalUri, true);
457
+        $fields = array_column($this->propertyMap, 0);
458
+        $fields[] = 'id';
459
+        $fields[] = 'uri';
460
+        $fields[] = 'synctoken';
461
+        $fields[] = 'components';
462
+        $fields[] = 'principaluri';
463
+        $fields[] = 'transparent';
464
+        // Making fields a comma-delimited list
465
+        $query = $this->db->getQueryBuilder();
466
+        $query->select($fields)->from('calendars')
467
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
468
+            ->orderBy('calendarorder', 'ASC');
469
+        $stmt = $query->executeQuery();
470
+        $calendars = [];
471
+        while ($row = $stmt->fetch()) {
472
+            $row['principaluri'] = (string)$row['principaluri'];
473
+            $components = [];
474
+            if ($row['components']) {
475
+                $components = explode(',', $row['components']);
476
+            }
477
+            $calendar = [
478
+                'id' => $row['id'],
479
+                'uri' => $row['uri'],
480
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
481
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
482
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
483
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
484
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
485
+            ];
486
+
487
+            $calendar = $this->rowToCalendar($row, $calendar);
488
+            $calendar = $this->addOwnerPrincipalToCalendar($calendar);
489
+            $calendar = $this->addResourceTypeToCalendar($row, $calendar);
490
+
491
+            if (!isset($calendars[$calendar['id']])) {
492
+                $calendars[$calendar['id']] = $calendar;
493
+            }
494
+        }
495
+        $stmt->closeCursor();
496
+        return array_values($calendars);
497
+    }
498
+
499
+    /**
500
+     * @return array
501
+     */
502
+    public function getPublicCalendars() {
503
+        $fields = array_column($this->propertyMap, 0);
504
+        $fields[] = 'a.id';
505
+        $fields[] = 'a.uri';
506
+        $fields[] = 'a.synctoken';
507
+        $fields[] = 'a.components';
508
+        $fields[] = 'a.principaluri';
509
+        $fields[] = 'a.transparent';
510
+        $fields[] = 's.access';
511
+        $fields[] = 's.publicuri';
512
+        $calendars = [];
513
+        $query = $this->db->getQueryBuilder();
514
+        $result = $query->select($fields)
515
+            ->from('dav_shares', 's')
516
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
517
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
518
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
519
+            ->executeQuery();
520
+
521
+        while ($row = $result->fetch()) {
522
+            $row['principaluri'] = (string)$row['principaluri'];
523
+            [, $name] = Uri\split($row['principaluri']);
524
+            $row['displayname'] = $row['displayname'] . "($name)";
525
+            $components = [];
526
+            if ($row['components']) {
527
+                $components = explode(',', $row['components']);
528
+            }
529
+            $calendar = [
530
+                'id' => $row['id'],
531
+                'uri' => $row['publicuri'],
532
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
533
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
534
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
535
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
536
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
537
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
538
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
539
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
540
+            ];
541
+
542
+            $calendar = $this->rowToCalendar($row, $calendar);
543
+            $calendar = $this->addOwnerPrincipalToCalendar($calendar);
544
+            $calendar = $this->addResourceTypeToCalendar($row, $calendar);
545
+
546
+            if (!isset($calendars[$calendar['id']])) {
547
+                $calendars[$calendar['id']] = $calendar;
548
+            }
549
+        }
550
+        $result->closeCursor();
551
+
552
+        return array_values($calendars);
553
+    }
554
+
555
+    /**
556
+     * @param string $uri
557
+     * @return array
558
+     * @throws NotFound
559
+     */
560
+    public function getPublicCalendar($uri) {
561
+        $fields = array_column($this->propertyMap, 0);
562
+        $fields[] = 'a.id';
563
+        $fields[] = 'a.uri';
564
+        $fields[] = 'a.synctoken';
565
+        $fields[] = 'a.components';
566
+        $fields[] = 'a.principaluri';
567
+        $fields[] = 'a.transparent';
568
+        $fields[] = 's.access';
569
+        $fields[] = 's.publicuri';
570
+        $query = $this->db->getQueryBuilder();
571
+        $result = $query->select($fields)
572
+            ->from('dav_shares', 's')
573
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
574
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
575
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
576
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
577
+            ->executeQuery();
578
+
579
+        $row = $result->fetch();
580
+
581
+        $result->closeCursor();
582
+
583
+        if ($row === false) {
584
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
585
+        }
586
+
587
+        $row['principaluri'] = (string)$row['principaluri'];
588
+        [, $name] = Uri\split($row['principaluri']);
589
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
590
+        $components = [];
591
+        if ($row['components']) {
592
+            $components = explode(',', $row['components']);
593
+        }
594
+        $calendar = [
595
+            'id' => $row['id'],
596
+            'uri' => $row['publicuri'],
597
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
598
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
599
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
600
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
601
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
602
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
603
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
604
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
605
+        ];
606
+
607
+        $calendar = $this->rowToCalendar($row, $calendar);
608
+        $calendar = $this->addOwnerPrincipalToCalendar($calendar);
609
+        $calendar = $this->addResourceTypeToCalendar($row, $calendar);
610
+
611
+        return $calendar;
612
+    }
613
+
614
+    /**
615
+     * @param string $principal
616
+     * @param string $uri
617
+     * @return array|null
618
+     */
619
+    public function getCalendarByUri($principal, $uri) {
620
+        $fields = array_column($this->propertyMap, 0);
621
+        $fields[] = 'id';
622
+        $fields[] = 'uri';
623
+        $fields[] = 'synctoken';
624
+        $fields[] = 'components';
625
+        $fields[] = 'principaluri';
626
+        $fields[] = 'transparent';
627
+
628
+        // Making fields a comma-delimited list
629
+        $query = $this->db->getQueryBuilder();
630
+        $query->select($fields)->from('calendars')
631
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
632
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
633
+            ->setMaxResults(1);
634
+        $stmt = $query->executeQuery();
635
+
636
+        $row = $stmt->fetch();
637
+        $stmt->closeCursor();
638
+        if ($row === false) {
639
+            return null;
640
+        }
641
+
642
+        $row['principaluri'] = (string)$row['principaluri'];
643
+        $components = [];
644
+        if ($row['components']) {
645
+            $components = explode(',', $row['components']);
646
+        }
647
+
648
+        $calendar = [
649
+            'id' => $row['id'],
650
+            'uri' => $row['uri'],
651
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
652
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
653
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
654
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
655
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
656
+        ];
657
+
658
+        $calendar = $this->rowToCalendar($row, $calendar);
659
+        $calendar = $this->addOwnerPrincipalToCalendar($calendar);
660
+        $calendar = $this->addResourceTypeToCalendar($row, $calendar);
661
+
662
+        return $calendar;
663
+    }
664
+
665
+    /**
666
+     * @psalm-return CalendarInfo|null
667
+     * @return array|null
668
+     */
669
+    public function getCalendarById(int $calendarId): ?array {
670
+        $fields = array_column($this->propertyMap, 0);
671
+        $fields[] = 'id';
672
+        $fields[] = 'uri';
673
+        $fields[] = 'synctoken';
674
+        $fields[] = 'components';
675
+        $fields[] = 'principaluri';
676
+        $fields[] = 'transparent';
677
+
678
+        // Making fields a comma-delimited list
679
+        $query = $this->db->getQueryBuilder();
680
+        $query->select($fields)->from('calendars')
681
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
682
+            ->setMaxResults(1);
683
+        $stmt = $query->executeQuery();
684
+
685
+        $row = $stmt->fetch();
686
+        $stmt->closeCursor();
687
+        if ($row === false) {
688
+            return null;
689
+        }
690
+
691
+        $row['principaluri'] = (string)$row['principaluri'];
692
+        $components = [];
693
+        if ($row['components']) {
694
+            $components = explode(',', $row['components']);
695
+        }
696
+
697
+        $calendar = [
698
+            'id' => $row['id'],
699
+            'uri' => $row['uri'],
700
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
701
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken'] ?: '0'),
702
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?? 0,
703
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
704
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
705
+        ];
706
+
707
+        $calendar = $this->rowToCalendar($row, $calendar);
708
+        $calendar = $this->addOwnerPrincipalToCalendar($calendar);
709
+        $calendar = $this->addResourceTypeToCalendar($row, $calendar);
710
+
711
+        return $calendar;
712
+    }
713
+
714
+    /**
715
+     * @param $subscriptionId
716
+     */
717
+    public function getSubscriptionById($subscriptionId) {
718
+        $fields = array_column($this->subscriptionPropertyMap, 0);
719
+        $fields[] = 'id';
720
+        $fields[] = 'uri';
721
+        $fields[] = 'source';
722
+        $fields[] = 'synctoken';
723
+        $fields[] = 'principaluri';
724
+        $fields[] = 'lastmodified';
725
+
726
+        $query = $this->db->getQueryBuilder();
727
+        $query->select($fields)
728
+            ->from('calendarsubscriptions')
729
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
730
+            ->orderBy('calendarorder', 'asc');
731
+        $stmt = $query->executeQuery();
732
+
733
+        $row = $stmt->fetch();
734
+        $stmt->closeCursor();
735
+        if ($row === false) {
736
+            return null;
737
+        }
738
+
739
+        $row['principaluri'] = (string)$row['principaluri'];
740
+        $subscription = [
741
+            'id' => $row['id'],
742
+            'uri' => $row['uri'],
743
+            'principaluri' => $row['principaluri'],
744
+            'source' => $row['source'],
745
+            'lastmodified' => $row['lastmodified'],
746
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
747
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
748
+        ];
749
+
750
+        return $this->rowToSubscription($row, $subscription);
751
+    }
752
+
753
+    public function getSubscriptionByUri(string $principal, string $uri): ?array {
754
+        $fields = array_column($this->subscriptionPropertyMap, 0);
755
+        $fields[] = 'id';
756
+        $fields[] = 'uri';
757
+        $fields[] = 'source';
758
+        $fields[] = 'synctoken';
759
+        $fields[] = 'principaluri';
760
+        $fields[] = 'lastmodified';
761
+
762
+        $query = $this->db->getQueryBuilder();
763
+        $query->select($fields)
764
+            ->from('calendarsubscriptions')
765
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
766
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
767
+            ->setMaxResults(1);
768
+        $stmt = $query->executeQuery();
769
+
770
+        $row = $stmt->fetch();
771
+        $stmt->closeCursor();
772
+        if ($row === false) {
773
+            return null;
774
+        }
775
+
776
+        $row['principaluri'] = (string)$row['principaluri'];
777
+        $subscription = [
778
+            'id' => $row['id'],
779
+            'uri' => $row['uri'],
780
+            'principaluri' => $row['principaluri'],
781
+            'source' => $row['source'],
782
+            'lastmodified' => $row['lastmodified'],
783
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
784
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
785
+        ];
786
+
787
+        return $this->rowToSubscription($row, $subscription);
788
+    }
789
+
790
+    /**
791
+     * Creates a new calendar for a principal.
792
+     *
793
+     * If the creation was a success, an id must be returned that can be used to reference
794
+     * this calendar in other methods, such as updateCalendar.
795
+     *
796
+     * @param string $principalUri
797
+     * @param string $calendarUri
798
+     * @param array $properties
799
+     * @return int
800
+     *
801
+     * @throws CalendarException
802
+     */
803
+    public function createCalendar($principalUri, $calendarUri, array $properties) {
804
+        if (strlen($calendarUri) > 255) {
805
+            throw new CalendarException('URI too long. Calendar not created');
806
+        }
807
+
808
+        $values = [
809
+            'principaluri' => $this->convertPrincipal($principalUri, true),
810
+            'uri' => $calendarUri,
811
+            'synctoken' => 1,
812
+            'transparent' => 0,
813
+            'components' => 'VEVENT,VTODO,VJOURNAL',
814
+            'displayname' => $calendarUri
815
+        ];
816
+
817
+        // Default value
818
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
819
+        if (isset($properties[$sccs])) {
820
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
821
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
822
+            }
823
+            $values['components'] = implode(',', $properties[$sccs]->getValue());
824
+        } elseif (isset($properties['components'])) {
825
+            // Allow to provide components internally without having
826
+            // to create a SupportedCalendarComponentSet object
827
+            $values['components'] = $properties['components'];
828
+        }
829
+
830
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
831
+        if (isset($properties[$transp])) {
832
+            $values['transparent'] = (int)($properties[$transp]->getValue() === 'transparent');
833
+        }
834
+
835
+        foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
836
+            if (isset($properties[$xmlName])) {
837
+                $values[$dbName] = $properties[$xmlName];
838
+            }
839
+        }
840
+
841
+        [$calendarId, $calendarData] = $this->atomic(function () use ($values) {
842
+            $query = $this->db->getQueryBuilder();
843
+            $query->insert('calendars');
844
+            foreach ($values as $column => $value) {
845
+                $query->setValue($column, $query->createNamedParameter($value));
846
+            }
847
+            $query->executeStatement();
848
+            $calendarId = $query->getLastInsertId();
849
+
850
+            $calendarData = $this->getCalendarById($calendarId);
851
+            return [$calendarId, $calendarData];
852
+        }, $this->db);
853
+
854
+        $this->dispatcher->dispatchTyped(new CalendarCreatedEvent((int)$calendarId, $calendarData));
855
+
856
+        return $calendarId;
857
+    }
858
+
859
+    /**
860
+     * Updates properties for a calendar.
861
+     *
862
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
863
+     * To do the actual updates, you must tell this object which properties
864
+     * you're going to process with the handle() method.
865
+     *
866
+     * Calling the handle method is like telling the PropPatch object "I
867
+     * promise I can handle updating this property".
868
+     *
869
+     * Read the PropPatch documentation for more info and examples.
870
+     *
871
+     * @param mixed $calendarId
872
+     * @param PropPatch $propPatch
873
+     * @return void
874
+     */
875
+    public function updateCalendar($calendarId, PropPatch $propPatch) {
876
+        $supportedProperties = array_keys($this->propertyMap);
877
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
878
+
879
+        $propPatch->handle($supportedProperties, function ($mutations) use ($calendarId) {
880
+            $newValues = [];
881
+            foreach ($mutations as $propertyName => $propertyValue) {
882
+                switch ($propertyName) {
883
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp':
884
+                        $fieldName = 'transparent';
885
+                        $newValues[$fieldName] = (int)($propertyValue->getValue() === 'transparent');
886
+                        break;
887
+                    default:
888
+                        $fieldName = $this->propertyMap[$propertyName][0];
889
+                        $newValues[$fieldName] = $propertyValue;
890
+                        break;
891
+                }
892
+            }
893
+            [$calendarData, $shares] = $this->atomic(function () use ($calendarId, $newValues) {
894
+                $query = $this->db->getQueryBuilder();
895
+                $query->update('calendars');
896
+                foreach ($newValues as $fieldName => $value) {
897
+                    $query->set($fieldName, $query->createNamedParameter($value));
898
+                }
899
+                $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
900
+                $query->executeStatement();
901
+
902
+                $this->addChanges($calendarId, [''], 2);
903
+
904
+                $calendarData = $this->getCalendarById($calendarId);
905
+                $shares = $this->getShares($calendarId);
906
+                return [$calendarData, $shares];
907
+            }, $this->db);
908
+
909
+            $this->dispatcher->dispatchTyped(new CalendarUpdatedEvent($calendarId, $calendarData, $shares, $mutations));
910
+
911
+            return true;
912
+        });
913
+    }
914
+
915
+    /**
916
+     * Delete a calendar and all it's objects
917
+     *
918
+     * @param mixed $calendarId
919
+     * @return void
920
+     */
921
+    public function deleteCalendar($calendarId, bool $forceDeletePermanently = false) {
922
+        $this->atomic(function () use ($calendarId, $forceDeletePermanently): void {
923
+            // The calendar is deleted right away if this is either enforced by the caller
924
+            // or the special contacts birthday calendar or when the preference of an empty
925
+            // retention (0 seconds) is set, which signals a disabled trashbin.
926
+            $calendarData = $this->getCalendarById($calendarId);
927
+            $isBirthdayCalendar = isset($calendarData['uri']) && $calendarData['uri'] === BirthdayService::BIRTHDAY_CALENDAR_URI;
928
+            $trashbinDisabled = $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0';
929
+            if ($forceDeletePermanently || $isBirthdayCalendar || $trashbinDisabled) {
930
+                $calendarData = $this->getCalendarById($calendarId);
931
+                $shares = $this->getShares($calendarId);
932
+
933
+                $this->purgeCalendarInvitations($calendarId);
934
+
935
+                $qbDeleteCalendarObjectProps = $this->db->getQueryBuilder();
936
+                $qbDeleteCalendarObjectProps->delete($this->dbObjectPropertiesTable)
937
+                    ->where($qbDeleteCalendarObjectProps->expr()->eq('calendarid', $qbDeleteCalendarObjectProps->createNamedParameter($calendarId)))
938
+                    ->andWhere($qbDeleteCalendarObjectProps->expr()->eq('calendartype', $qbDeleteCalendarObjectProps->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
939
+                    ->executeStatement();
940
+
941
+                $qbDeleteCalendarObjects = $this->db->getQueryBuilder();
942
+                $qbDeleteCalendarObjects->delete('calendarobjects')
943
+                    ->where($qbDeleteCalendarObjects->expr()->eq('calendarid', $qbDeleteCalendarObjects->createNamedParameter($calendarId)))
944
+                    ->andWhere($qbDeleteCalendarObjects->expr()->eq('calendartype', $qbDeleteCalendarObjects->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
945
+                    ->executeStatement();
946
+
947
+                $qbDeleteCalendarChanges = $this->db->getQueryBuilder();
948
+                $qbDeleteCalendarChanges->delete('calendarchanges')
949
+                    ->where($qbDeleteCalendarChanges->expr()->eq('calendarid', $qbDeleteCalendarChanges->createNamedParameter($calendarId)))
950
+                    ->andWhere($qbDeleteCalendarChanges->expr()->eq('calendartype', $qbDeleteCalendarChanges->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
951
+                    ->executeStatement();
952
+
953
+                $this->calendarSharingBackend->deleteAllShares($calendarId);
954
+
955
+                $qbDeleteCalendar = $this->db->getQueryBuilder();
956
+                $qbDeleteCalendar->delete('calendars')
957
+                    ->where($qbDeleteCalendar->expr()->eq('id', $qbDeleteCalendar->createNamedParameter($calendarId)))
958
+                    ->executeStatement();
959
+
960
+                // Only dispatch if we actually deleted anything
961
+                if ($calendarData) {
962
+                    $this->dispatcher->dispatchTyped(new CalendarDeletedEvent($calendarId, $calendarData, $shares));
963
+                }
964
+            } else {
965
+                $qbMarkCalendarDeleted = $this->db->getQueryBuilder();
966
+                $qbMarkCalendarDeleted->update('calendars')
967
+                    ->set('deleted_at', $qbMarkCalendarDeleted->createNamedParameter(time()))
968
+                    ->where($qbMarkCalendarDeleted->expr()->eq('id', $qbMarkCalendarDeleted->createNamedParameter($calendarId)))
969
+                    ->executeStatement();
970
+
971
+                $calendarData = $this->getCalendarById($calendarId);
972
+                $shares = $this->getShares($calendarId);
973
+                if ($calendarData) {
974
+                    $this->dispatcher->dispatchTyped(new CalendarMovedToTrashEvent(
975
+                        $calendarId,
976
+                        $calendarData,
977
+                        $shares
978
+                    ));
979
+                }
980
+            }
981
+        }, $this->db);
982
+    }
983
+
984
+    public function restoreCalendar(int $id): void {
985
+        $this->atomic(function () use ($id): void {
986
+            $qb = $this->db->getQueryBuilder();
987
+            $update = $qb->update('calendars')
988
+                ->set('deleted_at', $qb->createNamedParameter(null))
989
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
990
+            $update->executeStatement();
991
+
992
+            $calendarData = $this->getCalendarById($id);
993
+            $shares = $this->getShares($id);
994
+            if ($calendarData === null) {
995
+                throw new RuntimeException('Calendar data that was just written can\'t be read back. Check your database configuration.');
996
+            }
997
+            $this->dispatcher->dispatchTyped(new CalendarRestoredEvent(
998
+                $id,
999
+                $calendarData,
1000
+                $shares
1001
+            ));
1002
+        }, $this->db);
1003
+    }
1004
+
1005
+    /**
1006
+     * Returns all calendar entries as a stream of data
1007
+     *
1008
+     * @since 32.0.0
1009
+     *
1010
+     * @return Generator<array>
1011
+     */
1012
+    public function exportCalendar(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR, ?CalendarExportOptions $options = null): Generator {
1013
+        // extract options
1014
+        $rangeStart = $options?->getRangeStart();
1015
+        $rangeCount = $options?->getRangeCount();
1016
+        // construct query
1017
+        $qb = $this->db->getQueryBuilder();
1018
+        $qb->select('*')
1019
+            ->from('calendarobjects')
1020
+            ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1021
+            ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1022
+            ->andWhere($qb->expr()->isNull('deleted_at'));
1023
+        if ($rangeStart !== null) {
1024
+            $qb->andWhere($qb->expr()->gt('uid', $qb->createNamedParameter($rangeStart)));
1025
+        }
1026
+        if ($rangeCount !== null) {
1027
+            $qb->setMaxResults($rangeCount);
1028
+        }
1029
+        if ($rangeStart !== null || $rangeCount !== null) {
1030
+            $qb->orderBy('uid', 'ASC');
1031
+        }
1032
+        $rs = $qb->executeQuery();
1033
+        // iterate through results
1034
+        try {
1035
+            while (($row = $rs->fetch()) !== false) {
1036
+                yield $row;
1037
+            }
1038
+        } finally {
1039
+            $rs->closeCursor();
1040
+        }
1041
+    }
1042
+
1043
+    /**
1044
+     * Returns all calendar objects with limited metadata for a calendar
1045
+     *
1046
+     * Every item contains an array with the following keys:
1047
+     *   * id - the table row id
1048
+     *   * etag - An arbitrary string
1049
+     *   * uri - a unique key which will be used to construct the uri. This can
1050
+     *     be any arbitrary string.
1051
+     *   * calendardata - The iCalendar-compatible calendar data
1052
+     *
1053
+     * @param mixed $calendarId
1054
+     * @param int $calendarType
1055
+     * @return array
1056
+     */
1057
+    public function getLimitedCalendarObjects(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1058
+        $query = $this->db->getQueryBuilder();
1059
+        $query->select(['id','uid', 'etag', 'uri', 'calendardata'])
1060
+            ->from('calendarobjects')
1061
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1062
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1063
+            ->andWhere($query->expr()->isNull('deleted_at'));
1064
+        $stmt = $query->executeQuery();
1065
+
1066
+        $result = [];
1067
+        while (($row = $stmt->fetch()) !== false) {
1068
+            $result[$row['uid']] = [
1069
+                'id' => $row['id'],
1070
+                'etag' => $row['etag'],
1071
+                'uri' => $row['uri'],
1072
+                'calendardata' => $row['calendardata'],
1073
+            ];
1074
+        }
1075
+        $stmt->closeCursor();
1076
+
1077
+        return $result;
1078
+    }
1079
+
1080
+    /**
1081
+     * Delete all of an user's shares
1082
+     *
1083
+     * @param string $principaluri
1084
+     * @return void
1085
+     */
1086
+    public function deleteAllSharesByUser($principaluri) {
1087
+        $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
1088
+    }
1089
+
1090
+    /**
1091
+     * Returns all calendar objects within a calendar.
1092
+     *
1093
+     * Every item contains an array with the following keys:
1094
+     *   * calendardata - The iCalendar-compatible calendar data
1095
+     *   * uri - a unique key which will be used to construct the uri. This can
1096
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
1097
+     *     good idea. This is only the basename, or filename, not the full
1098
+     *     path.
1099
+     *   * lastmodified - a timestamp of the last modification time
1100
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
1101
+     *   '"abcdef"')
1102
+     *   * size - The size of the calendar objects, in bytes.
1103
+     *   * component - optional, a string containing the type of object, such
1104
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
1105
+     *     the Content-Type header.
1106
+     *
1107
+     * Note that the etag is optional, but it's highly encouraged to return for
1108
+     * speed reasons.
1109
+     *
1110
+     * The calendardata is also optional. If it's not returned
1111
+     * 'getCalendarObject' will be called later, which *is* expected to return
1112
+     * calendardata.
1113
+     *
1114
+     * If neither etag or size are specified, the calendardata will be
1115
+     * used/fetched to determine these numbers. If both are specified the
1116
+     * amount of times this is needed is reduced by a great degree.
1117
+     *
1118
+     * @param mixed $calendarId
1119
+     * @param int $calendarType
1120
+     * @return array
1121
+     */
1122
+    public function getCalendarObjects($calendarId, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1123
+        $query = $this->db->getQueryBuilder();
1124
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
1125
+            ->from('calendarobjects')
1126
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1127
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1128
+            ->andWhere($query->expr()->isNull('deleted_at'));
1129
+        $stmt = $query->executeQuery();
1130
+
1131
+        $result = [];
1132
+        while (($row = $stmt->fetch()) !== false) {
1133
+            $result[] = [
1134
+                'id' => $row['id'],
1135
+                'uri' => $row['uri'],
1136
+                'lastmodified' => $row['lastmodified'],
1137
+                'etag' => '"' . $row['etag'] . '"',
1138
+                'calendarid' => $row['calendarid'],
1139
+                'size' => (int)$row['size'],
1140
+                'component' => strtolower($row['componenttype']),
1141
+                'classification' => (int)$row['classification']
1142
+            ];
1143
+        }
1144
+        $stmt->closeCursor();
1145
+
1146
+        return $result;
1147
+    }
1148
+
1149
+    public function getDeletedCalendarObjects(int $deletedBefore): array {
1150
+        $query = $this->db->getQueryBuilder();
1151
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.calendartype', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1152
+            ->from('calendarobjects', 'co')
1153
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1154
+            ->where($query->expr()->isNotNull('co.deleted_at'))
1155
+            ->andWhere($query->expr()->lt('co.deleted_at', $query->createNamedParameter($deletedBefore)));
1156
+        $stmt = $query->executeQuery();
1157
+
1158
+        $result = [];
1159
+        while (($row = $stmt->fetch()) !== false) {
1160
+            $result[] = [
1161
+                'id' => $row['id'],
1162
+                'uri' => $row['uri'],
1163
+                'lastmodified' => $row['lastmodified'],
1164
+                'etag' => '"' . $row['etag'] . '"',
1165
+                'calendarid' => (int)$row['calendarid'],
1166
+                'calendartype' => (int)$row['calendartype'],
1167
+                'size' => (int)$row['size'],
1168
+                'component' => strtolower($row['componenttype']),
1169
+                'classification' => (int)$row['classification'],
1170
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1171
+            ];
1172
+        }
1173
+        $stmt->closeCursor();
1174
+
1175
+        return $result;
1176
+    }
1177
+
1178
+    /**
1179
+     * Return all deleted calendar objects by the given principal that are not
1180
+     * in deleted calendars.
1181
+     *
1182
+     * @param string $principalUri
1183
+     * @return array
1184
+     * @throws Exception
1185
+     */
1186
+    public function getDeletedCalendarObjectsByPrincipal(string $principalUri): array {
1187
+        $query = $this->db->getQueryBuilder();
1188
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.componenttype', 'co.classification', 'co.deleted_at'])
1189
+            ->selectAlias('c.uri', 'calendaruri')
1190
+            ->from('calendarobjects', 'co')
1191
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
1192
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1193
+            ->andWhere($query->expr()->isNotNull('co.deleted_at'))
1194
+            ->andWhere($query->expr()->isNull('c.deleted_at'));
1195
+        $stmt = $query->executeQuery();
1196
+
1197
+        $result = [];
1198
+        while ($row = $stmt->fetch()) {
1199
+            $result[] = [
1200
+                'id' => $row['id'],
1201
+                'uri' => $row['uri'],
1202
+                'lastmodified' => $row['lastmodified'],
1203
+                'etag' => '"' . $row['etag'] . '"',
1204
+                'calendarid' => $row['calendarid'],
1205
+                'calendaruri' => $row['calendaruri'],
1206
+                'size' => (int)$row['size'],
1207
+                'component' => strtolower($row['componenttype']),
1208
+                'classification' => (int)$row['classification'],
1209
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1210
+            ];
1211
+        }
1212
+        $stmt->closeCursor();
1213
+
1214
+        return $result;
1215
+    }
1216
+
1217
+    /**
1218
+     * Returns information from a single calendar object, based on it's object
1219
+     * uri.
1220
+     *
1221
+     * The object uri is only the basename, or filename and not a full path.
1222
+     *
1223
+     * The returned array must have the same keys as getCalendarObjects. The
1224
+     * 'calendardata' object is required here though, while it's not required
1225
+     * for getCalendarObjects.
1226
+     *
1227
+     * This method must return null if the object did not exist.
1228
+     *
1229
+     * @param mixed $calendarId
1230
+     * @param string $objectUri
1231
+     * @param int $calendarType
1232
+     * @return array|null
1233
+     */
1234
+    public function getCalendarObject($calendarId, $objectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1235
+        $key = $calendarId . '::' . $objectUri . '::' . $calendarType;
1236
+        if (isset($this->cachedObjects[$key])) {
1237
+            return $this->cachedObjects[$key];
1238
+        }
1239
+        $query = $this->db->getQueryBuilder();
1240
+        $query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1241
+            ->from('calendarobjects')
1242
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1243
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1244
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1245
+        $stmt = $query->executeQuery();
1246
+        $row = $stmt->fetch();
1247
+        $stmt->closeCursor();
1248
+
1249
+        if (!$row) {
1250
+            return null;
1251
+        }
1252
+
1253
+        $object = $this->rowToCalendarObject($row);
1254
+        $this->cachedObjects[$key] = $object;
1255
+        return $object;
1256
+    }
1257
+
1258
+    private function rowToCalendarObject(array $row): array {
1259
+        return [
1260
+            'id' => $row['id'],
1261
+            'uri' => $row['uri'],
1262
+            'uid' => $row['uid'],
1263
+            'lastmodified' => $row['lastmodified'],
1264
+            'etag' => '"' . $row['etag'] . '"',
1265
+            'calendarid' => $row['calendarid'],
1266
+            'size' => (int)$row['size'],
1267
+            'calendardata' => $this->readBlob($row['calendardata']),
1268
+            'component' => strtolower($row['componenttype']),
1269
+            'classification' => (int)$row['classification'],
1270
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}deleted-at' => $row['deleted_at'] === null ? $row['deleted_at'] : (int)$row['deleted_at'],
1271
+        ];
1272
+    }
1273
+
1274
+    /**
1275
+     * Returns a list of calendar objects.
1276
+     *
1277
+     * This method should work identical to getCalendarObject, but instead
1278
+     * return all the calendar objects in the list as an array.
1279
+     *
1280
+     * If the backend supports this, it may allow for some speed-ups.
1281
+     *
1282
+     * @param mixed $calendarId
1283
+     * @param string[] $uris
1284
+     * @param int $calendarType
1285
+     * @return array
1286
+     */
1287
+    public function getMultipleCalendarObjects($calendarId, array $uris, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1288
+        if (empty($uris)) {
1289
+            return [];
1290
+        }
1291
+
1292
+        $chunks = array_chunk($uris, 100);
1293
+        $objects = [];
1294
+
1295
+        $query = $this->db->getQueryBuilder();
1296
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
1297
+            ->from('calendarobjects')
1298
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1299
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1300
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1301
+            ->andWhere($query->expr()->isNull('deleted_at'));
1302
+
1303
+        foreach ($chunks as $uris) {
1304
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1305
+            $result = $query->executeQuery();
1306
+
1307
+            while ($row = $result->fetch()) {
1308
+                $objects[] = [
1309
+                    'id' => $row['id'],
1310
+                    'uri' => $row['uri'],
1311
+                    'lastmodified' => $row['lastmodified'],
1312
+                    'etag' => '"' . $row['etag'] . '"',
1313
+                    'calendarid' => $row['calendarid'],
1314
+                    'size' => (int)$row['size'],
1315
+                    'calendardata' => $this->readBlob($row['calendardata']),
1316
+                    'component' => strtolower($row['componenttype']),
1317
+                    'classification' => (int)$row['classification']
1318
+                ];
1319
+            }
1320
+            $result->closeCursor();
1321
+        }
1322
+
1323
+        return $objects;
1324
+    }
1325
+
1326
+    /**
1327
+     * Creates a new calendar object.
1328
+     *
1329
+     * The object uri is only the basename, or filename and not a full path.
1330
+     *
1331
+     * It is possible return an etag from this function, which will be used in
1332
+     * the response to this PUT request. Note that the ETag must be surrounded
1333
+     * by double-quotes.
1334
+     *
1335
+     * However, you should only really return this ETag if you don't mangle the
1336
+     * calendar-data. If the result of a subsequent GET to this object is not
1337
+     * the exact same as this request body, you should omit the ETag.
1338
+     *
1339
+     * @param mixed $calendarId
1340
+     * @param string $objectUri
1341
+     * @param string $calendarData
1342
+     * @param int $calendarType
1343
+     * @return string
1344
+     */
1345
+    public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1346
+        $this->cachedObjects = [];
1347
+        $extraData = $this->getDenormalizedData($calendarData);
1348
+
1349
+        return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1350
+            // Try to detect duplicates
1351
+            $qb = $this->db->getQueryBuilder();
1352
+            $qb->select($qb->func()->count('*'))
1353
+                ->from('calendarobjects')
1354
+                ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
1355
+                ->andWhere($qb->expr()->eq('uid', $qb->createNamedParameter($extraData['uid'])))
1356
+                ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
1357
+                ->andWhere($qb->expr()->isNull('deleted_at'));
1358
+            $result = $qb->executeQuery();
1359
+            $count = (int)$result->fetchOne();
1360
+            $result->closeCursor();
1361
+
1362
+            if ($count !== 0) {
1363
+                throw new BadRequest('Calendar object with uid already exists in this calendar collection.');
1364
+            }
1365
+            // For a more specific error message we also try to explicitly look up the UID but as a deleted entry
1366
+            $qbDel = $this->db->getQueryBuilder();
1367
+            $qbDel->select('*')
1368
+                ->from('calendarobjects')
1369
+                ->where($qbDel->expr()->eq('calendarid', $qbDel->createNamedParameter($calendarId)))
1370
+                ->andWhere($qbDel->expr()->eq('uid', $qbDel->createNamedParameter($extraData['uid'])))
1371
+                ->andWhere($qbDel->expr()->eq('calendartype', $qbDel->createNamedParameter($calendarType)))
1372
+                ->andWhere($qbDel->expr()->isNotNull('deleted_at'));
1373
+            $result = $qbDel->executeQuery();
1374
+            $found = $result->fetch();
1375
+            $result->closeCursor();
1376
+            if ($found !== false) {
1377
+                // the object existed previously but has been deleted
1378
+                // remove the trashbin entry and continue as if it was a new object
1379
+                $this->deleteCalendarObject($calendarId, $found['uri']);
1380
+            }
1381
+
1382
+            $query = $this->db->getQueryBuilder();
1383
+            $query->insert('calendarobjects')
1384
+                ->values([
1385
+                    'calendarid' => $query->createNamedParameter($calendarId),
1386
+                    'uri' => $query->createNamedParameter($objectUri),
1387
+                    'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1388
+                    'lastmodified' => $query->createNamedParameter(time()),
1389
+                    'etag' => $query->createNamedParameter($extraData['etag']),
1390
+                    'size' => $query->createNamedParameter($extraData['size']),
1391
+                    'componenttype' => $query->createNamedParameter($extraData['componentType']),
1392
+                    'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1393
+                    'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1394
+                    'classification' => $query->createNamedParameter($extraData['classification']),
1395
+                    'uid' => $query->createNamedParameter($extraData['uid']),
1396
+                    'calendartype' => $query->createNamedParameter($calendarType),
1397
+                ])
1398
+                ->executeStatement();
1399
+
1400
+            $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1401
+            $this->addChanges($calendarId, [$objectUri], 1, $calendarType);
1402
+
1403
+            $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1404
+            assert($objectRow !== null);
1405
+
1406
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1407
+                $calendarRow = $this->getCalendarById($calendarId);
1408
+                $shares = $this->getShares($calendarId);
1409
+
1410
+                $this->dispatcher->dispatchTyped(new CalendarObjectCreatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1411
+            } else {
1412
+                $subscriptionRow = $this->getSubscriptionById($calendarId);
1413
+
1414
+                $this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1415
+            }
1416
+
1417
+            return '"' . $extraData['etag'] . '"';
1418
+        }, $this->db);
1419
+    }
1420
+
1421
+    /**
1422
+     * Updates an existing calendarobject, based on it's uri.
1423
+     *
1424
+     * The object uri is only the basename, or filename and not a full path.
1425
+     *
1426
+     * It is possible return an etag from this function, which will be used in
1427
+     * the response to this PUT request. Note that the ETag must be surrounded
1428
+     * by double-quotes.
1429
+     *
1430
+     * However, you should only really return this ETag if you don't mangle the
1431
+     * calendar-data. If the result of a subsequent GET to this object is not
1432
+     * the exact same as this request body, you should omit the ETag.
1433
+     *
1434
+     * @param mixed $calendarId
1435
+     * @param string $objectUri
1436
+     * @param string $calendarData
1437
+     * @param int $calendarType
1438
+     * @return string
1439
+     */
1440
+    public function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
1441
+        $this->cachedObjects = [];
1442
+        $extraData = $this->getDenormalizedData($calendarData);
1443
+
1444
+        return $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $extraData, $calendarType) {
1445
+            $query = $this->db->getQueryBuilder();
1446
+            $query->update('calendarobjects')
1447
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1448
+                ->set('lastmodified', $query->createNamedParameter(time()))
1449
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1450
+                ->set('size', $query->createNamedParameter($extraData['size']))
1451
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1452
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1453
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1454
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1455
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1456
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1457
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1458
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1459
+                ->executeStatement();
1460
+
1461
+            $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1462
+            $this->addChanges($calendarId, [$objectUri], 2, $calendarType);
1463
+
1464
+            $objectRow = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1465
+            if (is_array($objectRow)) {
1466
+                if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1467
+                    $calendarRow = $this->getCalendarById($calendarId);
1468
+                    $shares = $this->getShares($calendarId);
1469
+
1470
+                    $this->dispatcher->dispatchTyped(new CalendarObjectUpdatedEvent($calendarId, $calendarRow, $shares, $objectRow));
1471
+                } else {
1472
+                    $subscriptionRow = $this->getSubscriptionById($calendarId);
1473
+
1474
+                    $this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent($calendarId, $subscriptionRow, [], $objectRow));
1475
+                }
1476
+            }
1477
+
1478
+            return '"' . $extraData['etag'] . '"';
1479
+        }, $this->db);
1480
+    }
1481
+
1482
+    /**
1483
+     * Moves a calendar object from calendar to calendar.
1484
+     *
1485
+     * @param string $sourcePrincipalUri
1486
+     * @param int $sourceObjectId
1487
+     * @param string $targetPrincipalUri
1488
+     * @param int $targetCalendarId
1489
+     * @param string $tragetObjectUri
1490
+     * @param int $calendarType
1491
+     * @return bool
1492
+     * @throws Exception
1493
+     */
1494
+    public function moveCalendarObject(string $sourcePrincipalUri, int $sourceObjectId, string $targetPrincipalUri, int $targetCalendarId, string $tragetObjectUri, int $calendarType = self::CALENDAR_TYPE_CALENDAR): bool {
1495
+        $this->cachedObjects = [];
1496
+        return $this->atomic(function () use ($sourcePrincipalUri, $sourceObjectId, $targetPrincipalUri, $targetCalendarId, $tragetObjectUri, $calendarType) {
1497
+            $object = $this->getCalendarObjectById($sourcePrincipalUri, $sourceObjectId);
1498
+            if (empty($object)) {
1499
+                return false;
1500
+            }
1501
+
1502
+            $sourceCalendarId = $object['calendarid'];
1503
+            $sourceObjectUri = $object['uri'];
1504
+
1505
+            $query = $this->db->getQueryBuilder();
1506
+            $query->update('calendarobjects')
1507
+                ->set('calendarid', $query->createNamedParameter($targetCalendarId, IQueryBuilder::PARAM_INT))
1508
+                ->set('uri', $query->createNamedParameter($tragetObjectUri, IQueryBuilder::PARAM_STR))
1509
+                ->where($query->expr()->eq('id', $query->createNamedParameter($sourceObjectId, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT))
1510
+                ->executeStatement();
1511
+
1512
+            $this->purgeProperties($sourceCalendarId, $sourceObjectId);
1513
+            $this->updateProperties($targetCalendarId, $tragetObjectUri, $object['calendardata'], $calendarType);
1514
+
1515
+            $this->addChanges($sourceCalendarId, [$sourceObjectUri], 3, $calendarType);
1516
+            $this->addChanges($targetCalendarId, [$tragetObjectUri], 1, $calendarType);
1517
+
1518
+            $object = $this->getCalendarObjectById($targetPrincipalUri, $sourceObjectId);
1519
+            // Calendar Object wasn't found - possibly because it was deleted in the meantime by a different client
1520
+            if (empty($object)) {
1521
+                return false;
1522
+            }
1523
+
1524
+            $targetCalendarRow = $this->getCalendarById($targetCalendarId);
1525
+            // the calendar this event is being moved to does not exist any longer
1526
+            if (empty($targetCalendarRow)) {
1527
+                return false;
1528
+            }
1529
+
1530
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1531
+                $sourceShares = $this->getShares($sourceCalendarId);
1532
+                $targetShares = $this->getShares($targetCalendarId);
1533
+                $sourceCalendarRow = $this->getCalendarById($sourceCalendarId);
1534
+                $this->dispatcher->dispatchTyped(new CalendarObjectMovedEvent($sourceCalendarId, $sourceCalendarRow, $targetCalendarId, $targetCalendarRow, $sourceShares, $targetShares, $object));
1535
+            }
1536
+            return true;
1537
+        }, $this->db);
1538
+    }
1539
+
1540
+    /**
1541
+     * Deletes an existing calendar object.
1542
+     *
1543
+     * The object uri is only the basename, or filename and not a full path.
1544
+     *
1545
+     * @param mixed $calendarId
1546
+     * @param string $objectUri
1547
+     * @param int $calendarType
1548
+     * @param bool $forceDeletePermanently
1549
+     * @return void
1550
+     */
1551
+    public function deleteCalendarObject($calendarId, $objectUri, $calendarType = self::CALENDAR_TYPE_CALENDAR, bool $forceDeletePermanently = false) {
1552
+        $this->cachedObjects = [];
1553
+        $this->atomic(function () use ($calendarId, $objectUri, $calendarType, $forceDeletePermanently): void {
1554
+            $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1555
+
1556
+            if ($data === null) {
1557
+                // Nothing to delete
1558
+                return;
1559
+            }
1560
+
1561
+            if ($forceDeletePermanently || $this->config->getAppValue(Application::APP_ID, RetentionService::RETENTION_CONFIG_KEY) === '0') {
1562
+                $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1563
+                $stmt->execute([$calendarId, $objectUri, $calendarType]);
1564
+
1565
+                $this->purgeProperties($calendarId, $data['id']);
1566
+
1567
+                $this->purgeObjectInvitations($data['uid']);
1568
+
1569
+                if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1570
+                    $calendarRow = $this->getCalendarById($calendarId);
1571
+                    $shares = $this->getShares($calendarId);
1572
+
1573
+                    $this->dispatcher->dispatchTyped(new CalendarObjectDeletedEvent($calendarId, $calendarRow, $shares, $data));
1574
+                } else {
1575
+                    $subscriptionRow = $this->getSubscriptionById($calendarId);
1576
+
1577
+                    $this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent($calendarId, $subscriptionRow, [], $data));
1578
+                }
1579
+            } else {
1580
+                $pathInfo = pathinfo($data['uri']);
1581
+                if (!empty($pathInfo['extension'])) {
1582
+                    // Append a suffix to "free" the old URI for recreation
1583
+                    $newUri = sprintf(
1584
+                        '%s-deleted.%s',
1585
+                        $pathInfo['filename'],
1586
+                        $pathInfo['extension']
1587
+                    );
1588
+                } else {
1589
+                    $newUri = sprintf(
1590
+                        '%s-deleted',
1591
+                        $pathInfo['filename']
1592
+                    );
1593
+                }
1594
+
1595
+                // Try to detect conflicts before the DB does
1596
+                // As unlikely as it seems, this can happen when the user imports, then deletes, imports and deletes again
1597
+                $newObject = $this->getCalendarObject($calendarId, $newUri, $calendarType);
1598
+                if ($newObject !== null) {
1599
+                    throw new Forbidden("A calendar object with URI $newUri already exists in calendar $calendarId, therefore this object can't be moved into the trashbin");
1600
+                }
1601
+
1602
+                $qb = $this->db->getQueryBuilder();
1603
+                $markObjectDeletedQuery = $qb->update('calendarobjects')
1604
+                    ->set('deleted_at', $qb->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
1605
+                    ->set('uri', $qb->createNamedParameter($newUri))
1606
+                    ->where(
1607
+                        $qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)),
1608
+                        $qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
1609
+                        $qb->expr()->eq('uri', $qb->createNamedParameter($objectUri))
1610
+                    );
1611
+                $markObjectDeletedQuery->executeStatement();
1612
+
1613
+                $calendarData = $this->getCalendarById($calendarId);
1614
+                if ($calendarData !== null) {
1615
+                    $this->dispatcher->dispatchTyped(
1616
+                        new CalendarObjectMovedToTrashEvent(
1617
+                            $calendarId,
1618
+                            $calendarData,
1619
+                            $this->getShares($calendarId),
1620
+                            $data
1621
+                        )
1622
+                    );
1623
+                }
1624
+            }
1625
+
1626
+            $this->addChanges($calendarId, [$objectUri], 3, $calendarType);
1627
+        }, $this->db);
1628
+    }
1629
+
1630
+    /**
1631
+     * @param mixed $objectData
1632
+     *
1633
+     * @throws Forbidden
1634
+     */
1635
+    public function restoreCalendarObject(array $objectData): void {
1636
+        $this->cachedObjects = [];
1637
+        $this->atomic(function () use ($objectData): void {
1638
+            $id = (int)$objectData['id'];
1639
+            $restoreUri = str_replace('-deleted.ics', '.ics', $objectData['uri']);
1640
+            $targetObject = $this->getCalendarObject(
1641
+                $objectData['calendarid'],
1642
+                $restoreUri
1643
+            );
1644
+            if ($targetObject !== null) {
1645
+                throw new Forbidden("Can not restore calendar $id because a calendar object with the URI $restoreUri already exists");
1646
+            }
1647
+
1648
+            $qb = $this->db->getQueryBuilder();
1649
+            $update = $qb->update('calendarobjects')
1650
+                ->set('uri', $qb->createNamedParameter($restoreUri))
1651
+                ->set('deleted_at', $qb->createNamedParameter(null))
1652
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1653
+            $update->executeStatement();
1654
+
1655
+            // Make sure this change is tracked in the changes table
1656
+            $qb2 = $this->db->getQueryBuilder();
1657
+            $selectObject = $qb2->select('calendardata', 'uri', 'calendarid', 'calendartype')
1658
+                ->selectAlias('componenttype', 'component')
1659
+                ->from('calendarobjects')
1660
+                ->where($qb2->expr()->eq('id', $qb2->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
1661
+            $result = $selectObject->executeQuery();
1662
+            $row = $result->fetch();
1663
+            $result->closeCursor();
1664
+            if ($row === false) {
1665
+                // Welp, this should possibly not have happened, but let's ignore
1666
+                return;
1667
+            }
1668
+            $this->addChanges($row['calendarid'], [$row['uri']], 1, (int)$row['calendartype']);
1669
+
1670
+            $calendarRow = $this->getCalendarById((int)$row['calendarid']);
1671
+            if ($calendarRow === null) {
1672
+                throw new RuntimeException('Calendar object data that was just written can\'t be read back. Check your database configuration.');
1673
+            }
1674
+            $this->dispatcher->dispatchTyped(
1675
+                new CalendarObjectRestoredEvent(
1676
+                    (int)$objectData['calendarid'],
1677
+                    $calendarRow,
1678
+                    $this->getShares((int)$row['calendarid']),
1679
+                    $row
1680
+                )
1681
+            );
1682
+        }, $this->db);
1683
+    }
1684
+
1685
+    /**
1686
+     * Performs a calendar-query on the contents of this calendar.
1687
+     *
1688
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1689
+     * calendar-query it is possible for a client to request a specific set of
1690
+     * object, based on contents of iCalendar properties, date-ranges and
1691
+     * iCalendar component types (VTODO, VEVENT).
1692
+     *
1693
+     * This method should just return a list of (relative) urls that match this
1694
+     * query.
1695
+     *
1696
+     * The list of filters are specified as an array. The exact array is
1697
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1698
+     *
1699
+     * Note that it is extremely likely that getCalendarObject for every path
1700
+     * returned from this method will be called almost immediately after. You
1701
+     * may want to anticipate this to speed up these requests.
1702
+     *
1703
+     * This method provides a default implementation, which parses *all* the
1704
+     * iCalendar objects in the specified calendar.
1705
+     *
1706
+     * This default may well be good enough for personal use, and calendars
1707
+     * that aren't very large. But if you anticipate high usage, big calendars
1708
+     * or high loads, you are strongly advised to optimize certain paths.
1709
+     *
1710
+     * The best way to do so is override this method and to optimize
1711
+     * specifically for 'common filters'.
1712
+     *
1713
+     * Requests that are extremely common are:
1714
+     *   * requests for just VEVENTS
1715
+     *   * requests for just VTODO
1716
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1717
+     *
1718
+     * ..and combinations of these requests. It may not be worth it to try to
1719
+     * handle every possible situation and just rely on the (relatively
1720
+     * easy to use) CalendarQueryValidator to handle the rest.
1721
+     *
1722
+     * Note that especially time-range-filters may be difficult to parse. A
1723
+     * time-range filter specified on a VEVENT must for instance also handle
1724
+     * recurrence rules correctly.
1725
+     * A good example of how to interpret all these filters can also simply
1726
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1727
+     * as possible, so it gives you a good idea on what type of stuff you need
1728
+     * to think of.
1729
+     *
1730
+     * @param mixed $calendarId
1731
+     * @param array $filters
1732
+     * @param int $calendarType
1733
+     * @return array
1734
+     */
1735
+    public function calendarQuery($calendarId, array $filters, $calendarType = self::CALENDAR_TYPE_CALENDAR):array {
1736
+        $componentType = null;
1737
+        $requirePostFilter = true;
1738
+        $timeRange = null;
1739
+
1740
+        // if no filters were specified, we don't need to filter after a query
1741
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1742
+            $requirePostFilter = false;
1743
+        }
1744
+
1745
+        // Figuring out if there's a component filter
1746
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1747
+            $componentType = $filters['comp-filters'][0]['name'];
1748
+
1749
+            // Checking if we need post-filters
1750
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1751
+                $requirePostFilter = false;
1752
+            }
1753
+            // There was a time-range filter
1754
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range']) && is_array($filters['comp-filters'][0]['time-range'])) {
1755
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1756
+
1757
+                // If start time OR the end time is not specified, we can do a
1758
+                // 100% accurate mysql query.
1759
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1760
+                    $requirePostFilter = false;
1761
+                }
1762
+            }
1763
+        }
1764
+        $query = $this->db->getQueryBuilder();
1765
+        $query->select(['id', 'uri', 'uid', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification', 'deleted_at'])
1766
+            ->from('calendarobjects')
1767
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1768
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1769
+            ->andWhere($query->expr()->isNull('deleted_at'));
1770
+
1771
+        if ($componentType) {
1772
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1773
+        }
1774
+
1775
+        if ($timeRange && $timeRange['start']) {
1776
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1777
+        }
1778
+        if ($timeRange && $timeRange['end']) {
1779
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1780
+        }
1781
+
1782
+        $stmt = $query->executeQuery();
1783
+
1784
+        $result = [];
1785
+        while ($row = $stmt->fetch()) {
1786
+            // if we leave it as a blob we can't read it both from the post filter and the rowToCalendarObject
1787
+            if (isset($row['calendardata'])) {
1788
+                $row['calendardata'] = $this->readBlob($row['calendardata']);
1789
+            }
1790
+
1791
+            if ($requirePostFilter) {
1792
+                // validateFilterForObject will parse the calendar data
1793
+                // catch parsing errors
1794
+                try {
1795
+                    $matches = $this->validateFilterForObject($row, $filters);
1796
+                } catch (ParseException $ex) {
1797
+                    $this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1798
+                        'app' => 'dav',
1799
+                        'exception' => $ex,
1800
+                    ]);
1801
+                    continue;
1802
+                } catch (InvalidDataException $ex) {
1803
+                    $this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:' . $calendarId . ' uri:' . $row['uri'], [
1804
+                        'app' => 'dav',
1805
+                        'exception' => $ex,
1806
+                    ]);
1807
+                    continue;
1808
+                } catch (MaxInstancesExceededException $ex) {
1809
+                    $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'], [
1810
+                        'app' => 'dav',
1811
+                        'exception' => $ex,
1812
+                    ]);
1813
+                    continue;
1814
+                }
1815
+
1816
+                if (!$matches) {
1817
+                    continue;
1818
+                }
1819
+            }
1820
+            $result[] = $row['uri'];
1821
+            $key = $calendarId . '::' . $row['uri'] . '::' . $calendarType;
1822
+            $this->cachedObjects[$key] = $this->rowToCalendarObject($row);
1823
+        }
1824
+
1825
+        return $result;
1826
+    }
1827
+
1828
+    /**
1829
+     * custom Nextcloud search extension for CalDAV
1830
+     *
1831
+     * TODO - this should optionally cover cached calendar objects as well
1832
+     *
1833
+     * @param string $principalUri
1834
+     * @param array $filters
1835
+     * @param integer|null $limit
1836
+     * @param integer|null $offset
1837
+     * @return array
1838
+     */
1839
+    public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) {
1840
+        return $this->atomic(function () use ($principalUri, $filters, $limit, $offset) {
1841
+            $calendars = $this->getCalendarsForUser($principalUri);
1842
+            $ownCalendars = [];
1843
+            $sharedCalendars = [];
1844
+
1845
+            $uriMapper = [];
1846
+
1847
+            foreach ($calendars as $calendar) {
1848
+                if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1849
+                    $ownCalendars[] = $calendar['id'];
1850
+                } else {
1851
+                    $sharedCalendars[] = $calendar['id'];
1852
+                }
1853
+                $uriMapper[$calendar['id']] = $calendar['uri'];
1854
+            }
1855
+            if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1856
+                return [];
1857
+            }
1858
+
1859
+            $query = $this->db->getQueryBuilder();
1860
+            // Calendar id expressions
1861
+            $calendarExpressions = [];
1862
+            foreach ($ownCalendars as $id) {
1863
+                $calendarExpressions[] = $query->expr()->andX(
1864
+                    $query->expr()->eq('c.calendarid',
1865
+                        $query->createNamedParameter($id)),
1866
+                    $query->expr()->eq('c.calendartype',
1867
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1868
+            }
1869
+            foreach ($sharedCalendars as $id) {
1870
+                $calendarExpressions[] = $query->expr()->andX(
1871
+                    $query->expr()->eq('c.calendarid',
1872
+                        $query->createNamedParameter($id)),
1873
+                    $query->expr()->eq('c.classification',
1874
+                        $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1875
+                    $query->expr()->eq('c.calendartype',
1876
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1877
+            }
1878
+
1879
+            if (count($calendarExpressions) === 1) {
1880
+                $calExpr = $calendarExpressions[0];
1881
+            } else {
1882
+                $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1883
+            }
1884
+
1885
+            // Component expressions
1886
+            $compExpressions = [];
1887
+            foreach ($filters['comps'] as $comp) {
1888
+                $compExpressions[] = $query->expr()
1889
+                    ->eq('c.componenttype', $query->createNamedParameter($comp));
1890
+            }
1891
+
1892
+            if (count($compExpressions) === 1) {
1893
+                $compExpr = $compExpressions[0];
1894
+            } else {
1895
+                $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1896
+            }
1897
+
1898
+            if (!isset($filters['props'])) {
1899
+                $filters['props'] = [];
1900
+            }
1901
+            if (!isset($filters['params'])) {
1902
+                $filters['params'] = [];
1903
+            }
1904
+
1905
+            $propParamExpressions = [];
1906
+            foreach ($filters['props'] as $prop) {
1907
+                $propParamExpressions[] = $query->expr()->andX(
1908
+                    $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1909
+                    $query->expr()->isNull('i.parameter')
1910
+                );
1911
+            }
1912
+            foreach ($filters['params'] as $param) {
1913
+                $propParamExpressions[] = $query->expr()->andX(
1914
+                    $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1915
+                    $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1916
+                );
1917
+            }
1918
+
1919
+            if (count($propParamExpressions) === 1) {
1920
+                $propParamExpr = $propParamExpressions[0];
1921
+            } else {
1922
+                $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1923
+            }
1924
+
1925
+            $query->select(['c.calendarid', 'c.uri'])
1926
+                ->from($this->dbObjectPropertiesTable, 'i')
1927
+                ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1928
+                ->where($calExpr)
1929
+                ->andWhere($compExpr)
1930
+                ->andWhere($propParamExpr)
1931
+                ->andWhere($query->expr()->iLike('i.value',
1932
+                    $query->createNamedParameter('%' . $this->db->escapeLikeParameter($filters['search-term']) . '%')))
1933
+                ->andWhere($query->expr()->isNull('deleted_at'));
1934
+
1935
+            if ($offset) {
1936
+                $query->setFirstResult($offset);
1937
+            }
1938
+            if ($limit) {
1939
+                $query->setMaxResults($limit);
1940
+            }
1941
+
1942
+            $stmt = $query->executeQuery();
1943
+
1944
+            $result = [];
1945
+            while ($row = $stmt->fetch()) {
1946
+                $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1947
+                if (!in_array($path, $result)) {
1948
+                    $result[] = $path;
1949
+                }
1950
+            }
1951
+
1952
+            return $result;
1953
+        }, $this->db);
1954
+    }
1955
+
1956
+    /**
1957
+     * used for Nextcloud's calendar API
1958
+     *
1959
+     * @param array $calendarInfo
1960
+     * @param string $pattern
1961
+     * @param array $searchProperties
1962
+     * @param array $options
1963
+     * @param integer|null $limit
1964
+     * @param integer|null $offset
1965
+     *
1966
+     * @return array
1967
+     */
1968
+    public function search(
1969
+        array $calendarInfo,
1970
+        $pattern,
1971
+        array $searchProperties,
1972
+        array $options,
1973
+        $limit,
1974
+        $offset,
1975
+    ) {
1976
+        $outerQuery = $this->db->getQueryBuilder();
1977
+        $innerQuery = $this->db->getQueryBuilder();
1978
+
1979
+        if (isset($calendarInfo['source'])) {
1980
+            $calendarType = self::CALENDAR_TYPE_SUBSCRIPTION;
1981
+        } else {
1982
+            $calendarType = self::CALENDAR_TYPE_CALENDAR;
1983
+        }
1984
+
1985
+        $innerQuery->selectDistinct('op.objectid')
1986
+            ->from($this->dbObjectPropertiesTable, 'op')
1987
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
1988
+                $outerQuery->createNamedParameter($calendarInfo['id'])))
1989
+            ->andWhere($innerQuery->expr()->eq('op.calendartype',
1990
+                $outerQuery->createNamedParameter($calendarType)));
1991
+
1992
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1993
+            ->from('calendarobjects', 'c')
1994
+            ->where($outerQuery->expr()->isNull('deleted_at'));
1995
+
1996
+        // only return public items for shared calendars for now
1997
+        if (isset($calendarInfo['{http://owncloud.org/ns}owner-principal']) === false || $calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1998
+            $outerQuery->andWhere($outerQuery->expr()->eq('c.classification',
1999
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2000
+        }
2001
+
2002
+        if (!empty($searchProperties)) {
2003
+            $or = [];
2004
+            foreach ($searchProperties as $searchProperty) {
2005
+                $or[] = $innerQuery->expr()->eq('op.name',
2006
+                    $outerQuery->createNamedParameter($searchProperty));
2007
+            }
2008
+            $innerQuery->andWhere($innerQuery->expr()->orX(...$or));
2009
+        }
2010
+
2011
+        if ($pattern !== '') {
2012
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
2013
+                $outerQuery->createNamedParameter('%'
2014
+                    . $this->db->escapeLikeParameter($pattern) . '%')));
2015
+        }
2016
+
2017
+        $start = null;
2018
+        $end = null;
2019
+
2020
+        $hasLimit = is_int($limit);
2021
+        $hasTimeRange = false;
2022
+
2023
+        if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2024
+            /** @var DateTimeInterface $start */
2025
+            $start = $options['timerange']['start'];
2026
+            $outerQuery->andWhere(
2027
+                $outerQuery->expr()->gt(
2028
+                    'lastoccurence',
2029
+                    $outerQuery->createNamedParameter($start->getTimestamp())
2030
+                )
2031
+            );
2032
+            $hasTimeRange = true;
2033
+        }
2034
+
2035
+        if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2036
+            /** @var DateTimeInterface $end */
2037
+            $end = $options['timerange']['end'];
2038
+            $outerQuery->andWhere(
2039
+                $outerQuery->expr()->lt(
2040
+                    'firstoccurence',
2041
+                    $outerQuery->createNamedParameter($end->getTimestamp())
2042
+                )
2043
+            );
2044
+            $hasTimeRange = true;
2045
+        }
2046
+
2047
+        if (isset($options['uid'])) {
2048
+            $outerQuery->andWhere($outerQuery->expr()->eq('uid', $outerQuery->createNamedParameter($options['uid'])));
2049
+        }
2050
+
2051
+        if (!empty($options['types'])) {
2052
+            $or = [];
2053
+            foreach ($options['types'] as $type) {
2054
+                $or[] = $outerQuery->expr()->eq('componenttype',
2055
+                    $outerQuery->createNamedParameter($type));
2056
+            }
2057
+            $outerQuery->andWhere($outerQuery->expr()->orX(...$or));
2058
+        }
2059
+
2060
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id', $outerQuery->createFunction($innerQuery->getSQL())));
2061
+
2062
+        // Without explicit order by its undefined in which order the SQL server returns the events.
2063
+        // For the pagination with hasLimit and hasTimeRange, a stable ordering is helpful.
2064
+        $outerQuery->addOrderBy('id');
2065
+
2066
+        $offset = (int)$offset;
2067
+        $outerQuery->setFirstResult($offset);
2068
+
2069
+        $calendarObjects = [];
2070
+
2071
+        if ($hasLimit && $hasTimeRange) {
2072
+            /**
2073
+             * Event recurrences are evaluated at runtime because the database only knows the first and last occurrence.
2074
+             *
2075
+             * Given, a user created 8 events with a yearly reoccurrence and two for events tomorrow.
2076
+             * The upcoming event widget asks the CalDAV backend for 7 events within the next 14 days.
2077
+             *
2078
+             * If limit 7 is applied to the SQL query, we find the 7 events with a yearly reoccurrence
2079
+             * and discard the events after evaluating the reoccurrence rules because they are not due within
2080
+             * the next 14 days and end up with an empty result even if there are two events to show.
2081
+             *
2082
+             * The workaround for search requests with a limit and time range is asking for more row than requested
2083
+             * and retrying if we have not reached the limit.
2084
+             *
2085
+             * 25 rows and 3 retries is entirely arbitrary.
2086
+             */
2087
+            $maxResults = (int)max($limit, 25);
2088
+            $outerQuery->setMaxResults($maxResults);
2089
+
2090
+            for ($attempt = $objectsCount = 0; $attempt < 3 && $objectsCount < $limit; $attempt++) {
2091
+                $objectsCount = array_push($calendarObjects, ...$this->searchCalendarObjects($outerQuery, $start, $end));
2092
+                $outerQuery->setFirstResult($offset += $maxResults);
2093
+            }
2094
+
2095
+            $calendarObjects = array_slice($calendarObjects, 0, $limit, false);
2096
+        } else {
2097
+            $outerQuery->setMaxResults($limit);
2098
+            $calendarObjects = $this->searchCalendarObjects($outerQuery, $start, $end);
2099
+        }
2100
+
2101
+        $calendarObjects = array_map(function ($o) use ($options) {
2102
+            $calendarData = Reader::read($o['calendardata']);
2103
+
2104
+            // Expand recurrences if an explicit time range is requested
2105
+            if ($calendarData instanceof VCalendar
2106
+                && isset($options['timerange']['start'], $options['timerange']['end'])) {
2107
+                $calendarData = $calendarData->expand(
2108
+                    $options['timerange']['start'],
2109
+                    $options['timerange']['end'],
2110
+                );
2111
+            }
2112
+
2113
+            $comps = $calendarData->getComponents();
2114
+            $objects = [];
2115
+            $timezones = [];
2116
+            foreach ($comps as $comp) {
2117
+                if ($comp instanceof VTimeZone) {
2118
+                    $timezones[] = $comp;
2119
+                } else {
2120
+                    $objects[] = $comp;
2121
+                }
2122
+            }
2123
+
2124
+            return [
2125
+                'id' => $o['id'],
2126
+                'type' => $o['componenttype'],
2127
+                'uid' => $o['uid'],
2128
+                'uri' => $o['uri'],
2129
+                'objects' => array_map(function ($c) {
2130
+                    return $this->transformSearchData($c);
2131
+                }, $objects),
2132
+                'timezones' => array_map(function ($c) {
2133
+                    return $this->transformSearchData($c);
2134
+                }, $timezones),
2135
+            ];
2136
+        }, $calendarObjects);
2137
+
2138
+        usort($calendarObjects, function (array $a, array $b) {
2139
+            /** @var DateTimeImmutable $startA */
2140
+            $startA = $a['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2141
+            /** @var DateTimeImmutable $startB */
2142
+            $startB = $b['objects'][0]['DTSTART'][0] ?? new DateTimeImmutable(self::MAX_DATE);
2143
+
2144
+            return $startA->getTimestamp() <=> $startB->getTimestamp();
2145
+        });
2146
+
2147
+        return $calendarObjects;
2148
+    }
2149
+
2150
+    private function searchCalendarObjects(IQueryBuilder $query, ?DateTimeInterface $start, ?DateTimeInterface $end): array {
2151
+        $calendarObjects = [];
2152
+        $filterByTimeRange = ($start instanceof DateTimeInterface) || ($end instanceof DateTimeInterface);
2153
+
2154
+        $result = $query->executeQuery();
2155
+
2156
+        while (($row = $result->fetch()) !== false) {
2157
+            if ($filterByTimeRange === false) {
2158
+                // No filter required
2159
+                $calendarObjects[] = $row;
2160
+                continue;
2161
+            }
2162
+
2163
+            try {
2164
+                $isValid = $this->validateFilterForObject($row, [
2165
+                    'name' => 'VCALENDAR',
2166
+                    'comp-filters' => [
2167
+                        [
2168
+                            'name' => 'VEVENT',
2169
+                            'comp-filters' => [],
2170
+                            'prop-filters' => [],
2171
+                            'is-not-defined' => false,
2172
+                            'time-range' => [
2173
+                                'start' => $start,
2174
+                                'end' => $end,
2175
+                            ],
2176
+                        ],
2177
+                    ],
2178
+                    'prop-filters' => [],
2179
+                    'is-not-defined' => false,
2180
+                    'time-range' => null,
2181
+                ]);
2182
+            } catch (MaxInstancesExceededException $ex) {
2183
+                $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'], [
2184
+                    'app' => 'dav',
2185
+                    'exception' => $ex,
2186
+                ]);
2187
+                continue;
2188
+            }
2189
+
2190
+            if (is_resource($row['calendardata'])) {
2191
+                // Put the stream back to the beginning so it can be read another time
2192
+                rewind($row['calendardata']);
2193
+            }
2194
+
2195
+            if ($isValid) {
2196
+                $calendarObjects[] = $row;
2197
+            }
2198
+        }
2199
+
2200
+        $result->closeCursor();
2201
+
2202
+        return $calendarObjects;
2203
+    }
2204
+
2205
+    /**
2206
+     * @param Component $comp
2207
+     * @return array
2208
+     */
2209
+    private function transformSearchData(Component $comp) {
2210
+        $data = [];
2211
+        /** @var Component[] $subComponents */
2212
+        $subComponents = $comp->getComponents();
2213
+        /** @var Property[] $properties */
2214
+        $properties = array_filter($comp->children(), function ($c) {
2215
+            return $c instanceof Property;
2216
+        });
2217
+        $validationRules = $comp->getValidationRules();
2218
+
2219
+        foreach ($subComponents as $subComponent) {
2220
+            $name = $subComponent->name;
2221
+            if (!isset($data[$name])) {
2222
+                $data[$name] = [];
2223
+            }
2224
+            $data[$name][] = $this->transformSearchData($subComponent);
2225
+        }
2226
+
2227
+        foreach ($properties as $property) {
2228
+            $name = $property->name;
2229
+            if (!isset($validationRules[$name])) {
2230
+                $validationRules[$name] = '*';
2231
+            }
2232
+
2233
+            $rule = $validationRules[$property->name];
2234
+            if ($rule === '+' || $rule === '*') { // multiple
2235
+                if (!isset($data[$name])) {
2236
+                    $data[$name] = [];
2237
+                }
2238
+
2239
+                $data[$name][] = $this->transformSearchProperty($property);
2240
+            } else { // once
2241
+                $data[$name] = $this->transformSearchProperty($property);
2242
+            }
2243
+        }
2244
+
2245
+        return $data;
2246
+    }
2247
+
2248
+    /**
2249
+     * @param Property $prop
2250
+     * @return array
2251
+     */
2252
+    private function transformSearchProperty(Property $prop) {
2253
+        // No need to check Date, as it extends DateTime
2254
+        if ($prop instanceof Property\ICalendar\DateTime) {
2255
+            $value = $prop->getDateTime();
2256
+        } else {
2257
+            $value = $prop->getValue();
2258
+        }
2259
+
2260
+        return [
2261
+            $value,
2262
+            $prop->parameters()
2263
+        ];
2264
+    }
2265
+
2266
+    /**
2267
+     * @param string $principalUri
2268
+     * @param string $pattern
2269
+     * @param array $componentTypes
2270
+     * @param array $searchProperties
2271
+     * @param array $searchParameters
2272
+     * @param array $options
2273
+     * @return array
2274
+     */
2275
+    public function searchPrincipalUri(string $principalUri,
2276
+        string $pattern,
2277
+        array $componentTypes,
2278
+        array $searchProperties,
2279
+        array $searchParameters,
2280
+        array $options = [],
2281
+    ): array {
2282
+        return $this->atomic(function () use ($principalUri, $pattern, $componentTypes, $searchProperties, $searchParameters, $options) {
2283
+            $escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false;
2284
+
2285
+            $calendarObjectIdQuery = $this->db->getQueryBuilder();
2286
+            $calendarOr = [];
2287
+            $searchOr = [];
2288
+
2289
+            // Fetch calendars and subscription
2290
+            $calendars = $this->getCalendarsForUser($principalUri);
2291
+            $subscriptions = $this->getSubscriptionsForUser($principalUri);
2292
+            foreach ($calendars as $calendar) {
2293
+                $calendarAnd = $calendarObjectIdQuery->expr()->andX(
2294
+                    $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$calendar['id'])),
2295
+                    $calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)),
2296
+                );
2297
+
2298
+                // If it's shared, limit search to public events
2299
+                if (isset($calendar['{http://owncloud.org/ns}owner-principal'])
2300
+                    && $calendar['principaluri'] !== $calendar['{http://owncloud.org/ns}owner-principal']) {
2301
+                    $calendarAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2302
+                }
2303
+
2304
+                $calendarOr[] = $calendarAnd;
2305
+            }
2306
+            foreach ($subscriptions as $subscription) {
2307
+                $subscriptionAnd = $calendarObjectIdQuery->expr()->andX(
2308
+                    $calendarObjectIdQuery->expr()->eq('cob.calendarid', $calendarObjectIdQuery->createNamedParameter((int)$subscription['id'])),
2309
+                    $calendarObjectIdQuery->expr()->eq('cob.calendartype', $calendarObjectIdQuery->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)),
2310
+                );
2311
+
2312
+                // If it's shared, limit search to public events
2313
+                if (isset($subscription['{http://owncloud.org/ns}owner-principal'])
2314
+                    && $subscription['principaluri'] !== $subscription['{http://owncloud.org/ns}owner-principal']) {
2315
+                    $subscriptionAnd->add($calendarObjectIdQuery->expr()->eq('co.classification', $calendarObjectIdQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
2316
+                }
2317
+
2318
+                $calendarOr[] = $subscriptionAnd;
2319
+            }
2320
+
2321
+            foreach ($searchProperties as $property) {
2322
+                $propertyAnd = $calendarObjectIdQuery->expr()->andX(
2323
+                    $calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2324
+                    $calendarObjectIdQuery->expr()->isNull('cob.parameter'),
2325
+                );
2326
+
2327
+                $searchOr[] = $propertyAnd;
2328
+            }
2329
+            foreach ($searchParameters as $property => $parameter) {
2330
+                $parameterAnd = $calendarObjectIdQuery->expr()->andX(
2331
+                    $calendarObjectIdQuery->expr()->eq('cob.name', $calendarObjectIdQuery->createNamedParameter($property, IQueryBuilder::PARAM_STR)),
2332
+                    $calendarObjectIdQuery->expr()->eq('cob.parameter', $calendarObjectIdQuery->createNamedParameter($parameter, IQueryBuilder::PARAM_STR_ARRAY)),
2333
+                );
2334
+
2335
+                $searchOr[] = $parameterAnd;
2336
+            }
2337
+
2338
+            if (empty($calendarOr)) {
2339
+                return [];
2340
+            }
2341
+            if (empty($searchOr)) {
2342
+                return [];
2343
+            }
2344
+
2345
+            $calendarObjectIdQuery->selectDistinct('cob.objectid')
2346
+                ->from($this->dbObjectPropertiesTable, 'cob')
2347
+                ->leftJoin('cob', 'calendarobjects', 'co', $calendarObjectIdQuery->expr()->eq('co.id', 'cob.objectid'))
2348
+                ->andWhere($calendarObjectIdQuery->expr()->in('co.componenttype', $calendarObjectIdQuery->createNamedParameter($componentTypes, IQueryBuilder::PARAM_STR_ARRAY)))
2349
+                ->andWhere($calendarObjectIdQuery->expr()->orX(...$calendarOr))
2350
+                ->andWhere($calendarObjectIdQuery->expr()->orX(...$searchOr))
2351
+                ->andWhere($calendarObjectIdQuery->expr()->isNull('deleted_at'));
2352
+
2353
+            if ($pattern !== '') {
2354
+                if (!$escapePattern) {
2355
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter($pattern)));
2356
+                } else {
2357
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->ilike('cob.value', $calendarObjectIdQuery->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
2358
+                }
2359
+            }
2360
+
2361
+            if (isset($options['limit'])) {
2362
+                $calendarObjectIdQuery->setMaxResults($options['limit']);
2363
+            }
2364
+            if (isset($options['offset'])) {
2365
+                $calendarObjectIdQuery->setFirstResult($options['offset']);
2366
+            }
2367
+            if (isset($options['timerange'])) {
2368
+                if (isset($options['timerange']['start']) && $options['timerange']['start'] instanceof DateTimeInterface) {
2369
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->gt(
2370
+                        'lastoccurence',
2371
+                        $calendarObjectIdQuery->createNamedParameter($options['timerange']['start']->getTimeStamp()),
2372
+                    ));
2373
+                }
2374
+                if (isset($options['timerange']['end']) && $options['timerange']['end'] instanceof DateTimeInterface) {
2375
+                    $calendarObjectIdQuery->andWhere($calendarObjectIdQuery->expr()->lt(
2376
+                        'firstoccurence',
2377
+                        $calendarObjectIdQuery->createNamedParameter($options['timerange']['end']->getTimeStamp()),
2378
+                    ));
2379
+                }
2380
+            }
2381
+
2382
+            $result = $calendarObjectIdQuery->executeQuery();
2383
+            $matches = [];
2384
+            while (($row = $result->fetch()) !== false) {
2385
+                $matches[] = (int)$row['objectid'];
2386
+            }
2387
+            $result->closeCursor();
2388
+
2389
+            $query = $this->db->getQueryBuilder();
2390
+            $query->select('calendardata', 'uri', 'calendarid', 'calendartype')
2391
+                ->from('calendarobjects')
2392
+                ->where($query->expr()->in('id', $query->createNamedParameter($matches, IQueryBuilder::PARAM_INT_ARRAY)));
2393
+
2394
+            $result = $query->executeQuery();
2395
+            $calendarObjects = [];
2396
+            while (($array = $result->fetch()) !== false) {
2397
+                $array['calendarid'] = (int)$array['calendarid'];
2398
+                $array['calendartype'] = (int)$array['calendartype'];
2399
+                $array['calendardata'] = $this->readBlob($array['calendardata']);
2400
+
2401
+                $calendarObjects[] = $array;
2402
+            }
2403
+            $result->closeCursor();
2404
+            return $calendarObjects;
2405
+        }, $this->db);
2406
+    }
2407
+
2408
+    /**
2409
+     * Searches through all of a users calendars and calendar objects to find
2410
+     * an object with a specific UID.
2411
+     *
2412
+     * This method should return the path to this object, relative to the
2413
+     * calendar home, so this path usually only contains two parts:
2414
+     *
2415
+     * calendarpath/objectpath.ics
2416
+     *
2417
+     * If the uid is not found, return null.
2418
+     *
2419
+     * This method should only consider * objects that the principal owns, so
2420
+     * any calendars owned by other principals that also appear in this
2421
+     * collection should be ignored.
2422
+     *
2423
+     * @param string $principalUri
2424
+     * @param string $uid
2425
+     * @return string|null
2426
+     */
2427
+    public function getCalendarObjectByUID($principalUri, $uid) {
2428
+        $query = $this->db->getQueryBuilder();
2429
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
2430
+            ->from('calendarobjects', 'co')
2431
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
2432
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2433
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
2434
+            ->andWhere($query->expr()->isNull('co.deleted_at'));
2435
+        $stmt = $query->executeQuery();
2436
+        $row = $stmt->fetch();
2437
+        $stmt->closeCursor();
2438
+        if ($row) {
2439
+            return $row['calendaruri'] . '/' . $row['objecturi'];
2440
+        }
2441
+
2442
+        return null;
2443
+    }
2444
+
2445
+    public function getCalendarObjectById(string $principalUri, int $id): ?array {
2446
+        $query = $this->db->getQueryBuilder();
2447
+        $query->select(['co.id', 'co.uri', 'co.lastmodified', 'co.etag', 'co.calendarid', 'co.size', 'co.calendardata', 'co.componenttype', 'co.classification', 'co.deleted_at'])
2448
+            ->selectAlias('c.uri', 'calendaruri')
2449
+            ->from('calendarobjects', 'co')
2450
+            ->join('co', 'calendars', 'c', $query->expr()->eq('c.id', 'co.calendarid', IQueryBuilder::PARAM_INT))
2451
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
2452
+            ->andWhere($query->expr()->eq('co.id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT));
2453
+        $stmt = $query->executeQuery();
2454
+        $row = $stmt->fetch();
2455
+        $stmt->closeCursor();
2456
+
2457
+        if (!$row) {
2458
+            return null;
2459
+        }
2460
+
2461
+        return [
2462
+            'id' => $row['id'],
2463
+            'uri' => $row['uri'],
2464
+            'lastmodified' => $row['lastmodified'],
2465
+            'etag' => '"' . $row['etag'] . '"',
2466
+            'calendarid' => $row['calendarid'],
2467
+            'calendaruri' => $row['calendaruri'],
2468
+            'size' => (int)$row['size'],
2469
+            'calendardata' => $this->readBlob($row['calendardata']),
2470
+            'component' => strtolower($row['componenttype']),
2471
+            'classification' => (int)$row['classification'],
2472
+            'deleted_at' => isset($row['deleted_at']) ? ((int)$row['deleted_at']) : null,
2473
+        ];
2474
+    }
2475
+
2476
+    /**
2477
+     * The getChanges method returns all the changes that have happened, since
2478
+     * the specified syncToken in the specified calendar.
2479
+     *
2480
+     * This function should return an array, such as the following:
2481
+     *
2482
+     * [
2483
+     *   'syncToken' => 'The current synctoken',
2484
+     *   'added'   => [
2485
+     *      'new.txt',
2486
+     *   ],
2487
+     *   'modified'   => [
2488
+     *      'modified.txt',
2489
+     *   ],
2490
+     *   'deleted' => [
2491
+     *      'foo.php.bak',
2492
+     *      'old.txt'
2493
+     *   ]
2494
+     * );
2495
+     *
2496
+     * The returned syncToken property should reflect the *current* syncToken
2497
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
2498
+     * property This is * needed here too, to ensure the operation is atomic.
2499
+     *
2500
+     * If the $syncToken argument is specified as null, this is an initial
2501
+     * sync, and all members should be reported.
2502
+     *
2503
+     * The modified property is an array of nodenames that have changed since
2504
+     * the last token.
2505
+     *
2506
+     * The deleted property is an array with nodenames, that have been deleted
2507
+     * from collection.
2508
+     *
2509
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
2510
+     * 1, you only have to report changes that happened only directly in
2511
+     * immediate descendants. If it's 2, it should also include changes from
2512
+     * the nodes below the child collections. (grandchildren)
2513
+     *
2514
+     * The $limit argument allows a client to specify how many results should
2515
+     * be returned at most. If the limit is not specified, it should be treated
2516
+     * as infinite.
2517
+     *
2518
+     * If the limit (infinite or not) is higher than you're willing to return,
2519
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
2520
+     *
2521
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
2522
+     * return null.
2523
+     *
2524
+     * The limit is 'suggestive'. You are free to ignore it.
2525
+     *
2526
+     * @param string $calendarId
2527
+     * @param string $syncToken
2528
+     * @param int $syncLevel
2529
+     * @param int|null $limit
2530
+     * @param int $calendarType
2531
+     * @return ?array
2532
+     */
2533
+    public function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
2534
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2535
+
2536
+        return $this->atomic(function () use ($calendarId, $syncToken, $syncLevel, $limit, $calendarType, $table) {
2537
+            // Current synctoken
2538
+            $qb = $this->db->getQueryBuilder();
2539
+            $qb->select('synctoken')
2540
+                ->from($table)
2541
+                ->where(
2542
+                    $qb->expr()->eq('id', $qb->createNamedParameter($calendarId))
2543
+                );
2544
+            $stmt = $qb->executeQuery();
2545
+            $currentToken = $stmt->fetchOne();
2546
+            $initialSync = !is_numeric($syncToken);
2547
+
2548
+            if ($currentToken === false) {
2549
+                return null;
2550
+            }
2551
+
2552
+            // evaluate if this is a initial sync and construct appropriate command
2553
+            if ($initialSync) {
2554
+                $qb = $this->db->getQueryBuilder();
2555
+                $qb->select('uri')
2556
+                    ->from('calendarobjects')
2557
+                    ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2558
+                    ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2559
+                    ->andWhere($qb->expr()->isNull('deleted_at'));
2560
+            } else {
2561
+                $qb = $this->db->getQueryBuilder();
2562
+                $qb->select('uri', $qb->func()->max('operation'))
2563
+                    ->from('calendarchanges')
2564
+                    ->where($qb->expr()->eq('calendarid', $qb->createNamedParameter($calendarId)))
2565
+                    ->andWhere($qb->expr()->eq('calendartype', $qb->createNamedParameter($calendarType)))
2566
+                    ->andWhere($qb->expr()->gte('synctoken', $qb->createNamedParameter($syncToken)))
2567
+                    ->andWhere($qb->expr()->lt('synctoken', $qb->createNamedParameter($currentToken)))
2568
+                    ->groupBy('uri');
2569
+            }
2570
+            // evaluate if limit exists
2571
+            if (is_numeric($limit)) {
2572
+                $qb->setMaxResults($limit);
2573
+            }
2574
+            // execute command
2575
+            $stmt = $qb->executeQuery();
2576
+            // build results
2577
+            $result = ['syncToken' => $currentToken, 'added' => [], 'modified' => [], 'deleted' => []];
2578
+            // retrieve results
2579
+            if ($initialSync) {
2580
+                $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
2581
+            } else {
2582
+                // \PDO::FETCH_NUM is needed due to the inconsistent field names
2583
+                // produced by doctrine for MAX() with different databases
2584
+                while ($entry = $stmt->fetch(\PDO::FETCH_NUM)) {
2585
+                    // assign uri (column 0) to appropriate mutation based on operation (column 1)
2586
+                    // forced (int) is needed as doctrine with OCI returns the operation field as string not integer
2587
+                    match ((int)$entry[1]) {
2588
+                        1 => $result['added'][] = $entry[0],
2589
+                        2 => $result['modified'][] = $entry[0],
2590
+                        3 => $result['deleted'][] = $entry[0],
2591
+                        default => $this->logger->debug('Unknown calendar change operation detected')
2592
+                    };
2593
+                }
2594
+            }
2595
+            $stmt->closeCursor();
2596
+
2597
+            return $result;
2598
+        }, $this->db);
2599
+    }
2600
+
2601
+    /**
2602
+     * Returns a list of subscriptions for a principal.
2603
+     *
2604
+     * Every subscription is an array with the following keys:
2605
+     *  * id, a unique id that will be used by other functions to modify the
2606
+     *    subscription. This can be the same as the uri or a database key.
2607
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
2608
+     *  * principaluri. The owner of the subscription. Almost always the same as
2609
+     *    principalUri passed to this method.
2610
+     *
2611
+     * Furthermore, all the subscription info must be returned too:
2612
+     *
2613
+     * 1. {DAV:}displayname
2614
+     * 2. {http://apple.com/ns/ical/}refreshrate
2615
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
2616
+     *    should not be stripped).
2617
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
2618
+     *    should not be stripped).
2619
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
2620
+     *    attachments should not be stripped).
2621
+     * 6. {http://calendarserver.org/ns/}source (Must be a
2622
+     *     Sabre\DAV\Property\Href).
2623
+     * 7. {http://apple.com/ns/ical/}calendar-color
2624
+     * 8. {http://apple.com/ns/ical/}calendar-order
2625
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
2626
+     *    (should just be an instance of
2627
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
2628
+     *    default components).
2629
+     *
2630
+     * @param string $principalUri
2631
+     * @return array
2632
+     */
2633
+    public function getSubscriptionsForUser($principalUri) {
2634
+        $fields = array_column($this->subscriptionPropertyMap, 0);
2635
+        $fields[] = 'id';
2636
+        $fields[] = 'uri';
2637
+        $fields[] = 'source';
2638
+        $fields[] = 'principaluri';
2639
+        $fields[] = 'lastmodified';
2640
+        $fields[] = 'synctoken';
2641
+
2642
+        $query = $this->db->getQueryBuilder();
2643
+        $query->select($fields)
2644
+            ->from('calendarsubscriptions')
2645
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2646
+            ->orderBy('calendarorder', 'asc');
2647
+        $stmt = $query->executeQuery();
2648
+
2649
+        $subscriptions = [];
2650
+        while ($row = $stmt->fetch()) {
2651
+            $subscription = [
2652
+                'id' => $row['id'],
2653
+                'uri' => $row['uri'],
2654
+                'principaluri' => $row['principaluri'],
2655
+                'source' => $row['source'],
2656
+                'lastmodified' => $row['lastmodified'],
2657
+
2658
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
2659
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0',
2660
+            ];
2661
+
2662
+            $subscriptions[] = $this->rowToSubscription($row, $subscription);
2663
+        }
2664
+
2665
+        return $subscriptions;
2666
+    }
2667
+
2668
+    /**
2669
+     * Creates a new subscription for a principal.
2670
+     *
2671
+     * If the creation was a success, an id must be returned that can be used to reference
2672
+     * this subscription in other methods, such as updateSubscription.
2673
+     *
2674
+     * @param string $principalUri
2675
+     * @param string $uri
2676
+     * @param array $properties
2677
+     * @return mixed
2678
+     */
2679
+    public function createSubscription($principalUri, $uri, array $properties) {
2680
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
2681
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
2682
+        }
2683
+
2684
+        $values = [
2685
+            'principaluri' => $principalUri,
2686
+            'uri' => $uri,
2687
+            'source' => $properties['{http://calendarserver.org/ns/}source']->getHref(),
2688
+            'lastmodified' => time(),
2689
+        ];
2690
+
2691
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
2692
+
2693
+        foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
2694
+            if (array_key_exists($xmlName, $properties)) {
2695
+                $values[$dbName] = $properties[$xmlName];
2696
+                if (in_array($dbName, $propertiesBoolean)) {
2697
+                    $values[$dbName] = true;
2698
+                }
2699
+            }
2700
+        }
2701
+
2702
+        [$subscriptionId, $subscriptionRow] = $this->atomic(function () use ($values) {
2703
+            $valuesToInsert = [];
2704
+            $query = $this->db->getQueryBuilder();
2705
+            foreach (array_keys($values) as $name) {
2706
+                $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
2707
+            }
2708
+            $query->insert('calendarsubscriptions')
2709
+                ->values($valuesToInsert)
2710
+                ->executeStatement();
2711
+
2712
+            $subscriptionId = $query->getLastInsertId();
2713
+
2714
+            $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2715
+            return [$subscriptionId, $subscriptionRow];
2716
+        }, $this->db);
2717
+
2718
+        $this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow));
2719
+
2720
+        return $subscriptionId;
2721
+    }
2722
+
2723
+    /**
2724
+     * Updates a subscription
2725
+     *
2726
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
2727
+     * To do the actual updates, you must tell this object which properties
2728
+     * you're going to process with the handle() method.
2729
+     *
2730
+     * Calling the handle method is like telling the PropPatch object "I
2731
+     * promise I can handle updating this property".
2732
+     *
2733
+     * Read the PropPatch documentation for more info and examples.
2734
+     *
2735
+     * @param mixed $subscriptionId
2736
+     * @param PropPatch $propPatch
2737
+     * @return void
2738
+     */
2739
+    public function updateSubscription($subscriptionId, PropPatch $propPatch) {
2740
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
2741
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
2742
+
2743
+        $propPatch->handle($supportedProperties, function ($mutations) use ($subscriptionId) {
2744
+            $newValues = [];
2745
+
2746
+            foreach ($mutations as $propertyName => $propertyValue) {
2747
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
2748
+                    $newValues['source'] = $propertyValue->getHref();
2749
+                } else {
2750
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName][0];
2751
+                    $newValues[$fieldName] = $propertyValue;
2752
+                }
2753
+            }
2754
+
2755
+            $subscriptionRow = $this->atomic(function () use ($subscriptionId, $newValues) {
2756
+                $query = $this->db->getQueryBuilder();
2757
+                $query->update('calendarsubscriptions')
2758
+                    ->set('lastmodified', $query->createNamedParameter(time()));
2759
+                foreach ($newValues as $fieldName => $value) {
2760
+                    $query->set($fieldName, $query->createNamedParameter($value));
2761
+                }
2762
+                $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2763
+                    ->executeStatement();
2764
+
2765
+                return $this->getSubscriptionById($subscriptionId);
2766
+            }, $this->db);
2767
+
2768
+            $this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations));
2769
+
2770
+            return true;
2771
+        });
2772
+    }
2773
+
2774
+    /**
2775
+     * Deletes a subscription.
2776
+     *
2777
+     * @param mixed $subscriptionId
2778
+     * @return void
2779
+     */
2780
+    public function deleteSubscription($subscriptionId) {
2781
+        $this->atomic(function () use ($subscriptionId): void {
2782
+            $subscriptionRow = $this->getSubscriptionById($subscriptionId);
2783
+
2784
+            $query = $this->db->getQueryBuilder();
2785
+            $query->delete('calendarsubscriptions')
2786
+                ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2787
+                ->executeStatement();
2788
+
2789
+            $query = $this->db->getQueryBuilder();
2790
+            $query->delete('calendarobjects')
2791
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2792
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2793
+                ->executeStatement();
2794
+
2795
+            $query->delete('calendarchanges')
2796
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2797
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2798
+                ->executeStatement();
2799
+
2800
+            $query->delete($this->dbObjectPropertiesTable)
2801
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2802
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2803
+                ->executeStatement();
2804
+
2805
+            if ($subscriptionRow) {
2806
+                $this->dispatcher->dispatchTyped(new SubscriptionDeletedEvent((int)$subscriptionId, $subscriptionRow, []));
2807
+            }
2808
+        }, $this->db);
2809
+    }
2810
+
2811
+    /**
2812
+     * Returns a single scheduling object for the inbox collection.
2813
+     *
2814
+     * The returned array should contain the following elements:
2815
+     *   * uri - A unique basename for the object. This will be used to
2816
+     *           construct a full uri.
2817
+     *   * calendardata - The iCalendar object
2818
+     *   * lastmodified - The last modification date. Can be an int for a unix
2819
+     *                    timestamp, or a PHP DateTime object.
2820
+     *   * etag - A unique token that must change if the object changed.
2821
+     *   * size - The size of the object, in bytes.
2822
+     *
2823
+     * @param string $principalUri
2824
+     * @param string $objectUri
2825
+     * @return array
2826
+     */
2827
+    public function getSchedulingObject($principalUri, $objectUri) {
2828
+        $query = $this->db->getQueryBuilder();
2829
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2830
+            ->from('schedulingobjects')
2831
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2832
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2833
+            ->executeQuery();
2834
+
2835
+        $row = $stmt->fetch();
2836
+
2837
+        if (!$row) {
2838
+            return null;
2839
+        }
2840
+
2841
+        return [
2842
+            'uri' => $row['uri'],
2843
+            'calendardata' => $row['calendardata'],
2844
+            'lastmodified' => $row['lastmodified'],
2845
+            'etag' => '"' . $row['etag'] . '"',
2846
+            'size' => (int)$row['size'],
2847
+        ];
2848
+    }
2849
+
2850
+    /**
2851
+     * Returns all scheduling objects for the inbox collection.
2852
+     *
2853
+     * These objects should be returned as an array. Every item in the array
2854
+     * should follow the same structure as returned from getSchedulingObject.
2855
+     *
2856
+     * The main difference is that 'calendardata' is optional.
2857
+     *
2858
+     * @param string $principalUri
2859
+     * @return array
2860
+     */
2861
+    public function getSchedulingObjects($principalUri) {
2862
+        $query = $this->db->getQueryBuilder();
2863
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2864
+            ->from('schedulingobjects')
2865
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2866
+            ->executeQuery();
2867
+
2868
+        $results = [];
2869
+        while (($row = $stmt->fetch()) !== false) {
2870
+            $results[] = [
2871
+                'calendardata' => $row['calendardata'],
2872
+                'uri' => $row['uri'],
2873
+                'lastmodified' => $row['lastmodified'],
2874
+                'etag' => '"' . $row['etag'] . '"',
2875
+                'size' => (int)$row['size'],
2876
+            ];
2877
+        }
2878
+        $stmt->closeCursor();
2879
+
2880
+        return $results;
2881
+    }
2882
+
2883
+    /**
2884
+     * Deletes a scheduling object from the inbox collection.
2885
+     *
2886
+     * @param string $principalUri
2887
+     * @param string $objectUri
2888
+     * @return void
2889
+     */
2890
+    public function deleteSchedulingObject($principalUri, $objectUri) {
2891
+        $this->cachedObjects = [];
2892
+        $query = $this->db->getQueryBuilder();
2893
+        $query->delete('schedulingobjects')
2894
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2895
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2896
+            ->executeStatement();
2897
+    }
2898
+
2899
+    /**
2900
+     * Deletes all scheduling objects last modified before $modifiedBefore from the inbox collection.
2901
+     *
2902
+     * @param int $modifiedBefore
2903
+     * @param int $limit
2904
+     * @return void
2905
+     */
2906
+    public function deleteOutdatedSchedulingObjects(int $modifiedBefore, int $limit): void {
2907
+        $query = $this->db->getQueryBuilder();
2908
+        $query->select('id')
2909
+            ->from('schedulingobjects')
2910
+            ->where($query->expr()->lt('lastmodified', $query->createNamedParameter($modifiedBefore)))
2911
+            ->setMaxResults($limit);
2912
+        $result = $query->executeQuery();
2913
+        $count = $result->rowCount();
2914
+        if ($count === 0) {
2915
+            return;
2916
+        }
2917
+        $ids = array_map(static function (array $id) {
2918
+            return (int)$id[0];
2919
+        }, $result->fetchAll(\PDO::FETCH_NUM));
2920
+        $result->closeCursor();
2921
+
2922
+        $numDeleted = 0;
2923
+        $deleteQuery = $this->db->getQueryBuilder();
2924
+        $deleteQuery->delete('schedulingobjects')
2925
+            ->where($deleteQuery->expr()->in('id', $deleteQuery->createParameter('ids'), IQueryBuilder::PARAM_INT_ARRAY));
2926
+        foreach (array_chunk($ids, 1000) as $chunk) {
2927
+            $deleteQuery->setParameter('ids', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
2928
+            $numDeleted += $deleteQuery->executeStatement();
2929
+        }
2930
+
2931
+        if ($numDeleted === $limit) {
2932
+            $this->logger->info("Deleted $limit scheduling objects, continuing with next batch");
2933
+            $this->deleteOutdatedSchedulingObjects($modifiedBefore, $limit);
2934
+        }
2935
+    }
2936
+
2937
+    /**
2938
+     * Creates a new scheduling object. This should land in a users' inbox.
2939
+     *
2940
+     * @param string $principalUri
2941
+     * @param string $objectUri
2942
+     * @param string $objectData
2943
+     * @return void
2944
+     */
2945
+    public function createSchedulingObject($principalUri, $objectUri, $objectData) {
2946
+        $this->cachedObjects = [];
2947
+        $query = $this->db->getQueryBuilder();
2948
+        $query->insert('schedulingobjects')
2949
+            ->values([
2950
+                'principaluri' => $query->createNamedParameter($principalUri),
2951
+                'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2952
+                'uri' => $query->createNamedParameter($objectUri),
2953
+                'lastmodified' => $query->createNamedParameter(time()),
2954
+                'etag' => $query->createNamedParameter(md5($objectData)),
2955
+                'size' => $query->createNamedParameter(strlen($objectData))
2956
+            ])
2957
+            ->executeStatement();
2958
+    }
2959
+
2960
+    /**
2961
+     * Adds a change record to the calendarchanges table.
2962
+     *
2963
+     * @param mixed $calendarId
2964
+     * @param string[] $objectUris
2965
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2966
+     * @param int $calendarType
2967
+     * @return void
2968
+     */
2969
+    protected function addChanges(int $calendarId, array $objectUris, int $operation, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
2970
+        $this->cachedObjects = [];
2971
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2972
+
2973
+        $this->atomic(function () use ($calendarId, $objectUris, $operation, $calendarType, $table): void {
2974
+            $query = $this->db->getQueryBuilder();
2975
+            $query->select('synctoken')
2976
+                ->from($table)
2977
+                ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2978
+            $result = $query->executeQuery();
2979
+            $syncToken = (int)$result->fetchOne();
2980
+            $result->closeCursor();
2981
+
2982
+            $query = $this->db->getQueryBuilder();
2983
+            $query->insert('calendarchanges')
2984
+                ->values([
2985
+                    'uri' => $query->createParameter('uri'),
2986
+                    'synctoken' => $query->createNamedParameter($syncToken),
2987
+                    'calendarid' => $query->createNamedParameter($calendarId),
2988
+                    'operation' => $query->createNamedParameter($operation),
2989
+                    'calendartype' => $query->createNamedParameter($calendarType),
2990
+                    'created_at' => $query->createNamedParameter(time()),
2991
+                ]);
2992
+            foreach ($objectUris as $uri) {
2993
+                $query->setParameter('uri', $uri);
2994
+                $query->executeStatement();
2995
+            }
2996
+
2997
+            $query = $this->db->getQueryBuilder();
2998
+            $query->update($table)
2999
+                ->set('synctoken', $query->createNamedParameter($syncToken + 1, IQueryBuilder::PARAM_INT))
3000
+                ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)))
3001
+                ->executeStatement();
3002
+        }, $this->db);
3003
+    }
3004
+
3005
+    public function restoreChanges(int $calendarId, int $calendarType = self::CALENDAR_TYPE_CALENDAR): void {
3006
+        $this->cachedObjects = [];
3007
+
3008
+        $this->atomic(function () use ($calendarId, $calendarType): void {
3009
+            $qbAdded = $this->db->getQueryBuilder();
3010
+            $qbAdded->select('uri')
3011
+                ->from('calendarobjects')
3012
+                ->where(
3013
+                    $qbAdded->expr()->andX(
3014
+                        $qbAdded->expr()->eq('calendarid', $qbAdded->createNamedParameter($calendarId)),
3015
+                        $qbAdded->expr()->eq('calendartype', $qbAdded->createNamedParameter($calendarType)),
3016
+                        $qbAdded->expr()->isNull('deleted_at'),
3017
+                    )
3018
+                );
3019
+            $resultAdded = $qbAdded->executeQuery();
3020
+            $addedUris = $resultAdded->fetchAll(\PDO::FETCH_COLUMN);
3021
+            $resultAdded->closeCursor();
3022
+            // Track everything as changed
3023
+            // Tracking the creation is not necessary because \OCA\DAV\CalDAV\CalDavBackend::getChangesForCalendar
3024
+            // only returns the last change per object.
3025
+            $this->addChanges($calendarId, $addedUris, 2, $calendarType);
3026
+
3027
+            $qbDeleted = $this->db->getQueryBuilder();
3028
+            $qbDeleted->select('uri')
3029
+                ->from('calendarobjects')
3030
+                ->where(
3031
+                    $qbDeleted->expr()->andX(
3032
+                        $qbDeleted->expr()->eq('calendarid', $qbDeleted->createNamedParameter($calendarId)),
3033
+                        $qbDeleted->expr()->eq('calendartype', $qbDeleted->createNamedParameter($calendarType)),
3034
+                        $qbDeleted->expr()->isNotNull('deleted_at'),
3035
+                    )
3036
+                );
3037
+            $resultDeleted = $qbDeleted->executeQuery();
3038
+            $deletedUris = array_map(function (string $uri) {
3039
+                return str_replace('-deleted.ics', '.ics', $uri);
3040
+            }, $resultDeleted->fetchAll(\PDO::FETCH_COLUMN));
3041
+            $resultDeleted->closeCursor();
3042
+            $this->addChanges($calendarId, $deletedUris, 3, $calendarType);
3043
+        }, $this->db);
3044
+    }
3045
+
3046
+    /**
3047
+     * Parses some information from calendar objects, used for optimized
3048
+     * calendar-queries.
3049
+     *
3050
+     * Returns an array with the following keys:
3051
+     *   * etag - An md5 checksum of the object without the quotes.
3052
+     *   * size - Size of the object in bytes
3053
+     *   * componentType - VEVENT, VTODO or VJOURNAL
3054
+     *   * firstOccurence
3055
+     *   * lastOccurence
3056
+     *   * uid - value of the UID property
3057
+     *
3058
+     * @param string $calendarData
3059
+     * @return array
3060
+     */
3061
+    public function getDenormalizedData(string $calendarData): array {
3062
+        $vObject = Reader::read($calendarData);
3063
+        $vEvents = [];
3064
+        $componentType = null;
3065
+        $component = null;
3066
+        $firstOccurrence = null;
3067
+        $lastOccurrence = null;
3068
+        $uid = null;
3069
+        $classification = self::CLASSIFICATION_PUBLIC;
3070
+        $hasDTSTART = false;
3071
+        foreach ($vObject->getComponents() as $component) {
3072
+            if ($component->name !== 'VTIMEZONE') {
3073
+                // Finding all VEVENTs, and track them
3074
+                if ($component->name === 'VEVENT') {
3075
+                    $vEvents[] = $component;
3076
+                    if ($component->DTSTART) {
3077
+                        $hasDTSTART = true;
3078
+                    }
3079
+                }
3080
+                // Track first component type and uid
3081
+                if ($uid === null) {
3082
+                    $componentType = $component->name;
3083
+                    $uid = (string)$component->UID;
3084
+                }
3085
+            }
3086
+        }
3087
+        if (!$componentType) {
3088
+            throw new BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
3089
+        }
3090
+
3091
+        if ($hasDTSTART) {
3092
+            $component = $vEvents[0];
3093
+
3094
+            // Finding the last occurrence is a bit harder
3095
+            if (!isset($component->RRULE) && count($vEvents) === 1) {
3096
+                $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
3097
+                if (isset($component->DTEND)) {
3098
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
3099
+                } elseif (isset($component->DURATION)) {
3100
+                    $endDate = clone $component->DTSTART->getDateTime();
3101
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
3102
+                    $lastOccurrence = $endDate->getTimeStamp();
3103
+                } elseif (!$component->DTSTART->hasTime()) {
3104
+                    $endDate = clone $component->DTSTART->getDateTime();
3105
+                    $endDate->modify('+1 day');
3106
+                    $lastOccurrence = $endDate->getTimeStamp();
3107
+                } else {
3108
+                    $lastOccurrence = $firstOccurrence;
3109
+                }
3110
+            } else {
3111
+                try {
3112
+                    $it = new EventIterator($vEvents);
3113
+                } catch (NoInstancesException $e) {
3114
+                    $this->logger->debug('Caught no instance exception for calendar data. This usually indicates invalid calendar data.', [
3115
+                        'app' => 'dav',
3116
+                        'exception' => $e,
3117
+                    ]);
3118
+                    throw new Forbidden($e->getMessage());
3119
+                }
3120
+                $maxDate = new DateTime(self::MAX_DATE);
3121
+                $firstOccurrence = $it->getDtStart()->getTimestamp();
3122
+                if ($it->isInfinite()) {
3123
+                    $lastOccurrence = $maxDate->getTimestamp();
3124
+                } else {
3125
+                    $end = $it->getDtEnd();
3126
+                    while ($it->valid() && $end < $maxDate) {
3127
+                        $end = $it->getDtEnd();
3128
+                        $it->next();
3129
+                    }
3130
+                    $lastOccurrence = $end->getTimestamp();
3131
+                }
3132
+            }
3133
+        }
3134
+
3135
+        if ($component->CLASS) {
3136
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
3137
+            switch ($component->CLASS->getValue()) {
3138
+                case 'PUBLIC':
3139
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
3140
+                    break;
3141
+                case 'CONFIDENTIAL':
3142
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
3143
+                    break;
3144
+            }
3145
+        }
3146
+        return [
3147
+            'etag' => md5($calendarData),
3148
+            'size' => strlen($calendarData),
3149
+            'componentType' => $componentType,
3150
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
3151
+            'lastOccurence' => is_null($lastOccurrence) ? null : max(0, $lastOccurrence),
3152
+            'uid' => $uid,
3153
+            'classification' => $classification
3154
+        ];
3155
+    }
3156
+
3157
+    /**
3158
+     * @param $cardData
3159
+     * @return bool|string
3160
+     */
3161
+    private function readBlob($cardData) {
3162
+        if (is_resource($cardData)) {
3163
+            return stream_get_contents($cardData);
3164
+        }
3165
+
3166
+        return $cardData;
3167
+    }
3168
+
3169
+    /**
3170
+     * @param list<array{href: string, commonName: string, readOnly: bool}> $add
3171
+     * @param list<string> $remove
3172
+     */
3173
+    public function updateShares(IShareable $shareable, array $add, array $remove): void {
3174
+        $this->atomic(function () use ($shareable, $add, $remove): void {
3175
+            $calendarId = $shareable->getResourceId();
3176
+            $calendarRow = $this->getCalendarById($calendarId);
3177
+            if ($calendarRow === null) {
3178
+                throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $calendarId);
3179
+            }
3180
+            $oldShares = $this->getShares($calendarId);
3181
+
3182
+            $this->calendarSharingBackend->updateShares($shareable, $add, $remove, $oldShares);
3183
+
3184
+            $this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent($calendarId, $calendarRow, $oldShares, $add, $remove));
3185
+        }, $this->db);
3186
+    }
3187
+
3188
+    /**
3189
+     * @return list<array{href: string, commonName: string, status: int, readOnly: bool, '{http://owncloud.org/ns}principal': string, '{http://owncloud.org/ns}group-share': bool}>
3190
+     */
3191
+    public function getShares(int $resourceId): array {
3192
+        return $this->calendarSharingBackend->getShares($resourceId);
3193
+    }
3194
+
3195
+    public function preloadShares(array $resourceIds): void {
3196
+        $this->calendarSharingBackend->preloadShares($resourceIds);
3197
+    }
3198
+
3199
+    /**
3200
+     * @param boolean $value
3201
+     * @param Calendar $calendar
3202
+     * @return string|null
3203
+     */
3204
+    public function setPublishStatus($value, $calendar) {
3205
+        return $this->atomic(function () use ($value, $calendar) {
3206
+            $calendarId = $calendar->getResourceId();
3207
+            $calendarData = $this->getCalendarById($calendarId);
3208
+
3209
+            $query = $this->db->getQueryBuilder();
3210
+            if ($value) {
3211
+                $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
3212
+                $query->insert('dav_shares')
3213
+                    ->values([
3214
+                        'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
3215
+                        'type' => $query->createNamedParameter('calendar'),
3216
+                        'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
3217
+                        'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
3218
+                        'publicuri' => $query->createNamedParameter($publicUri)
3219
+                    ]);
3220
+                $query->executeStatement();
3221
+
3222
+                $this->dispatcher->dispatchTyped(new CalendarPublishedEvent($calendarId, $calendarData, $publicUri));
3223
+                return $publicUri;
3224
+            }
3225
+            $query->delete('dav_shares')
3226
+                ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3227
+                ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
3228
+            $query->executeStatement();
3229
+
3230
+            $this->dispatcher->dispatchTyped(new CalendarUnpublishedEvent($calendarId, $calendarData));
3231
+            return null;
3232
+        }, $this->db);
3233
+    }
3234
+
3235
+    /**
3236
+     * @param Calendar $calendar
3237
+     * @return mixed
3238
+     */
3239
+    public function getPublishStatus($calendar) {
3240
+        $query = $this->db->getQueryBuilder();
3241
+        $result = $query->select('publicuri')
3242
+            ->from('dav_shares')
3243
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
3244
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
3245
+            ->executeQuery();
3246
+
3247
+        $row = $result->fetch();
3248
+        $result->closeCursor();
3249
+        return $row ? reset($row) : false;
3250
+    }
3251
+
3252
+    /**
3253
+     * @param int $resourceId
3254
+     * @param list<array{privilege: string, principal: string, protected: bool}> $acl
3255
+     * @return list<array{privilege: string, principal: string, protected: bool}>
3256
+     */
3257
+    public function applyShareAcl(int $resourceId, array $acl): array {
3258
+        $shares = $this->calendarSharingBackend->getShares($resourceId);
3259
+        return $this->calendarSharingBackend->applyShareAcl($shares, $acl);
3260
+    }
3261
+
3262
+    /**
3263
+     * update properties table
3264
+     *
3265
+     * @param int $calendarId
3266
+     * @param string $objectUri
3267
+     * @param string $calendarData
3268
+     * @param int $calendarType
3269
+     */
3270
+    public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) {
3271
+        $this->cachedObjects = [];
3272
+        $this->atomic(function () use ($calendarId, $objectUri, $calendarData, $calendarType): void {
3273
+            $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
3274
+
3275
+            try {
3276
+                $vCalendar = $this->readCalendarData($calendarData);
3277
+            } catch (\Exception $ex) {
3278
+                return;
3279
+            }
3280
+
3281
+            $this->purgeProperties($calendarId, $objectId);
3282
+
3283
+            $query = $this->db->getQueryBuilder();
3284
+            $query->insert($this->dbObjectPropertiesTable)
3285
+                ->values(
3286
+                    [
3287
+                        'calendarid' => $query->createNamedParameter($calendarId),
3288
+                        'calendartype' => $query->createNamedParameter($calendarType),
3289
+                        'objectid' => $query->createNamedParameter($objectId),
3290
+                        'name' => $query->createParameter('name'),
3291
+                        'parameter' => $query->createParameter('parameter'),
3292
+                        'value' => $query->createParameter('value'),
3293
+                    ]
3294
+                );
3295
+
3296
+            $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
3297
+            foreach ($vCalendar->getComponents() as $component) {
3298
+                if (!in_array($component->name, $indexComponents)) {
3299
+                    continue;
3300
+                }
3301
+
3302
+                foreach ($component->children() as $property) {
3303
+                    if (in_array($property->name, self::INDEXED_PROPERTIES, true)) {
3304
+                        $value = $property->getValue();
3305
+                        // is this a shitty db?
3306
+                        if (!$this->db->supports4ByteText()) {
3307
+                            $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3308
+                        }
3309
+                        $value = mb_strcut($value, 0, 254);
3310
+
3311
+                        $query->setParameter('name', $property->name);
3312
+                        $query->setParameter('parameter', null);
3313
+                        $query->setParameter('value', mb_strcut($value, 0, 254));
3314
+                        $query->executeStatement();
3315
+                    }
3316
+
3317
+                    if (array_key_exists($property->name, self::$indexParameters)) {
3318
+                        $parameters = $property->parameters();
3319
+                        $indexedParametersForProperty = self::$indexParameters[$property->name];
3320
+
3321
+                        foreach ($parameters as $key => $value) {
3322
+                            if (in_array($key, $indexedParametersForProperty)) {
3323
+                                // is this a shitty db?
3324
+                                if ($this->db->supports4ByteText()) {
3325
+                                    $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
3326
+                                }
3327
+
3328
+                                $query->setParameter('name', $property->name);
3329
+                                $query->setParameter('parameter', mb_strcut($key, 0, 254));
3330
+                                $query->setParameter('value', mb_strcut($value, 0, 254));
3331
+                                $query->executeStatement();
3332
+                            }
3333
+                        }
3334
+                    }
3335
+                }
3336
+            }
3337
+        }, $this->db);
3338
+    }
3339
+
3340
+    /**
3341
+     * deletes all birthday calendars
3342
+     */
3343
+    public function deleteAllBirthdayCalendars() {
3344
+        $this->atomic(function (): void {
3345
+            $query = $this->db->getQueryBuilder();
3346
+            $result = $query->select(['id'])->from('calendars')
3347
+                ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
3348
+                ->executeQuery();
3349
+
3350
+            while (($row = $result->fetch()) !== false) {
3351
+                $this->deleteCalendar(
3352
+                    $row['id'],
3353
+                    true // No data to keep in the trashbin, if the user re-enables then we regenerate
3354
+                );
3355
+            }
3356
+            $result->closeCursor();
3357
+        }, $this->db);
3358
+    }
3359
+
3360
+    /**
3361
+     * @param $subscriptionId
3362
+     */
3363
+    public function purgeAllCachedEventsForSubscription($subscriptionId) {
3364
+        $this->atomic(function () use ($subscriptionId): void {
3365
+            $query = $this->db->getQueryBuilder();
3366
+            $query->select('uri')
3367
+                ->from('calendarobjects')
3368
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3369
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
3370
+            $stmt = $query->executeQuery();
3371
+
3372
+            $uris = [];
3373
+            while (($row = $stmt->fetch()) !== false) {
3374
+                $uris[] = $row['uri'];
3375
+            }
3376
+            $stmt->closeCursor();
3377
+
3378
+            $query = $this->db->getQueryBuilder();
3379
+            $query->delete('calendarobjects')
3380
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3381
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3382
+                ->executeStatement();
3383
+
3384
+            $query = $this->db->getQueryBuilder();
3385
+            $query->delete('calendarchanges')
3386
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3387
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3388
+                ->executeStatement();
3389
+
3390
+            $query = $this->db->getQueryBuilder();
3391
+            $query->delete($this->dbObjectPropertiesTable)
3392
+                ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3393
+                ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3394
+                ->executeStatement();
3395
+
3396
+            $this->addChanges($subscriptionId, $uris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3397
+        }, $this->db);
3398
+    }
3399
+
3400
+    /**
3401
+     * @param int $subscriptionId
3402
+     * @param array<int> $calendarObjectIds
3403
+     * @param array<string> $calendarObjectUris
3404
+     */
3405
+    public function purgeCachedEventsForSubscription(int $subscriptionId, array $calendarObjectIds, array $calendarObjectUris): void {
3406
+        if (empty($calendarObjectUris)) {
3407
+            return;
3408
+        }
3409
+
3410
+        $this->atomic(function () use ($subscriptionId, $calendarObjectIds, $calendarObjectUris): void {
3411
+            foreach (array_chunk($calendarObjectIds, 1000) as $chunk) {
3412
+                $query = $this->db->getQueryBuilder();
3413
+                $query->delete($this->dbObjectPropertiesTable)
3414
+                    ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3415
+                    ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3416
+                    ->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3417
+                    ->executeStatement();
3418
+
3419
+                $query = $this->db->getQueryBuilder();
3420
+                $query->delete('calendarobjects')
3421
+                    ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3422
+                    ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3423
+                    ->andWhere($query->expr()->in('id', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY), IQueryBuilder::PARAM_INT_ARRAY))
3424
+                    ->executeStatement();
3425
+            }
3426
+
3427
+            foreach (array_chunk($calendarObjectUris, 1000) as $chunk) {
3428
+                $query = $this->db->getQueryBuilder();
3429
+                $query->delete('calendarchanges')
3430
+                    ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
3431
+                    ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
3432
+                    ->andWhere($query->expr()->in('uri', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY), IQueryBuilder::PARAM_STR_ARRAY))
3433
+                    ->executeStatement();
3434
+            }
3435
+            $this->addChanges($subscriptionId, $calendarObjectUris, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
3436
+        }, $this->db);
3437
+    }
3438
+
3439
+    /**
3440
+     * Move a calendar from one user to another
3441
+     *
3442
+     * @param string $uriName
3443
+     * @param string $uriOrigin
3444
+     * @param string $uriDestination
3445
+     * @param string $newUriName (optional) the new uriName
3446
+     */
3447
+    public function moveCalendar($uriName, $uriOrigin, $uriDestination, $newUriName = null) {
3448
+        $query = $this->db->getQueryBuilder();
3449
+        $query->update('calendars')
3450
+            ->set('principaluri', $query->createNamedParameter($uriDestination))
3451
+            ->set('uri', $query->createNamedParameter($newUriName ?: $uriName))
3452
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($uriOrigin)))
3453
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($uriName)))
3454
+            ->executeStatement();
3455
+    }
3456
+
3457
+    /**
3458
+     * read VCalendar data into a VCalendar object
3459
+     *
3460
+     * @param string $objectData
3461
+     * @return VCalendar
3462
+     */
3463
+    protected function readCalendarData($objectData) {
3464
+        return Reader::read($objectData);
3465
+    }
3466
+
3467
+    /**
3468
+     * delete all properties from a given calendar object
3469
+     *
3470
+     * @param int $calendarId
3471
+     * @param int $objectId
3472
+     */
3473
+    protected function purgeProperties($calendarId, $objectId) {
3474
+        $this->cachedObjects = [];
3475
+        $query = $this->db->getQueryBuilder();
3476
+        $query->delete($this->dbObjectPropertiesTable)
3477
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
3478
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
3479
+        $query->executeStatement();
3480
+    }
3481
+
3482
+    /**
3483
+     * get ID from a given calendar object
3484
+     *
3485
+     * @param int $calendarId
3486
+     * @param string $uri
3487
+     * @param int $calendarType
3488
+     * @return int
3489
+     */
3490
+    protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
3491
+        $query = $this->db->getQueryBuilder();
3492
+        $query->select('id')
3493
+            ->from('calendarobjects')
3494
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
3495
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
3496
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
3497
+
3498
+        $result = $query->executeQuery();
3499
+        $objectIds = $result->fetch();
3500
+        $result->closeCursor();
3501
+
3502
+        if (!isset($objectIds['id'])) {
3503
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
3504
+        }
3505
+
3506
+        return (int)$objectIds['id'];
3507
+    }
3508
+
3509
+    /**
3510
+     * @throws \InvalidArgumentException
3511
+     */
3512
+    public function pruneOutdatedSyncTokens(int $keep, int $retention): int {
3513
+        if ($keep < 0) {
3514
+            throw new \InvalidArgumentException();
3515
+        }
3516
+
3517
+        $query = $this->db->getQueryBuilder();
3518
+        $query->select($query->func()->max('id'))
3519
+            ->from('calendarchanges');
3520
+
3521
+        $result = $query->executeQuery();
3522
+        $maxId = (int)$result->fetchOne();
3523
+        $result->closeCursor();
3524
+        if (!$maxId || $maxId < $keep) {
3525
+            return 0;
3526
+        }
3527
+
3528
+        $query = $this->db->getQueryBuilder();
3529
+        $query->delete('calendarchanges')
3530
+            ->where(
3531
+                $query->expr()->lte('id', $query->createNamedParameter($maxId - $keep, IQueryBuilder::PARAM_INT), IQueryBuilder::PARAM_INT),
3532
+                $query->expr()->lte('created_at', $query->createNamedParameter($retention)),
3533
+            );
3534
+        return $query->executeStatement();
3535
+    }
3536
+
3537
+    /**
3538
+     * return legacy endpoint principal name to new principal name
3539
+     *
3540
+     * @param $principalUri
3541
+     * @param $toV2
3542
+     * @return string
3543
+     */
3544
+    private function convertPrincipal($principalUri, $toV2) {
3545
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
3546
+            [, $name] = Uri\split($principalUri);
3547
+            if ($toV2 === true) {
3548
+                return "principals/users/$name";
3549
+            }
3550
+            return "principals/$name";
3551
+        }
3552
+        return $principalUri;
3553
+    }
3554
+
3555
+    /**
3556
+     * adds information about an owner to the calendar data
3557
+     *
3558
+     */
3559
+    private function addOwnerPrincipalToCalendar(array $calendarInfo): array {
3560
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
3561
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
3562
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
3563
+            $uri = $calendarInfo[$ownerPrincipalKey];
3564
+        } else {
3565
+            $uri = $calendarInfo['principaluri'];
3566
+        }
3567
+
3568
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
3569
+        if (isset($principalInformation['{DAV:}displayname'])) {
3570
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
3571
+        }
3572
+        return $calendarInfo;
3573
+    }
3574
+
3575
+    private function addResourceTypeToCalendar(array $row, array $calendar): array {
3576
+        if (isset($row['deleted_at'])) {
3577
+            // Columns is set and not null -> this is a deleted calendar
3578
+            // we send a custom resourcetype to hide the deleted calendar
3579
+            // from ordinary DAV clients, but the Calendar app will know
3580
+            // how to handle this special resource.
3581
+            $calendar['{DAV:}resourcetype'] = new DAV\Xml\Property\ResourceType([
3582
+                '{DAV:}collection',
3583
+                sprintf('{%s}deleted-calendar', \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD),
3584
+            ]);
3585
+        }
3586
+        return $calendar;
3587
+    }
3588
+
3589
+    /**
3590
+     * Amend the calendar info with database row data
3591
+     *
3592
+     * @param array $row
3593
+     * @param array $calendar
3594
+     *
3595
+     * @return array
3596
+     */
3597
+    private function rowToCalendar($row, array $calendar): array {
3598
+        foreach ($this->propertyMap as $xmlName => [$dbName, $type]) {
3599
+            $value = $row[$dbName];
3600
+            if ($value !== null) {
3601
+                settype($value, $type);
3602
+            }
3603
+            $calendar[$xmlName] = $value;
3604
+        }
3605
+        return $calendar;
3606
+    }
3607
+
3608
+    /**
3609
+     * Amend the subscription info with database row data
3610
+     *
3611
+     * @param array $row
3612
+     * @param array $subscription
3613
+     *
3614
+     * @return array
3615
+     */
3616
+    private function rowToSubscription($row, array $subscription): array {
3617
+        foreach ($this->subscriptionPropertyMap as $xmlName => [$dbName, $type]) {
3618
+            $value = $row[$dbName];
3619
+            if ($value !== null) {
3620
+                settype($value, $type);
3621
+            }
3622
+            $subscription[$xmlName] = $value;
3623
+        }
3624
+        return $subscription;
3625
+    }
3626
+
3627
+    /**
3628
+     * delete all invitations from a given calendar
3629
+     *
3630
+     * @since 31.0.0
3631
+     *
3632
+     * @param int $calendarId
3633
+     *
3634
+     * @return void
3635
+     */
3636
+    protected function purgeCalendarInvitations(int $calendarId): void {
3637
+        // select all calendar object uid's
3638
+        $cmd = $this->db->getQueryBuilder();
3639
+        $cmd->select('uid')
3640
+            ->from($this->dbObjectsTable)
3641
+            ->where($cmd->expr()->eq('calendarid', $cmd->createNamedParameter($calendarId)));
3642
+        $allIds = $cmd->executeQuery()->fetchAll(\PDO::FETCH_COLUMN);
3643
+        // delete all links that match object uid's
3644
+        $cmd = $this->db->getQueryBuilder();
3645
+        $cmd->delete($this->dbObjectInvitationsTable)
3646
+            ->where($cmd->expr()->in('uid', $cmd->createParameter('uids'), IQueryBuilder::PARAM_STR_ARRAY));
3647
+        foreach (array_chunk($allIds, 1000) as $chunkIds) {
3648
+            $cmd->setParameter('uids', $chunkIds, IQueryBuilder::PARAM_STR_ARRAY);
3649
+            $cmd->executeStatement();
3650
+        }
3651
+    }
3652
+
3653
+    /**
3654
+     * Delete all invitations from a given calendar event
3655
+     *
3656
+     * @since 31.0.0
3657
+     *
3658
+     * @param string $eventId UID of the event
3659
+     *
3660
+     * @return void
3661
+     */
3662
+    protected function purgeObjectInvitations(string $eventId): void {
3663
+        $cmd = $this->db->getQueryBuilder();
3664
+        $cmd->delete($this->dbObjectInvitationsTable)
3665
+            ->where($cmd->expr()->eq('uid', $cmd->createNamedParameter($eventId, IQueryBuilder::PARAM_STR), IQueryBuilder::PARAM_STR));
3666
+        $cmd->executeStatement();
3667
+    }
3668
+
3669
+    public function unshare(IShareable $shareable, string $principal): void {
3670
+        $this->atomic(function () use ($shareable, $principal): void {
3671
+            $calendarData = $this->getCalendarById($shareable->getResourceId());
3672
+            if ($calendarData === null) {
3673
+                throw new \RuntimeException('Trying to update shares for non-existing calendar: ' . $shareable->getResourceId());
3674
+            }
3675
+
3676
+            $oldShares = $this->getShares($shareable->getResourceId());
3677
+            $unshare = $this->calendarSharingBackend->unshare($shareable, $principal);
3678
+
3679
+            if ($unshare) {
3680
+                $this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent(
3681
+                    $shareable->getResourceId(),
3682
+                    $calendarData,
3683
+                    $oldShares,
3684
+                    [],
3685
+                    [$principal]
3686
+                ));
3687
+            }
3688
+        }, $this->db);
3689
+    }
3690 3690
 }
Please login to merge, or discard this patch.