Passed
Push — master ( 9e1ec0...fd8eec )
by Morris
10:54
created
lib/private/Comments/Manager.php 2 patches
Indentation   +1013 added lines, -1013 removed lines patch added patch discarded remove patch
@@ -41,1017 +41,1017 @@
 block discarded – undo
41 41
 
42 42
 class Manager implements ICommentsManager {
43 43
 
44
-	/** @var  IDBConnection */
45
-	protected $dbConn;
46
-
47
-	/** @var  ILogger */
48
-	protected $logger;
49
-
50
-	/** @var IConfig */
51
-	protected $config;
52
-
53
-	/** @var IComment[] */
54
-	protected $commentsCache = [];
55
-
56
-	/** @var  \Closure[] */
57
-	protected $eventHandlerClosures = [];
58
-
59
-	/** @var  ICommentsEventHandler[] */
60
-	protected $eventHandlers = [];
61
-
62
-	/** @var \Closure[] */
63
-	protected $displayNameResolvers = [];
64
-
65
-	/**
66
-	 * Manager constructor.
67
-	 *
68
-	 * @param IDBConnection $dbConn
69
-	 * @param ILogger $logger
70
-	 * @param IConfig $config
71
-	 */
72
-	public function __construct(
73
-		IDBConnection $dbConn,
74
-		ILogger $logger,
75
-		IConfig $config
76
-	) {
77
-		$this->dbConn = $dbConn;
78
-		$this->logger = $logger;
79
-		$this->config = $config;
80
-	}
81
-
82
-	/**
83
-	 * converts data base data into PHP native, proper types as defined by
84
-	 * IComment interface.
85
-	 *
86
-	 * @param array $data
87
-	 * @return array
88
-	 */
89
-	protected function normalizeDatabaseData(array $data) {
90
-		$data['id'] = (string)$data['id'];
91
-		$data['parent_id'] = (string)$data['parent_id'];
92
-		$data['topmost_parent_id'] = (string)$data['topmost_parent_id'];
93
-		$data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
94
-		if (!is_null($data['latest_child_timestamp'])) {
95
-			$data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
96
-		}
97
-		$data['children_count'] = (int)$data['children_count'];
98
-		return $data;
99
-	}
100
-
101
-	/**
102
-	 * prepares a comment for an insert or update operation after making sure
103
-	 * all necessary fields have a value assigned.
104
-	 *
105
-	 * @param IComment $comment
106
-	 * @return IComment returns the same updated IComment instance as provided
107
-	 *                  by parameter for convenience
108
-	 * @throws \UnexpectedValueException
109
-	 */
110
-	protected function prepareCommentForDatabaseWrite(IComment $comment) {
111
-		if (!$comment->getActorType()
112
-			|| !$comment->getActorId()
113
-			|| !$comment->getObjectType()
114
-			|| !$comment->getObjectId()
115
-			|| !$comment->getVerb()
116
-		) {
117
-			throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
118
-		}
119
-
120
-		if ($comment->getId() === '') {
121
-			$comment->setChildrenCount(0);
122
-			$comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
123
-			$comment->setLatestChildDateTime(null);
124
-		}
125
-
126
-		if (is_null($comment->getCreationDateTime())) {
127
-			$comment->setCreationDateTime(new \DateTime());
128
-		}
129
-
130
-		if ($comment->getParentId() !== '0') {
131
-			$comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
132
-		} else {
133
-			$comment->setTopmostParentId('0');
134
-		}
135
-
136
-		$this->cache($comment);
137
-
138
-		return $comment;
139
-	}
140
-
141
-	/**
142
-	 * returns the topmost parent id of a given comment identified by ID
143
-	 *
144
-	 * @param string $id
145
-	 * @return string
146
-	 * @throws NotFoundException
147
-	 */
148
-	protected function determineTopmostParentId($id) {
149
-		$comment = $this->get($id);
150
-		if ($comment->getParentId() === '0') {
151
-			return $comment->getId();
152
-		} else {
153
-			return $this->determineTopmostParentId($comment->getId());
154
-		}
155
-	}
156
-
157
-	/**
158
-	 * updates child information of a comment
159
-	 *
160
-	 * @param string $id
161
-	 * @param \DateTime $cDateTime the date time of the most recent child
162
-	 * @throws NotFoundException
163
-	 */
164
-	protected function updateChildrenInformation($id, \DateTime $cDateTime) {
165
-		$qb = $this->dbConn->getQueryBuilder();
166
-		$query = $qb->select($qb->func()->count('id'))
167
-			->from('comments')
168
-			->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
169
-			->setParameter('id', $id);
170
-
171
-		$resultStatement = $query->execute();
172
-		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
173
-		$resultStatement->closeCursor();
174
-		$children = (int)$data[0];
175
-
176
-		$comment = $this->get($id);
177
-		$comment->setChildrenCount($children);
178
-		$comment->setLatestChildDateTime($cDateTime);
179
-		$this->save($comment);
180
-	}
181
-
182
-	/**
183
-	 * Tests whether actor or object type and id parameters are acceptable.
184
-	 * Throws exception if not.
185
-	 *
186
-	 * @param string $role
187
-	 * @param string $type
188
-	 * @param string $id
189
-	 * @throws \InvalidArgumentException
190
-	 */
191
-	protected function checkRoleParameters($role, $type, $id) {
192
-		if (
193
-			!is_string($type) || empty($type)
194
-			|| !is_string($id) || empty($id)
195
-		) {
196
-			throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
197
-		}
198
-	}
199
-
200
-	/**
201
-	 * run-time caches a comment
202
-	 *
203
-	 * @param IComment $comment
204
-	 */
205
-	protected function cache(IComment $comment) {
206
-		$id = $comment->getId();
207
-		if (empty($id)) {
208
-			return;
209
-		}
210
-		$this->commentsCache[(string)$id] = $comment;
211
-	}
212
-
213
-	/**
214
-	 * removes an entry from the comments run time cache
215
-	 *
216
-	 * @param mixed $id the comment's id
217
-	 */
218
-	protected function uncache($id) {
219
-		$id = (string)$id;
220
-		if (isset($this->commentsCache[$id])) {
221
-			unset($this->commentsCache[$id]);
222
-		}
223
-	}
224
-
225
-	/**
226
-	 * returns a comment instance
227
-	 *
228
-	 * @param string $id the ID of the comment
229
-	 * @return IComment
230
-	 * @throws NotFoundException
231
-	 * @throws \InvalidArgumentException
232
-	 * @since 9.0.0
233
-	 */
234
-	public function get($id) {
235
-		if ((int)$id === 0) {
236
-			throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
237
-		}
238
-
239
-		if (isset($this->commentsCache[$id])) {
240
-			return $this->commentsCache[$id];
241
-		}
242
-
243
-		$qb = $this->dbConn->getQueryBuilder();
244
-		$resultStatement = $qb->select('*')
245
-			->from('comments')
246
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
247
-			->setParameter('id', $id, IQueryBuilder::PARAM_INT)
248
-			->execute();
249
-
250
-		$data = $resultStatement->fetch();
251
-		$resultStatement->closeCursor();
252
-		if (!$data) {
253
-			throw new NotFoundException();
254
-		}
255
-
256
-		$comment = new Comment($this->normalizeDatabaseData($data));
257
-		$this->cache($comment);
258
-		return $comment;
259
-	}
260
-
261
-	/**
262
-	 * returns the comment specified by the id and all it's child comments.
263
-	 * At this point of time, we do only support one level depth.
264
-	 *
265
-	 * @param string $id
266
-	 * @param int $limit max number of entries to return, 0 returns all
267
-	 * @param int $offset the start entry
268
-	 * @return array
269
-	 * @since 9.0.0
270
-	 *
271
-	 * The return array looks like this
272
-	 * [
273
-	 *   'comment' => IComment, // root comment
274
-	 *   'replies' =>
275
-	 *   [
276
-	 *     0 =>
277
-	 *     [
278
-	 *       'comment' => IComment,
279
-	 *       'replies' => []
280
-	 *     ]
281
-	 *     1 =>
282
-	 *     [
283
-	 *       'comment' => IComment,
284
-	 *       'replies'=> []
285
-	 *     ],
286
-	 *     …
287
-	 *   ]
288
-	 * ]
289
-	 */
290
-	public function getTree($id, $limit = 0, $offset = 0) {
291
-		$tree = [];
292
-		$tree['comment'] = $this->get($id);
293
-		$tree['replies'] = [];
294
-
295
-		$qb = $this->dbConn->getQueryBuilder();
296
-		$query = $qb->select('*')
297
-			->from('comments')
298
-			->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
299
-			->orderBy('creation_timestamp', 'DESC')
300
-			->setParameter('id', $id);
301
-
302
-		if ($limit > 0) {
303
-			$query->setMaxResults($limit);
304
-		}
305
-		if ($offset > 0) {
306
-			$query->setFirstResult($offset);
307
-		}
308
-
309
-		$resultStatement = $query->execute();
310
-		while ($data = $resultStatement->fetch()) {
311
-			$comment = new Comment($this->normalizeDatabaseData($data));
312
-			$this->cache($comment);
313
-			$tree['replies'][] = [
314
-				'comment' => $comment,
315
-				'replies' => []
316
-			];
317
-		}
318
-		$resultStatement->closeCursor();
319
-
320
-		return $tree;
321
-	}
322
-
323
-	/**
324
-	 * returns comments for a specific object (e.g. a file).
325
-	 *
326
-	 * The sort order is always newest to oldest.
327
-	 *
328
-	 * @param string $objectType the object type, e.g. 'files'
329
-	 * @param string $objectId the id of the object
330
-	 * @param int $limit optional, number of maximum comments to be returned. if
331
-	 * not specified, all comments are returned.
332
-	 * @param int $offset optional, starting point
333
-	 * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
334
-	 * that may be returned
335
-	 * @return IComment[]
336
-	 * @since 9.0.0
337
-	 */
338
-	public function getForObject(
339
-		$objectType,
340
-		$objectId,
341
-		$limit = 0,
342
-		$offset = 0,
343
-		\DateTime $notOlderThan = null
344
-	) {
345
-		$comments = [];
346
-
347
-		$qb = $this->dbConn->getQueryBuilder();
348
-		$query = $qb->select('*')
349
-			->from('comments')
350
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
351
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
352
-			->orderBy('creation_timestamp', 'DESC')
353
-			->setParameter('type', $objectType)
354
-			->setParameter('id', $objectId);
355
-
356
-		if ($limit > 0) {
357
-			$query->setMaxResults($limit);
358
-		}
359
-		if ($offset > 0) {
360
-			$query->setFirstResult($offset);
361
-		}
362
-		if (!is_null($notOlderThan)) {
363
-			$query
364
-				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
365
-				->setParameter('notOlderThan', $notOlderThan, 'datetime');
366
-		}
367
-
368
-		$resultStatement = $query->execute();
369
-		while ($data = $resultStatement->fetch()) {
370
-			$comment = new Comment($this->normalizeDatabaseData($data));
371
-			$this->cache($comment);
372
-			$comments[] = $comment;
373
-		}
374
-		$resultStatement->closeCursor();
375
-
376
-		return $comments;
377
-	}
378
-
379
-	/**
380
-	 * @param string $objectType the object type, e.g. 'files'
381
-	 * @param string $objectId the id of the object
382
-	 * @param int $lastKnownCommentId the last known comment (will be used as offset)
383
-	 * @param string $sortDirection direction of the comments (`asc` or `desc`)
384
-	 * @param int $limit optional, number of maximum comments to be returned. if
385
-	 * set to 0, all comments are returned.
386
-	 * @return IComment[]
387
-	 * @return array
388
-	 */
389
-	public function getForObjectSince(
390
-		string $objectType,
391
-		string $objectId,
392
-		int $lastKnownCommentId,
393
-		string $sortDirection = 'asc',
394
-		int $limit = 30
395
-	): array {
396
-		$comments = [];
397
-
398
-		$query = $this->dbConn->getQueryBuilder();
399
-		$query->select('*')
400
-			->from('comments')
401
-			->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
402
-			->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
403
-			->orderBy('creation_timestamp', $sortDirection === 'desc' ? 'DESC' : 'ASC')
404
-			->addOrderBy('id', $sortDirection === 'desc' ? 'DESC' : 'ASC');
405
-
406
-		if ($limit > 0) {
407
-			$query->setMaxResults($limit);
408
-		}
409
-
410
-		$lastKnownComment = $lastKnownCommentId > 0 ? $this->getLastKnownComment(
411
-			$objectType,
412
-			$objectId,
413
-			$lastKnownCommentId
414
-		) : null;
415
-		if ($lastKnownComment instanceof IComment) {
416
-			$lastKnownCommentDateTime = $lastKnownComment->getCreationDateTime();
417
-			if ($sortDirection === 'desc') {
418
-				$query->andWhere(
419
-					$query->expr()->orX(
420
-						$query->expr()->lt(
421
-							'creation_timestamp',
422
-							$query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
423
-							IQueryBuilder::PARAM_DATE
424
-						),
425
-						$query->expr()->andX(
426
-							$query->expr()->eq(
427
-								'creation_timestamp',
428
-								$query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
429
-								IQueryBuilder::PARAM_DATE
430
-							),
431
-							$query->expr()->lt('id', $query->createNamedParameter($lastKnownCommentId))
432
-						)
433
-					)
434
-				);
435
-			} else {
436
-				$query->andWhere(
437
-					$query->expr()->orX(
438
-						$query->expr()->gt(
439
-							'creation_timestamp',
440
-							$query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
441
-							IQueryBuilder::PARAM_DATE
442
-						),
443
-						$query->expr()->andX(
444
-							$query->expr()->eq(
445
-								'creation_timestamp',
446
-								$query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
447
-								IQueryBuilder::PARAM_DATE
448
-							),
449
-							$query->expr()->gt('id', $query->createNamedParameter($lastKnownCommentId))
450
-						)
451
-					)
452
-				);
453
-			}
454
-		}
455
-
456
-		$resultStatement = $query->execute();
457
-		while ($data = $resultStatement->fetch()) {
458
-			$comment = new Comment($this->normalizeDatabaseData($data));
459
-			$this->cache($comment);
460
-			$comments[] = $comment;
461
-		}
462
-		$resultStatement->closeCursor();
463
-
464
-		return $comments;
465
-	}
466
-
467
-	/**
468
-	 * @param string $objectType the object type, e.g. 'files'
469
-	 * @param string $objectId the id of the object
470
-	 * @param int $id the comment to look for
471
-	 * @return Comment|null
472
-	 */
473
-	protected function getLastKnownComment(string $objectType,
474
-										   string $objectId,
475
-										   int $id) {
476
-		$query = $this->dbConn->getQueryBuilder();
477
-		$query->select('*')
478
-			->from('comments')
479
-			->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
480
-			->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
481
-			->andWhere($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
482
-
483
-		$result = $query->execute();
484
-		$row = $result->fetch();
485
-		$result->closeCursor();
486
-
487
-		if ($row) {
488
-			$comment = new Comment($this->normalizeDatabaseData($row));
489
-			$this->cache($comment);
490
-			return $comment;
491
-		}
492
-
493
-		return null;
494
-	}
495
-
496
-	/**
497
-	 * Search for comments with a given content
498
-	 *
499
-	 * @param string $search content to search for
500
-	 * @param string $objectType Limit the search by object type
501
-	 * @param string $objectId Limit the search by object id
502
-	 * @param string $verb Limit the verb of the comment
503
-	 * @param int $offset
504
-	 * @param int $limit
505
-	 * @return IComment[]
506
-	 */
507
-	public function search(string $search, string $objectType, string $objectId, string $verb, int $offset, int $limit = 50): array {
508
-		$query = $this->dbConn->getQueryBuilder();
509
-
510
-		$query->select('*')
511
-			->from('comments')
512
-			->where($query->expr()->iLike('message', $query->createNamedParameter(
513
-				'%' . $this->dbConn->escapeLikeParameter($search). '%'
514
-			)))
515
-			->orderBy('creation_timestamp', 'DESC')
516
-			->addOrderBy('id', 'DESC')
517
-			->setMaxResults($limit);
518
-
519
-		if ($objectType !== '') {
520
-			$query->andWhere($query->expr()->eq('object_type', $query->createNamedParameter($objectType)));
521
-		}
522
-		if ($objectId !== '') {
523
-			$query->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)));
524
-		}
525
-		if ($verb !== '') {
526
-			$query->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)));
527
-		}
528
-		if ($offset !== 0) {
529
-			$query->setFirstResult($offset);
530
-		}
531
-
532
-		$comments = [];
533
-		$result = $query->execute();
534
-		while ($data = $result->fetch()) {
535
-			$comment = new Comment($this->normalizeDatabaseData($data));
536
-			$this->cache($comment);
537
-			$comments[] = $comment;
538
-		}
539
-		$result->closeCursor();
540
-
541
-		return $comments;
542
-	}
543
-
544
-	/**
545
-	 * @param $objectType string the object type, e.g. 'files'
546
-	 * @param $objectId string the id of the object
547
-	 * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
548
-	 * that may be returned
549
-	 * @param string $verb Limit the verb of the comment - Added in 14.0.0
550
-	 * @return Int
551
-	 * @since 9.0.0
552
-	 */
553
-	public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null, $verb = '') {
554
-		$qb = $this->dbConn->getQueryBuilder();
555
-		$query = $qb->select($qb->func()->count('id'))
556
-			->from('comments')
557
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
558
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
559
-			->setParameter('type', $objectType)
560
-			->setParameter('id', $objectId);
561
-
562
-		if (!is_null($notOlderThan)) {
563
-			$query
564
-				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
565
-				->setParameter('notOlderThan', $notOlderThan, 'datetime');
566
-		}
567
-
568
-		if ($verb !== '') {
569
-			$query->andWhere($qb->expr()->eq('verb', $qb->createNamedParameter($verb)));
570
-		}
571
-
572
-		$resultStatement = $query->execute();
573
-		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
574
-		$resultStatement->closeCursor();
575
-		return (int)$data[0];
576
-	}
577
-
578
-	/**
579
-	 * Get the number of unread comments for all files in a folder
580
-	 *
581
-	 * @param int $folderId
582
-	 * @param IUser $user
583
-	 * @return array [$fileId => $unreadCount]
584
-	 */
585
-	public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
586
-		$qb = $this->dbConn->getQueryBuilder();
587
-		$query = $qb->select('f.fileid')
588
-			->addSelect($qb->func()->count('c.id', 'num_ids'))
589
-			->from('comments', 'c')
590
-			->innerJoin('c', 'filecache', 'f', $qb->expr()->andX(
591
-				$qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
592
-				$qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT))
593
-			))
594
-			->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX(
595
-				$qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')),
596
-				$qb->expr()->eq('m.object_id', 'c.object_id'),
597
-				$qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID()))
598
-			))
599
-			->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId)))
600
-			->andWhere($qb->expr()->orX(
601
-				$qb->expr()->gt('c.creation_timestamp', 'marker_datetime'),
602
-				$qb->expr()->isNull('marker_datetime')
603
-			))
604
-			->groupBy('f.fileid');
605
-
606
-		$resultStatement = $query->execute();
607
-
608
-		$results = [];
609
-		while ($row = $resultStatement->fetch()) {
610
-			$results[$row['fileid']] = (int) $row['num_ids'];
611
-		}
612
-		$resultStatement->closeCursor();
613
-		return $results;
614
-	}
615
-
616
-	/**
617
-	 * creates a new comment and returns it. At this point of time, it is not
618
-	 * saved in the used data storage. Use save() after setting other fields
619
-	 * of the comment (e.g. message or verb).
620
-	 *
621
-	 * @param string $actorType the actor type (e.g. 'users')
622
-	 * @param string $actorId a user id
623
-	 * @param string $objectType the object type the comment is attached to
624
-	 * @param string $objectId the object id the comment is attached to
625
-	 * @return IComment
626
-	 * @since 9.0.0
627
-	 */
628
-	public function create($actorType, $actorId, $objectType, $objectId) {
629
-		$comment = new Comment();
630
-		$comment
631
-			->setActor($actorType, $actorId)
632
-			->setObject($objectType, $objectId);
633
-		return $comment;
634
-	}
635
-
636
-	/**
637
-	 * permanently deletes the comment specified by the ID
638
-	 *
639
-	 * When the comment has child comments, their parent ID will be changed to
640
-	 * the parent ID of the item that is to be deleted.
641
-	 *
642
-	 * @param string $id
643
-	 * @return bool
644
-	 * @throws \InvalidArgumentException
645
-	 * @since 9.0.0
646
-	 */
647
-	public function delete($id) {
648
-		if (!is_string($id)) {
649
-			throw new \InvalidArgumentException('Parameter must be string');
650
-		}
651
-
652
-		try {
653
-			$comment = $this->get($id);
654
-		} catch (\Exception $e) {
655
-			// Ignore exceptions, we just don't fire a hook then
656
-			$comment = null;
657
-		}
658
-
659
-		$qb = $this->dbConn->getQueryBuilder();
660
-		$query = $qb->delete('comments')
661
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
662
-			->setParameter('id', $id);
663
-
664
-		try {
665
-			$affectedRows = $query->execute();
666
-			$this->uncache($id);
667
-		} catch (DriverException $e) {
668
-			$this->logger->logException($e, ['app' => 'core_comments']);
669
-			return false;
670
-		}
671
-
672
-		if ($affectedRows > 0 && $comment instanceof IComment) {
673
-			$this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
674
-		}
675
-
676
-		return ($affectedRows > 0);
677
-	}
678
-
679
-	/**
680
-	 * saves the comment permanently
681
-	 *
682
-	 * if the supplied comment has an empty ID, a new entry comment will be
683
-	 * saved and the instance updated with the new ID.
684
-	 *
685
-	 * Otherwise, an existing comment will be updated.
686
-	 *
687
-	 * Throws NotFoundException when a comment that is to be updated does not
688
-	 * exist anymore at this point of time.
689
-	 *
690
-	 * @param IComment $comment
691
-	 * @return bool
692
-	 * @throws NotFoundException
693
-	 * @since 9.0.0
694
-	 */
695
-	public function save(IComment $comment) {
696
-		if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
697
-			$result = $this->insert($comment);
698
-		} else {
699
-			$result = $this->update($comment);
700
-		}
701
-
702
-		if ($result && !!$comment->getParentId()) {
703
-			$this->updateChildrenInformation(
704
-				$comment->getParentId(),
705
-				$comment->getCreationDateTime()
706
-			);
707
-			$this->cache($comment);
708
-		}
709
-
710
-		return $result;
711
-	}
712
-
713
-	/**
714
-	 * inserts the provided comment in the database
715
-	 *
716
-	 * @param IComment $comment
717
-	 * @return bool
718
-	 */
719
-	protected function insert(IComment &$comment) {
720
-		$qb = $this->dbConn->getQueryBuilder();
721
-		$affectedRows = $qb
722
-			->insert('comments')
723
-			->values([
724
-				'parent_id' => $qb->createNamedParameter($comment->getParentId()),
725
-				'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
726
-				'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
727
-				'actor_type' => $qb->createNamedParameter($comment->getActorType()),
728
-				'actor_id' => $qb->createNamedParameter($comment->getActorId()),
729
-				'message' => $qb->createNamedParameter($comment->getMessage()),
730
-				'verb' => $qb->createNamedParameter($comment->getVerb()),
731
-				'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
732
-				'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
733
-				'object_type' => $qb->createNamedParameter($comment->getObjectType()),
734
-				'object_id' => $qb->createNamedParameter($comment->getObjectId()),
735
-			])
736
-			->execute();
737
-
738
-		if ($affectedRows > 0) {
739
-			$comment->setId((string)$qb->getLastInsertId());
740
-			$this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
741
-		}
742
-
743
-		return $affectedRows > 0;
744
-	}
745
-
746
-	/**
747
-	 * updates a Comment data row
748
-	 *
749
-	 * @param IComment $comment
750
-	 * @return bool
751
-	 * @throws NotFoundException
752
-	 */
753
-	protected function update(IComment $comment) {
754
-		// for properly working preUpdate Events we need the old comments as is
755
-		// in the DB and overcome caching. Also avoid that outdated information stays.
756
-		$this->uncache($comment->getId());
757
-		$this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
758
-		$this->uncache($comment->getId());
759
-
760
-		$qb = $this->dbConn->getQueryBuilder();
761
-		$affectedRows = $qb
762
-			->update('comments')
763
-			->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
764
-			->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
765
-			->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
766
-			->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
767
-			->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
768
-			->set('message', $qb->createNamedParameter($comment->getMessage()))
769
-			->set('verb', $qb->createNamedParameter($comment->getVerb()))
770
-			->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
771
-			->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
772
-			->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
773
-			->set('object_id', $qb->createNamedParameter($comment->getObjectId()))
774
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
775
-			->setParameter('id', $comment->getId())
776
-			->execute();
777
-
778
-		if ($affectedRows === 0) {
779
-			throw new NotFoundException('Comment to update does ceased to exist');
780
-		}
781
-
782
-		$this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
783
-
784
-		return $affectedRows > 0;
785
-	}
786
-
787
-	/**
788
-	 * removes references to specific actor (e.g. on user delete) of a comment.
789
-	 * The comment itself must not get lost/deleted.
790
-	 *
791
-	 * @param string $actorType the actor type (e.g. 'users')
792
-	 * @param string $actorId a user id
793
-	 * @return boolean
794
-	 * @since 9.0.0
795
-	 */
796
-	public function deleteReferencesOfActor($actorType, $actorId) {
797
-		$this->checkRoleParameters('Actor', $actorType, $actorId);
798
-
799
-		$qb = $this->dbConn->getQueryBuilder();
800
-		$affectedRows = $qb
801
-			->update('comments')
802
-			->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
803
-			->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
804
-			->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
805
-			->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
806
-			->setParameter('type', $actorType)
807
-			->setParameter('id', $actorId)
808
-			->execute();
809
-
810
-		$this->commentsCache = [];
811
-
812
-		return is_int($affectedRows);
813
-	}
814
-
815
-	/**
816
-	 * deletes all comments made of a specific object (e.g. on file delete)
817
-	 *
818
-	 * @param string $objectType the object type (e.g. 'files')
819
-	 * @param string $objectId e.g. the file id
820
-	 * @return boolean
821
-	 * @since 9.0.0
822
-	 */
823
-	public function deleteCommentsAtObject($objectType, $objectId) {
824
-		$this->checkRoleParameters('Object', $objectType, $objectId);
825
-
826
-		$qb = $this->dbConn->getQueryBuilder();
827
-		$affectedRows = $qb
828
-			->delete('comments')
829
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
830
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
831
-			->setParameter('type', $objectType)
832
-			->setParameter('id', $objectId)
833
-			->execute();
834
-
835
-		$this->commentsCache = [];
836
-
837
-		return is_int($affectedRows);
838
-	}
839
-
840
-	/**
841
-	 * deletes the read markers for the specified user
842
-	 *
843
-	 * @param \OCP\IUser $user
844
-	 * @return bool
845
-	 * @since 9.0.0
846
-	 */
847
-	public function deleteReadMarksFromUser(IUser $user) {
848
-		$qb = $this->dbConn->getQueryBuilder();
849
-		$query = $qb->delete('comments_read_markers')
850
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
851
-			->setParameter('user_id', $user->getUID());
852
-
853
-		try {
854
-			$affectedRows = $query->execute();
855
-		} catch (DriverException $e) {
856
-			$this->logger->logException($e, ['app' => 'core_comments']);
857
-			return false;
858
-		}
859
-		return ($affectedRows > 0);
860
-	}
861
-
862
-	/**
863
-	 * sets the read marker for a given file to the specified date for the
864
-	 * provided user
865
-	 *
866
-	 * @param string $objectType
867
-	 * @param string $objectId
868
-	 * @param \DateTime $dateTime
869
-	 * @param IUser $user
870
-	 * @since 9.0.0
871
-	 * @suppress SqlInjectionChecker
872
-	 */
873
-	public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
874
-		$this->checkRoleParameters('Object', $objectType, $objectId);
875
-
876
-		$qb = $this->dbConn->getQueryBuilder();
877
-		$values = [
878
-			'user_id' => $qb->createNamedParameter($user->getUID()),
879
-			'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
880
-			'object_type' => $qb->createNamedParameter($objectType),
881
-			'object_id' => $qb->createNamedParameter($objectId),
882
-		];
883
-
884
-		// Strategy: try to update, if this does not return affected rows, do an insert.
885
-		$affectedRows = $qb
886
-			->update('comments_read_markers')
887
-			->set('user_id', $values['user_id'])
888
-			->set('marker_datetime', $values['marker_datetime'])
889
-			->set('object_type', $values['object_type'])
890
-			->set('object_id', $values['object_id'])
891
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
892
-			->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
893
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
894
-			->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
895
-			->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
896
-			->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
897
-			->execute();
898
-
899
-		if ($affectedRows > 0) {
900
-			return;
901
-		}
902
-
903
-		$qb->insert('comments_read_markers')
904
-			->values($values)
905
-			->execute();
906
-	}
907
-
908
-	/**
909
-	 * returns the read marker for a given file to the specified date for the
910
-	 * provided user. It returns null, when the marker is not present, i.e.
911
-	 * no comments were marked as read.
912
-	 *
913
-	 * @param string $objectType
914
-	 * @param string $objectId
915
-	 * @param IUser $user
916
-	 * @return \DateTime|null
917
-	 * @since 9.0.0
918
-	 */
919
-	public function getReadMark($objectType, $objectId, IUser $user) {
920
-		$qb = $this->dbConn->getQueryBuilder();
921
-		$resultStatement = $qb->select('marker_datetime')
922
-			->from('comments_read_markers')
923
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
924
-			->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
925
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
926
-			->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
927
-			->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
928
-			->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
929
-			->execute();
930
-
931
-		$data = $resultStatement->fetch();
932
-		$resultStatement->closeCursor();
933
-		if (!$data || is_null($data['marker_datetime'])) {
934
-			return null;
935
-		}
936
-
937
-		return new \DateTime($data['marker_datetime']);
938
-	}
939
-
940
-	/**
941
-	 * deletes the read markers on the specified object
942
-	 *
943
-	 * @param string $objectType
944
-	 * @param string $objectId
945
-	 * @return bool
946
-	 * @since 9.0.0
947
-	 */
948
-	public function deleteReadMarksOnObject($objectType, $objectId) {
949
-		$this->checkRoleParameters('Object', $objectType, $objectId);
950
-
951
-		$qb = $this->dbConn->getQueryBuilder();
952
-		$query = $qb->delete('comments_read_markers')
953
-			->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
954
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
955
-			->setParameter('object_type', $objectType)
956
-			->setParameter('object_id', $objectId);
957
-
958
-		try {
959
-			$affectedRows = $query->execute();
960
-		} catch (DriverException $e) {
961
-			$this->logger->logException($e, ['app' => 'core_comments']);
962
-			return false;
963
-		}
964
-		return ($affectedRows > 0);
965
-	}
966
-
967
-	/**
968
-	 * registers an Entity to the manager, so event notifications can be send
969
-	 * to consumers of the comments infrastructure
970
-	 *
971
-	 * @param \Closure $closure
972
-	 */
973
-	public function registerEventHandler(\Closure $closure) {
974
-		$this->eventHandlerClosures[] = $closure;
975
-		$this->eventHandlers = [];
976
-	}
977
-
978
-	/**
979
-	 * registers a method that resolves an ID to a display name for a given type
980
-	 *
981
-	 * @param string $type
982
-	 * @param \Closure $closure
983
-	 * @throws \OutOfBoundsException
984
-	 * @since 11.0.0
985
-	 *
986
-	 * Only one resolver shall be registered per type. Otherwise a
987
-	 * \OutOfBoundsException has to thrown.
988
-	 */
989
-	public function registerDisplayNameResolver($type, \Closure $closure) {
990
-		if (!is_string($type)) {
991
-			throw new \InvalidArgumentException('String expected.');
992
-		}
993
-		if (isset($this->displayNameResolvers[$type])) {
994
-			throw new \OutOfBoundsException('Displayname resolver for this type already registered');
995
-		}
996
-		$this->displayNameResolvers[$type] = $closure;
997
-	}
998
-
999
-	/**
1000
-	 * resolves a given ID of a given Type to a display name.
1001
-	 *
1002
-	 * @param string $type
1003
-	 * @param string $id
1004
-	 * @return string
1005
-	 * @throws \OutOfBoundsException
1006
-	 * @since 11.0.0
1007
-	 *
1008
-	 * If a provided type was not registered, an \OutOfBoundsException shall
1009
-	 * be thrown. It is upon the resolver discretion what to return of the
1010
-	 * provided ID is unknown. It must be ensured that a string is returned.
1011
-	 */
1012
-	public function resolveDisplayName($type, $id) {
1013
-		if (!is_string($type)) {
1014
-			throw new \InvalidArgumentException('String expected.');
1015
-		}
1016
-		if (!isset($this->displayNameResolvers[$type])) {
1017
-			throw new \OutOfBoundsException('No Displayname resolver for this type registered');
1018
-		}
1019
-		return (string)$this->displayNameResolvers[$type]($id);
1020
-	}
1021
-
1022
-	/**
1023
-	 * returns valid, registered entities
1024
-	 *
1025
-	 * @return \OCP\Comments\ICommentsEventHandler[]
1026
-	 */
1027
-	private function getEventHandlers() {
1028
-		if (!empty($this->eventHandlers)) {
1029
-			return $this->eventHandlers;
1030
-		}
1031
-
1032
-		$this->eventHandlers = [];
1033
-		foreach ($this->eventHandlerClosures as $name => $closure) {
1034
-			$entity = $closure();
1035
-			if (!($entity instanceof ICommentsEventHandler)) {
1036
-				throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
1037
-			}
1038
-			$this->eventHandlers[$name] = $entity;
1039
-		}
1040
-
1041
-		return $this->eventHandlers;
1042
-	}
1043
-
1044
-	/**
1045
-	 * sends notifications to the registered entities
1046
-	 *
1047
-	 * @param $eventType
1048
-	 * @param IComment $comment
1049
-	 */
1050
-	private function sendEvent($eventType, IComment $comment) {
1051
-		$entities = $this->getEventHandlers();
1052
-		$event = new CommentsEvent($eventType, $comment);
1053
-		foreach ($entities as $entity) {
1054
-			$entity->handle($event);
1055
-		}
1056
-	}
44
+    /** @var  IDBConnection */
45
+    protected $dbConn;
46
+
47
+    /** @var  ILogger */
48
+    protected $logger;
49
+
50
+    /** @var IConfig */
51
+    protected $config;
52
+
53
+    /** @var IComment[] */
54
+    protected $commentsCache = [];
55
+
56
+    /** @var  \Closure[] */
57
+    protected $eventHandlerClosures = [];
58
+
59
+    /** @var  ICommentsEventHandler[] */
60
+    protected $eventHandlers = [];
61
+
62
+    /** @var \Closure[] */
63
+    protected $displayNameResolvers = [];
64
+
65
+    /**
66
+     * Manager constructor.
67
+     *
68
+     * @param IDBConnection $dbConn
69
+     * @param ILogger $logger
70
+     * @param IConfig $config
71
+     */
72
+    public function __construct(
73
+        IDBConnection $dbConn,
74
+        ILogger $logger,
75
+        IConfig $config
76
+    ) {
77
+        $this->dbConn = $dbConn;
78
+        $this->logger = $logger;
79
+        $this->config = $config;
80
+    }
81
+
82
+    /**
83
+     * converts data base data into PHP native, proper types as defined by
84
+     * IComment interface.
85
+     *
86
+     * @param array $data
87
+     * @return array
88
+     */
89
+    protected function normalizeDatabaseData(array $data) {
90
+        $data['id'] = (string)$data['id'];
91
+        $data['parent_id'] = (string)$data['parent_id'];
92
+        $data['topmost_parent_id'] = (string)$data['topmost_parent_id'];
93
+        $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
94
+        if (!is_null($data['latest_child_timestamp'])) {
95
+            $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
96
+        }
97
+        $data['children_count'] = (int)$data['children_count'];
98
+        return $data;
99
+    }
100
+
101
+    /**
102
+     * prepares a comment for an insert or update operation after making sure
103
+     * all necessary fields have a value assigned.
104
+     *
105
+     * @param IComment $comment
106
+     * @return IComment returns the same updated IComment instance as provided
107
+     *                  by parameter for convenience
108
+     * @throws \UnexpectedValueException
109
+     */
110
+    protected function prepareCommentForDatabaseWrite(IComment $comment) {
111
+        if (!$comment->getActorType()
112
+            || !$comment->getActorId()
113
+            || !$comment->getObjectType()
114
+            || !$comment->getObjectId()
115
+            || !$comment->getVerb()
116
+        ) {
117
+            throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
118
+        }
119
+
120
+        if ($comment->getId() === '') {
121
+            $comment->setChildrenCount(0);
122
+            $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
123
+            $comment->setLatestChildDateTime(null);
124
+        }
125
+
126
+        if (is_null($comment->getCreationDateTime())) {
127
+            $comment->setCreationDateTime(new \DateTime());
128
+        }
129
+
130
+        if ($comment->getParentId() !== '0') {
131
+            $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
132
+        } else {
133
+            $comment->setTopmostParentId('0');
134
+        }
135
+
136
+        $this->cache($comment);
137
+
138
+        return $comment;
139
+    }
140
+
141
+    /**
142
+     * returns the topmost parent id of a given comment identified by ID
143
+     *
144
+     * @param string $id
145
+     * @return string
146
+     * @throws NotFoundException
147
+     */
148
+    protected function determineTopmostParentId($id) {
149
+        $comment = $this->get($id);
150
+        if ($comment->getParentId() === '0') {
151
+            return $comment->getId();
152
+        } else {
153
+            return $this->determineTopmostParentId($comment->getId());
154
+        }
155
+    }
156
+
157
+    /**
158
+     * updates child information of a comment
159
+     *
160
+     * @param string $id
161
+     * @param \DateTime $cDateTime the date time of the most recent child
162
+     * @throws NotFoundException
163
+     */
164
+    protected function updateChildrenInformation($id, \DateTime $cDateTime) {
165
+        $qb = $this->dbConn->getQueryBuilder();
166
+        $query = $qb->select($qb->func()->count('id'))
167
+            ->from('comments')
168
+            ->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
169
+            ->setParameter('id', $id);
170
+
171
+        $resultStatement = $query->execute();
172
+        $data = $resultStatement->fetch(\PDO::FETCH_NUM);
173
+        $resultStatement->closeCursor();
174
+        $children = (int)$data[0];
175
+
176
+        $comment = $this->get($id);
177
+        $comment->setChildrenCount($children);
178
+        $comment->setLatestChildDateTime($cDateTime);
179
+        $this->save($comment);
180
+    }
181
+
182
+    /**
183
+     * Tests whether actor or object type and id parameters are acceptable.
184
+     * Throws exception if not.
185
+     *
186
+     * @param string $role
187
+     * @param string $type
188
+     * @param string $id
189
+     * @throws \InvalidArgumentException
190
+     */
191
+    protected function checkRoleParameters($role, $type, $id) {
192
+        if (
193
+            !is_string($type) || empty($type)
194
+            || !is_string($id) || empty($id)
195
+        ) {
196
+            throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
197
+        }
198
+    }
199
+
200
+    /**
201
+     * run-time caches a comment
202
+     *
203
+     * @param IComment $comment
204
+     */
205
+    protected function cache(IComment $comment) {
206
+        $id = $comment->getId();
207
+        if (empty($id)) {
208
+            return;
209
+        }
210
+        $this->commentsCache[(string)$id] = $comment;
211
+    }
212
+
213
+    /**
214
+     * removes an entry from the comments run time cache
215
+     *
216
+     * @param mixed $id the comment's id
217
+     */
218
+    protected function uncache($id) {
219
+        $id = (string)$id;
220
+        if (isset($this->commentsCache[$id])) {
221
+            unset($this->commentsCache[$id]);
222
+        }
223
+    }
224
+
225
+    /**
226
+     * returns a comment instance
227
+     *
228
+     * @param string $id the ID of the comment
229
+     * @return IComment
230
+     * @throws NotFoundException
231
+     * @throws \InvalidArgumentException
232
+     * @since 9.0.0
233
+     */
234
+    public function get($id) {
235
+        if ((int)$id === 0) {
236
+            throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
237
+        }
238
+
239
+        if (isset($this->commentsCache[$id])) {
240
+            return $this->commentsCache[$id];
241
+        }
242
+
243
+        $qb = $this->dbConn->getQueryBuilder();
244
+        $resultStatement = $qb->select('*')
245
+            ->from('comments')
246
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
247
+            ->setParameter('id', $id, IQueryBuilder::PARAM_INT)
248
+            ->execute();
249
+
250
+        $data = $resultStatement->fetch();
251
+        $resultStatement->closeCursor();
252
+        if (!$data) {
253
+            throw new NotFoundException();
254
+        }
255
+
256
+        $comment = new Comment($this->normalizeDatabaseData($data));
257
+        $this->cache($comment);
258
+        return $comment;
259
+    }
260
+
261
+    /**
262
+     * returns the comment specified by the id and all it's child comments.
263
+     * At this point of time, we do only support one level depth.
264
+     *
265
+     * @param string $id
266
+     * @param int $limit max number of entries to return, 0 returns all
267
+     * @param int $offset the start entry
268
+     * @return array
269
+     * @since 9.0.0
270
+     *
271
+     * The return array looks like this
272
+     * [
273
+     *   'comment' => IComment, // root comment
274
+     *   'replies' =>
275
+     *   [
276
+     *     0 =>
277
+     *     [
278
+     *       'comment' => IComment,
279
+     *       'replies' => []
280
+     *     ]
281
+     *     1 =>
282
+     *     [
283
+     *       'comment' => IComment,
284
+     *       'replies'=> []
285
+     *     ],
286
+     *     …
287
+     *   ]
288
+     * ]
289
+     */
290
+    public function getTree($id, $limit = 0, $offset = 0) {
291
+        $tree = [];
292
+        $tree['comment'] = $this->get($id);
293
+        $tree['replies'] = [];
294
+
295
+        $qb = $this->dbConn->getQueryBuilder();
296
+        $query = $qb->select('*')
297
+            ->from('comments')
298
+            ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
299
+            ->orderBy('creation_timestamp', 'DESC')
300
+            ->setParameter('id', $id);
301
+
302
+        if ($limit > 0) {
303
+            $query->setMaxResults($limit);
304
+        }
305
+        if ($offset > 0) {
306
+            $query->setFirstResult($offset);
307
+        }
308
+
309
+        $resultStatement = $query->execute();
310
+        while ($data = $resultStatement->fetch()) {
311
+            $comment = new Comment($this->normalizeDatabaseData($data));
312
+            $this->cache($comment);
313
+            $tree['replies'][] = [
314
+                'comment' => $comment,
315
+                'replies' => []
316
+            ];
317
+        }
318
+        $resultStatement->closeCursor();
319
+
320
+        return $tree;
321
+    }
322
+
323
+    /**
324
+     * returns comments for a specific object (e.g. a file).
325
+     *
326
+     * The sort order is always newest to oldest.
327
+     *
328
+     * @param string $objectType the object type, e.g. 'files'
329
+     * @param string $objectId the id of the object
330
+     * @param int $limit optional, number of maximum comments to be returned. if
331
+     * not specified, all comments are returned.
332
+     * @param int $offset optional, starting point
333
+     * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
334
+     * that may be returned
335
+     * @return IComment[]
336
+     * @since 9.0.0
337
+     */
338
+    public function getForObject(
339
+        $objectType,
340
+        $objectId,
341
+        $limit = 0,
342
+        $offset = 0,
343
+        \DateTime $notOlderThan = null
344
+    ) {
345
+        $comments = [];
346
+
347
+        $qb = $this->dbConn->getQueryBuilder();
348
+        $query = $qb->select('*')
349
+            ->from('comments')
350
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
351
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
352
+            ->orderBy('creation_timestamp', 'DESC')
353
+            ->setParameter('type', $objectType)
354
+            ->setParameter('id', $objectId);
355
+
356
+        if ($limit > 0) {
357
+            $query->setMaxResults($limit);
358
+        }
359
+        if ($offset > 0) {
360
+            $query->setFirstResult($offset);
361
+        }
362
+        if (!is_null($notOlderThan)) {
363
+            $query
364
+                ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
365
+                ->setParameter('notOlderThan', $notOlderThan, 'datetime');
366
+        }
367
+
368
+        $resultStatement = $query->execute();
369
+        while ($data = $resultStatement->fetch()) {
370
+            $comment = new Comment($this->normalizeDatabaseData($data));
371
+            $this->cache($comment);
372
+            $comments[] = $comment;
373
+        }
374
+        $resultStatement->closeCursor();
375
+
376
+        return $comments;
377
+    }
378
+
379
+    /**
380
+     * @param string $objectType the object type, e.g. 'files'
381
+     * @param string $objectId the id of the object
382
+     * @param int $lastKnownCommentId the last known comment (will be used as offset)
383
+     * @param string $sortDirection direction of the comments (`asc` or `desc`)
384
+     * @param int $limit optional, number of maximum comments to be returned. if
385
+     * set to 0, all comments are returned.
386
+     * @return IComment[]
387
+     * @return array
388
+     */
389
+    public function getForObjectSince(
390
+        string $objectType,
391
+        string $objectId,
392
+        int $lastKnownCommentId,
393
+        string $sortDirection = 'asc',
394
+        int $limit = 30
395
+    ): array {
396
+        $comments = [];
397
+
398
+        $query = $this->dbConn->getQueryBuilder();
399
+        $query->select('*')
400
+            ->from('comments')
401
+            ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
402
+            ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
403
+            ->orderBy('creation_timestamp', $sortDirection === 'desc' ? 'DESC' : 'ASC')
404
+            ->addOrderBy('id', $sortDirection === 'desc' ? 'DESC' : 'ASC');
405
+
406
+        if ($limit > 0) {
407
+            $query->setMaxResults($limit);
408
+        }
409
+
410
+        $lastKnownComment = $lastKnownCommentId > 0 ? $this->getLastKnownComment(
411
+            $objectType,
412
+            $objectId,
413
+            $lastKnownCommentId
414
+        ) : null;
415
+        if ($lastKnownComment instanceof IComment) {
416
+            $lastKnownCommentDateTime = $lastKnownComment->getCreationDateTime();
417
+            if ($sortDirection === 'desc') {
418
+                $query->andWhere(
419
+                    $query->expr()->orX(
420
+                        $query->expr()->lt(
421
+                            'creation_timestamp',
422
+                            $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
423
+                            IQueryBuilder::PARAM_DATE
424
+                        ),
425
+                        $query->expr()->andX(
426
+                            $query->expr()->eq(
427
+                                'creation_timestamp',
428
+                                $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
429
+                                IQueryBuilder::PARAM_DATE
430
+                            ),
431
+                            $query->expr()->lt('id', $query->createNamedParameter($lastKnownCommentId))
432
+                        )
433
+                    )
434
+                );
435
+            } else {
436
+                $query->andWhere(
437
+                    $query->expr()->orX(
438
+                        $query->expr()->gt(
439
+                            'creation_timestamp',
440
+                            $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
441
+                            IQueryBuilder::PARAM_DATE
442
+                        ),
443
+                        $query->expr()->andX(
444
+                            $query->expr()->eq(
445
+                                'creation_timestamp',
446
+                                $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
447
+                                IQueryBuilder::PARAM_DATE
448
+                            ),
449
+                            $query->expr()->gt('id', $query->createNamedParameter($lastKnownCommentId))
450
+                        )
451
+                    )
452
+                );
453
+            }
454
+        }
455
+
456
+        $resultStatement = $query->execute();
457
+        while ($data = $resultStatement->fetch()) {
458
+            $comment = new Comment($this->normalizeDatabaseData($data));
459
+            $this->cache($comment);
460
+            $comments[] = $comment;
461
+        }
462
+        $resultStatement->closeCursor();
463
+
464
+        return $comments;
465
+    }
466
+
467
+    /**
468
+     * @param string $objectType the object type, e.g. 'files'
469
+     * @param string $objectId the id of the object
470
+     * @param int $id the comment to look for
471
+     * @return Comment|null
472
+     */
473
+    protected function getLastKnownComment(string $objectType,
474
+                                            string $objectId,
475
+                                            int $id) {
476
+        $query = $this->dbConn->getQueryBuilder();
477
+        $query->select('*')
478
+            ->from('comments')
479
+            ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
480
+            ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
481
+            ->andWhere($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
482
+
483
+        $result = $query->execute();
484
+        $row = $result->fetch();
485
+        $result->closeCursor();
486
+
487
+        if ($row) {
488
+            $comment = new Comment($this->normalizeDatabaseData($row));
489
+            $this->cache($comment);
490
+            return $comment;
491
+        }
492
+
493
+        return null;
494
+    }
495
+
496
+    /**
497
+     * Search for comments with a given content
498
+     *
499
+     * @param string $search content to search for
500
+     * @param string $objectType Limit the search by object type
501
+     * @param string $objectId Limit the search by object id
502
+     * @param string $verb Limit the verb of the comment
503
+     * @param int $offset
504
+     * @param int $limit
505
+     * @return IComment[]
506
+     */
507
+    public function search(string $search, string $objectType, string $objectId, string $verb, int $offset, int $limit = 50): array {
508
+        $query = $this->dbConn->getQueryBuilder();
509
+
510
+        $query->select('*')
511
+            ->from('comments')
512
+            ->where($query->expr()->iLike('message', $query->createNamedParameter(
513
+                '%' . $this->dbConn->escapeLikeParameter($search). '%'
514
+            )))
515
+            ->orderBy('creation_timestamp', 'DESC')
516
+            ->addOrderBy('id', 'DESC')
517
+            ->setMaxResults($limit);
518
+
519
+        if ($objectType !== '') {
520
+            $query->andWhere($query->expr()->eq('object_type', $query->createNamedParameter($objectType)));
521
+        }
522
+        if ($objectId !== '') {
523
+            $query->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)));
524
+        }
525
+        if ($verb !== '') {
526
+            $query->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)));
527
+        }
528
+        if ($offset !== 0) {
529
+            $query->setFirstResult($offset);
530
+        }
531
+
532
+        $comments = [];
533
+        $result = $query->execute();
534
+        while ($data = $result->fetch()) {
535
+            $comment = new Comment($this->normalizeDatabaseData($data));
536
+            $this->cache($comment);
537
+            $comments[] = $comment;
538
+        }
539
+        $result->closeCursor();
540
+
541
+        return $comments;
542
+    }
543
+
544
+    /**
545
+     * @param $objectType string the object type, e.g. 'files'
546
+     * @param $objectId string the id of the object
547
+     * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
548
+     * that may be returned
549
+     * @param string $verb Limit the verb of the comment - Added in 14.0.0
550
+     * @return Int
551
+     * @since 9.0.0
552
+     */
553
+    public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null, $verb = '') {
554
+        $qb = $this->dbConn->getQueryBuilder();
555
+        $query = $qb->select($qb->func()->count('id'))
556
+            ->from('comments')
557
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
558
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
559
+            ->setParameter('type', $objectType)
560
+            ->setParameter('id', $objectId);
561
+
562
+        if (!is_null($notOlderThan)) {
563
+            $query
564
+                ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
565
+                ->setParameter('notOlderThan', $notOlderThan, 'datetime');
566
+        }
567
+
568
+        if ($verb !== '') {
569
+            $query->andWhere($qb->expr()->eq('verb', $qb->createNamedParameter($verb)));
570
+        }
571
+
572
+        $resultStatement = $query->execute();
573
+        $data = $resultStatement->fetch(\PDO::FETCH_NUM);
574
+        $resultStatement->closeCursor();
575
+        return (int)$data[0];
576
+    }
577
+
578
+    /**
579
+     * Get the number of unread comments for all files in a folder
580
+     *
581
+     * @param int $folderId
582
+     * @param IUser $user
583
+     * @return array [$fileId => $unreadCount]
584
+     */
585
+    public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
586
+        $qb = $this->dbConn->getQueryBuilder();
587
+        $query = $qb->select('f.fileid')
588
+            ->addSelect($qb->func()->count('c.id', 'num_ids'))
589
+            ->from('comments', 'c')
590
+            ->innerJoin('c', 'filecache', 'f', $qb->expr()->andX(
591
+                $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
592
+                $qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT))
593
+            ))
594
+            ->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX(
595
+                $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')),
596
+                $qb->expr()->eq('m.object_id', 'c.object_id'),
597
+                $qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID()))
598
+            ))
599
+            ->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId)))
600
+            ->andWhere($qb->expr()->orX(
601
+                $qb->expr()->gt('c.creation_timestamp', 'marker_datetime'),
602
+                $qb->expr()->isNull('marker_datetime')
603
+            ))
604
+            ->groupBy('f.fileid');
605
+
606
+        $resultStatement = $query->execute();
607
+
608
+        $results = [];
609
+        while ($row = $resultStatement->fetch()) {
610
+            $results[$row['fileid']] = (int) $row['num_ids'];
611
+        }
612
+        $resultStatement->closeCursor();
613
+        return $results;
614
+    }
615
+
616
+    /**
617
+     * creates a new comment and returns it. At this point of time, it is not
618
+     * saved in the used data storage. Use save() after setting other fields
619
+     * of the comment (e.g. message or verb).
620
+     *
621
+     * @param string $actorType the actor type (e.g. 'users')
622
+     * @param string $actorId a user id
623
+     * @param string $objectType the object type the comment is attached to
624
+     * @param string $objectId the object id the comment is attached to
625
+     * @return IComment
626
+     * @since 9.0.0
627
+     */
628
+    public function create($actorType, $actorId, $objectType, $objectId) {
629
+        $comment = new Comment();
630
+        $comment
631
+            ->setActor($actorType, $actorId)
632
+            ->setObject($objectType, $objectId);
633
+        return $comment;
634
+    }
635
+
636
+    /**
637
+     * permanently deletes the comment specified by the ID
638
+     *
639
+     * When the comment has child comments, their parent ID will be changed to
640
+     * the parent ID of the item that is to be deleted.
641
+     *
642
+     * @param string $id
643
+     * @return bool
644
+     * @throws \InvalidArgumentException
645
+     * @since 9.0.0
646
+     */
647
+    public function delete($id) {
648
+        if (!is_string($id)) {
649
+            throw new \InvalidArgumentException('Parameter must be string');
650
+        }
651
+
652
+        try {
653
+            $comment = $this->get($id);
654
+        } catch (\Exception $e) {
655
+            // Ignore exceptions, we just don't fire a hook then
656
+            $comment = null;
657
+        }
658
+
659
+        $qb = $this->dbConn->getQueryBuilder();
660
+        $query = $qb->delete('comments')
661
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
662
+            ->setParameter('id', $id);
663
+
664
+        try {
665
+            $affectedRows = $query->execute();
666
+            $this->uncache($id);
667
+        } catch (DriverException $e) {
668
+            $this->logger->logException($e, ['app' => 'core_comments']);
669
+            return false;
670
+        }
671
+
672
+        if ($affectedRows > 0 && $comment instanceof IComment) {
673
+            $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
674
+        }
675
+
676
+        return ($affectedRows > 0);
677
+    }
678
+
679
+    /**
680
+     * saves the comment permanently
681
+     *
682
+     * if the supplied comment has an empty ID, a new entry comment will be
683
+     * saved and the instance updated with the new ID.
684
+     *
685
+     * Otherwise, an existing comment will be updated.
686
+     *
687
+     * Throws NotFoundException when a comment that is to be updated does not
688
+     * exist anymore at this point of time.
689
+     *
690
+     * @param IComment $comment
691
+     * @return bool
692
+     * @throws NotFoundException
693
+     * @since 9.0.0
694
+     */
695
+    public function save(IComment $comment) {
696
+        if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
697
+            $result = $this->insert($comment);
698
+        } else {
699
+            $result = $this->update($comment);
700
+        }
701
+
702
+        if ($result && !!$comment->getParentId()) {
703
+            $this->updateChildrenInformation(
704
+                $comment->getParentId(),
705
+                $comment->getCreationDateTime()
706
+            );
707
+            $this->cache($comment);
708
+        }
709
+
710
+        return $result;
711
+    }
712
+
713
+    /**
714
+     * inserts the provided comment in the database
715
+     *
716
+     * @param IComment $comment
717
+     * @return bool
718
+     */
719
+    protected function insert(IComment &$comment) {
720
+        $qb = $this->dbConn->getQueryBuilder();
721
+        $affectedRows = $qb
722
+            ->insert('comments')
723
+            ->values([
724
+                'parent_id' => $qb->createNamedParameter($comment->getParentId()),
725
+                'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
726
+                'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
727
+                'actor_type' => $qb->createNamedParameter($comment->getActorType()),
728
+                'actor_id' => $qb->createNamedParameter($comment->getActorId()),
729
+                'message' => $qb->createNamedParameter($comment->getMessage()),
730
+                'verb' => $qb->createNamedParameter($comment->getVerb()),
731
+                'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
732
+                'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
733
+                'object_type' => $qb->createNamedParameter($comment->getObjectType()),
734
+                'object_id' => $qb->createNamedParameter($comment->getObjectId()),
735
+            ])
736
+            ->execute();
737
+
738
+        if ($affectedRows > 0) {
739
+            $comment->setId((string)$qb->getLastInsertId());
740
+            $this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
741
+        }
742
+
743
+        return $affectedRows > 0;
744
+    }
745
+
746
+    /**
747
+     * updates a Comment data row
748
+     *
749
+     * @param IComment $comment
750
+     * @return bool
751
+     * @throws NotFoundException
752
+     */
753
+    protected function update(IComment $comment) {
754
+        // for properly working preUpdate Events we need the old comments as is
755
+        // in the DB and overcome caching. Also avoid that outdated information stays.
756
+        $this->uncache($comment->getId());
757
+        $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
758
+        $this->uncache($comment->getId());
759
+
760
+        $qb = $this->dbConn->getQueryBuilder();
761
+        $affectedRows = $qb
762
+            ->update('comments')
763
+            ->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
764
+            ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
765
+            ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
766
+            ->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
767
+            ->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
768
+            ->set('message', $qb->createNamedParameter($comment->getMessage()))
769
+            ->set('verb', $qb->createNamedParameter($comment->getVerb()))
770
+            ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
771
+            ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
772
+            ->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
773
+            ->set('object_id', $qb->createNamedParameter($comment->getObjectId()))
774
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
775
+            ->setParameter('id', $comment->getId())
776
+            ->execute();
777
+
778
+        if ($affectedRows === 0) {
779
+            throw new NotFoundException('Comment to update does ceased to exist');
780
+        }
781
+
782
+        $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
783
+
784
+        return $affectedRows > 0;
785
+    }
786
+
787
+    /**
788
+     * removes references to specific actor (e.g. on user delete) of a comment.
789
+     * The comment itself must not get lost/deleted.
790
+     *
791
+     * @param string $actorType the actor type (e.g. 'users')
792
+     * @param string $actorId a user id
793
+     * @return boolean
794
+     * @since 9.0.0
795
+     */
796
+    public function deleteReferencesOfActor($actorType, $actorId) {
797
+        $this->checkRoleParameters('Actor', $actorType, $actorId);
798
+
799
+        $qb = $this->dbConn->getQueryBuilder();
800
+        $affectedRows = $qb
801
+            ->update('comments')
802
+            ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
803
+            ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
804
+            ->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
805
+            ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
806
+            ->setParameter('type', $actorType)
807
+            ->setParameter('id', $actorId)
808
+            ->execute();
809
+
810
+        $this->commentsCache = [];
811
+
812
+        return is_int($affectedRows);
813
+    }
814
+
815
+    /**
816
+     * deletes all comments made of a specific object (e.g. on file delete)
817
+     *
818
+     * @param string $objectType the object type (e.g. 'files')
819
+     * @param string $objectId e.g. the file id
820
+     * @return boolean
821
+     * @since 9.0.0
822
+     */
823
+    public function deleteCommentsAtObject($objectType, $objectId) {
824
+        $this->checkRoleParameters('Object', $objectType, $objectId);
825
+
826
+        $qb = $this->dbConn->getQueryBuilder();
827
+        $affectedRows = $qb
828
+            ->delete('comments')
829
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
830
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
831
+            ->setParameter('type', $objectType)
832
+            ->setParameter('id', $objectId)
833
+            ->execute();
834
+
835
+        $this->commentsCache = [];
836
+
837
+        return is_int($affectedRows);
838
+    }
839
+
840
+    /**
841
+     * deletes the read markers for the specified user
842
+     *
843
+     * @param \OCP\IUser $user
844
+     * @return bool
845
+     * @since 9.0.0
846
+     */
847
+    public function deleteReadMarksFromUser(IUser $user) {
848
+        $qb = $this->dbConn->getQueryBuilder();
849
+        $query = $qb->delete('comments_read_markers')
850
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
851
+            ->setParameter('user_id', $user->getUID());
852
+
853
+        try {
854
+            $affectedRows = $query->execute();
855
+        } catch (DriverException $e) {
856
+            $this->logger->logException($e, ['app' => 'core_comments']);
857
+            return false;
858
+        }
859
+        return ($affectedRows > 0);
860
+    }
861
+
862
+    /**
863
+     * sets the read marker for a given file to the specified date for the
864
+     * provided user
865
+     *
866
+     * @param string $objectType
867
+     * @param string $objectId
868
+     * @param \DateTime $dateTime
869
+     * @param IUser $user
870
+     * @since 9.0.0
871
+     * @suppress SqlInjectionChecker
872
+     */
873
+    public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
874
+        $this->checkRoleParameters('Object', $objectType, $objectId);
875
+
876
+        $qb = $this->dbConn->getQueryBuilder();
877
+        $values = [
878
+            'user_id' => $qb->createNamedParameter($user->getUID()),
879
+            'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
880
+            'object_type' => $qb->createNamedParameter($objectType),
881
+            'object_id' => $qb->createNamedParameter($objectId),
882
+        ];
883
+
884
+        // Strategy: try to update, if this does not return affected rows, do an insert.
885
+        $affectedRows = $qb
886
+            ->update('comments_read_markers')
887
+            ->set('user_id', $values['user_id'])
888
+            ->set('marker_datetime', $values['marker_datetime'])
889
+            ->set('object_type', $values['object_type'])
890
+            ->set('object_id', $values['object_id'])
891
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
892
+            ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
893
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
894
+            ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
895
+            ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
896
+            ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
897
+            ->execute();
898
+
899
+        if ($affectedRows > 0) {
900
+            return;
901
+        }
902
+
903
+        $qb->insert('comments_read_markers')
904
+            ->values($values)
905
+            ->execute();
906
+    }
907
+
908
+    /**
909
+     * returns the read marker for a given file to the specified date for the
910
+     * provided user. It returns null, when the marker is not present, i.e.
911
+     * no comments were marked as read.
912
+     *
913
+     * @param string $objectType
914
+     * @param string $objectId
915
+     * @param IUser $user
916
+     * @return \DateTime|null
917
+     * @since 9.0.0
918
+     */
919
+    public function getReadMark($objectType, $objectId, IUser $user) {
920
+        $qb = $this->dbConn->getQueryBuilder();
921
+        $resultStatement = $qb->select('marker_datetime')
922
+            ->from('comments_read_markers')
923
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
924
+            ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
925
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
926
+            ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
927
+            ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
928
+            ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
929
+            ->execute();
930
+
931
+        $data = $resultStatement->fetch();
932
+        $resultStatement->closeCursor();
933
+        if (!$data || is_null($data['marker_datetime'])) {
934
+            return null;
935
+        }
936
+
937
+        return new \DateTime($data['marker_datetime']);
938
+    }
939
+
940
+    /**
941
+     * deletes the read markers on the specified object
942
+     *
943
+     * @param string $objectType
944
+     * @param string $objectId
945
+     * @return bool
946
+     * @since 9.0.0
947
+     */
948
+    public function deleteReadMarksOnObject($objectType, $objectId) {
949
+        $this->checkRoleParameters('Object', $objectType, $objectId);
950
+
951
+        $qb = $this->dbConn->getQueryBuilder();
952
+        $query = $qb->delete('comments_read_markers')
953
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
954
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
955
+            ->setParameter('object_type', $objectType)
956
+            ->setParameter('object_id', $objectId);
957
+
958
+        try {
959
+            $affectedRows = $query->execute();
960
+        } catch (DriverException $e) {
961
+            $this->logger->logException($e, ['app' => 'core_comments']);
962
+            return false;
963
+        }
964
+        return ($affectedRows > 0);
965
+    }
966
+
967
+    /**
968
+     * registers an Entity to the manager, so event notifications can be send
969
+     * to consumers of the comments infrastructure
970
+     *
971
+     * @param \Closure $closure
972
+     */
973
+    public function registerEventHandler(\Closure $closure) {
974
+        $this->eventHandlerClosures[] = $closure;
975
+        $this->eventHandlers = [];
976
+    }
977
+
978
+    /**
979
+     * registers a method that resolves an ID to a display name for a given type
980
+     *
981
+     * @param string $type
982
+     * @param \Closure $closure
983
+     * @throws \OutOfBoundsException
984
+     * @since 11.0.0
985
+     *
986
+     * Only one resolver shall be registered per type. Otherwise a
987
+     * \OutOfBoundsException has to thrown.
988
+     */
989
+    public function registerDisplayNameResolver($type, \Closure $closure) {
990
+        if (!is_string($type)) {
991
+            throw new \InvalidArgumentException('String expected.');
992
+        }
993
+        if (isset($this->displayNameResolvers[$type])) {
994
+            throw new \OutOfBoundsException('Displayname resolver for this type already registered');
995
+        }
996
+        $this->displayNameResolvers[$type] = $closure;
997
+    }
998
+
999
+    /**
1000
+     * resolves a given ID of a given Type to a display name.
1001
+     *
1002
+     * @param string $type
1003
+     * @param string $id
1004
+     * @return string
1005
+     * @throws \OutOfBoundsException
1006
+     * @since 11.0.0
1007
+     *
1008
+     * If a provided type was not registered, an \OutOfBoundsException shall
1009
+     * be thrown. It is upon the resolver discretion what to return of the
1010
+     * provided ID is unknown. It must be ensured that a string is returned.
1011
+     */
1012
+    public function resolveDisplayName($type, $id) {
1013
+        if (!is_string($type)) {
1014
+            throw new \InvalidArgumentException('String expected.');
1015
+        }
1016
+        if (!isset($this->displayNameResolvers[$type])) {
1017
+            throw new \OutOfBoundsException('No Displayname resolver for this type registered');
1018
+        }
1019
+        return (string)$this->displayNameResolvers[$type]($id);
1020
+    }
1021
+
1022
+    /**
1023
+     * returns valid, registered entities
1024
+     *
1025
+     * @return \OCP\Comments\ICommentsEventHandler[]
1026
+     */
1027
+    private function getEventHandlers() {
1028
+        if (!empty($this->eventHandlers)) {
1029
+            return $this->eventHandlers;
1030
+        }
1031
+
1032
+        $this->eventHandlers = [];
1033
+        foreach ($this->eventHandlerClosures as $name => $closure) {
1034
+            $entity = $closure();
1035
+            if (!($entity instanceof ICommentsEventHandler)) {
1036
+                throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
1037
+            }
1038
+            $this->eventHandlers[$name] = $entity;
1039
+        }
1040
+
1041
+        return $this->eventHandlers;
1042
+    }
1043
+
1044
+    /**
1045
+     * sends notifications to the registered entities
1046
+     *
1047
+     * @param $eventType
1048
+     * @param IComment $comment
1049
+     */
1050
+    private function sendEvent($eventType, IComment $comment) {
1051
+        $entities = $this->getEventHandlers();
1052
+        $event = new CommentsEvent($eventType, $comment);
1053
+        foreach ($entities as $entity) {
1054
+            $entity->handle($event);
1055
+        }
1056
+    }
1057 1057
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -87,14 +87,14 @@  discard block
 block discarded – undo
87 87
 	 * @return array
88 88
 	 */
89 89
 	protected function normalizeDatabaseData(array $data) {
90
-		$data['id'] = (string)$data['id'];
91
-		$data['parent_id'] = (string)$data['parent_id'];
92
-		$data['topmost_parent_id'] = (string)$data['topmost_parent_id'];
90
+		$data['id'] = (string) $data['id'];
91
+		$data['parent_id'] = (string) $data['parent_id'];
92
+		$data['topmost_parent_id'] = (string) $data['topmost_parent_id'];
93 93
 		$data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
94 94
 		if (!is_null($data['latest_child_timestamp'])) {
95 95
 			$data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
96 96
 		}
97
-		$data['children_count'] = (int)$data['children_count'];
97
+		$data['children_count'] = (int) $data['children_count'];
98 98
 		return $data;
99 99
 	}
100 100
 
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 		$resultStatement = $query->execute();
172 172
 		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
173 173
 		$resultStatement->closeCursor();
174
-		$children = (int)$data[0];
174
+		$children = (int) $data[0];
175 175
 
176 176
 		$comment = $this->get($id);
177 177
 		$comment->setChildrenCount($children);
@@ -193,7 +193,7 @@  discard block
 block discarded – undo
193 193
 			!is_string($type) || empty($type)
194 194
 			|| !is_string($id) || empty($id)
195 195
 		) {
196
-			throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
196
+			throw new \InvalidArgumentException($role.' parameters must be string and not empty');
197 197
 		}
198 198
 	}
199 199
 
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
 		if (empty($id)) {
208 208
 			return;
209 209
 		}
210
-		$this->commentsCache[(string)$id] = $comment;
210
+		$this->commentsCache[(string) $id] = $comment;
211 211
 	}
212 212
 
213 213
 	/**
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
 	 * @param mixed $id the comment's id
217 217
 	 */
218 218
 	protected function uncache($id) {
219
-		$id = (string)$id;
219
+		$id = (string) $id;
220 220
 		if (isset($this->commentsCache[$id])) {
221 221
 			unset($this->commentsCache[$id]);
222 222
 		}
@@ -232,7 +232,7 @@  discard block
 block discarded – undo
232 232
 	 * @since 9.0.0
233 233
 	 */
234 234
 	public function get($id) {
235
-		if ((int)$id === 0) {
235
+		if ((int) $id === 0) {
236 236
 			throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
237 237
 		}
238 238
 
@@ -510,7 +510,7 @@  discard block
 block discarded – undo
510 510
 		$query->select('*')
511 511
 			->from('comments')
512 512
 			->where($query->expr()->iLike('message', $query->createNamedParameter(
513
-				'%' . $this->dbConn->escapeLikeParameter($search). '%'
513
+				'%'.$this->dbConn->escapeLikeParameter($search).'%'
514 514
 			)))
515 515
 			->orderBy('creation_timestamp', 'DESC')
516 516
 			->addOrderBy('id', 'DESC')
@@ -572,7 +572,7 @@  discard block
 block discarded – undo
572 572
 		$resultStatement = $query->execute();
573 573
 		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
574 574
 		$resultStatement->closeCursor();
575
-		return (int)$data[0];
575
+		return (int) $data[0];
576 576
 	}
577 577
 
578 578
 	/**
@@ -736,7 +736,7 @@  discard block
 block discarded – undo
736 736
 			->execute();
737 737
 
738 738
 		if ($affectedRows > 0) {
739
-			$comment->setId((string)$qb->getLastInsertId());
739
+			$comment->setId((string) $qb->getLastInsertId());
740 740
 			$this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
741 741
 		}
742 742
 
@@ -1016,7 +1016,7 @@  discard block
 block discarded – undo
1016 1016
 		if (!isset($this->displayNameResolvers[$type])) {
1017 1017
 			throw new \OutOfBoundsException('No Displayname resolver for this type registered');
1018 1018
 		}
1019
-		return (string)$this->displayNameResolvers[$type]($id);
1019
+		return (string) $this->displayNameResolvers[$type]($id);
1020 1020
 	}
1021 1021
 
1022 1022
 	/**
Please login to merge, or discard this patch.
lib/public/DB/QueryBuilder/IFunctionBuilder.php 1 patch
Indentation   +69 added lines, -69 removed lines patch added patch discarded remove patch
@@ -29,80 +29,80 @@
 block discarded – undo
29 29
  * @since 12.0.0
30 30
  */
31 31
 interface IFunctionBuilder {
32
-	/**
33
-	 * Calculates the MD5 hash of a given input
34
-	 *
35
-	 * @param mixed $input The input to be hashed
36
-	 *
37
-	 * @return IQueryFunction
38
-	 * @since 12.0.0
39
-	 */
40
-	public function md5($input);
32
+    /**
33
+     * Calculates the MD5 hash of a given input
34
+     *
35
+     * @param mixed $input The input to be hashed
36
+     *
37
+     * @return IQueryFunction
38
+     * @since 12.0.0
39
+     */
40
+    public function md5($input);
41 41
 
42
-	/**
43
-	 * Combines two input strings
44
-	 *
45
-	 * @param mixed $x The first input string
46
-	 * @param mixed $y The seccond input string
47
-	 *
48
-	 * @return IQueryFunction
49
-	 * @since 12.0.0
50
-	 */
51
-	public function concat($x, $y);
42
+    /**
43
+     * Combines two input strings
44
+     *
45
+     * @param mixed $x The first input string
46
+     * @param mixed $y The seccond input string
47
+     *
48
+     * @return IQueryFunction
49
+     * @since 12.0.0
50
+     */
51
+    public function concat($x, $y);
52 52
 
53
-	/**
54
-	 * Takes a substring from the input string
55
-	 *
56
-	 * @param mixed $input The input string
57
-	 * @param mixed $start The start of the substring, note that counting starts at 1
58
-	 * @param mixed $length The length of the substring
59
-	 *
60
-	 * @return IQueryFunction
61
-	 * @since 12.0.0
62
-	 */
63
-	public function substring($input, $start, $length = null);
53
+    /**
54
+     * Takes a substring from the input string
55
+     *
56
+     * @param mixed $input The input string
57
+     * @param mixed $start The start of the substring, note that counting starts at 1
58
+     * @param mixed $length The length of the substring
59
+     *
60
+     * @return IQueryFunction
61
+     * @since 12.0.0
62
+     */
63
+    public function substring($input, $start, $length = null);
64 64
 
65
-	/**
66
-	 * Takes the sum of all rows in a column
67
-	 *
68
-	 * @param mixed $field the column to sum
69
-	 *
70
-	 * @return IQueryFunction
71
-	 * @since 12.0.0
72
-	 */
73
-	public function sum($field);
65
+    /**
66
+     * Takes the sum of all rows in a column
67
+     *
68
+     * @param mixed $field the column to sum
69
+     *
70
+     * @return IQueryFunction
71
+     * @since 12.0.0
72
+     */
73
+    public function sum($field);
74 74
 
75
-	/**
76
-	 * Transforms a string field or value to lower case
77
-	 *
78
-	 * @param mixed $field
79
-	 * @return IQueryFunction
80
-	 * @since 14.0.0
81
-	 */
82
-	public function lower($field);
75
+    /**
76
+     * Transforms a string field or value to lower case
77
+     *
78
+     * @param mixed $field
79
+     * @return IQueryFunction
80
+     * @since 14.0.0
81
+     */
82
+    public function lower($field);
83 83
 
84
-	/**
85
-	 * @param mixed $x The first input field or number
86
-	 * @param mixed $y The second input field or number
87
-	 * @return IQueryFunction
88
-	 * @since 14.0.0
89
-	 */
90
-	public function add($x, $y);
84
+    /**
85
+     * @param mixed $x The first input field or number
86
+     * @param mixed $y The second input field or number
87
+     * @return IQueryFunction
88
+     * @since 14.0.0
89
+     */
90
+    public function add($x, $y);
91 91
 
92
-	/**
93
-	 * @param mixed $x The first input field or number
94
-	 * @param mixed $y The second input field or number
95
-	 * @return IQueryFunction
96
-	 * @since 14.0.0
97
-	 */
98
-	public function subtract($x, $y);
92
+    /**
93
+     * @param mixed $x The first input field or number
94
+     * @param mixed $y The second input field or number
95
+     * @return IQueryFunction
96
+     * @since 14.0.0
97
+     */
98
+    public function subtract($x, $y);
99 99
 
100
-	/**
101
-	 * @param mixed $count The input to be counted
102
-	 * @param string $alias Alias for the counter
103
-	 *
104
-	 * @return IQueryFunction
105
-	 * @since 14.0.0
106
-	 */
107
-	public function count($count, $alias = '');
100
+    /**
101
+     * @param mixed $count The input to be counted
102
+     * @param string $alias Alias for the counter
103
+     *
104
+     * @return IQueryFunction
105
+     * @since 14.0.0
106
+     */
107
+    public function count($count, $alias = '');
108 108
 }
Please login to merge, or discard this patch.
apps/dav/lib/CardDAV/CardDavBackend.php 1 patch
Indentation   +1110 added lines, -1110 removed lines patch added patch discarded remove patch
@@ -53,1114 +53,1114 @@
 block discarded – undo
53 53
 
54 54
 class CardDavBackend implements BackendInterface, SyncSupport {
55 55
 
56
-	const PERSONAL_ADDRESSBOOK_URI = 'contacts';
57
-	const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
58
-
59
-	/** @var Principal */
60
-	private $principalBackend;
61
-
62
-	/** @var string */
63
-	private $dbCardsTable = 'cards';
64
-
65
-	/** @var string */
66
-	private $dbCardsPropertiesTable = 'cards_properties';
67
-
68
-	/** @var IDBConnection */
69
-	private $db;
70
-
71
-	/** @var Backend */
72
-	private $sharingBackend;
73
-
74
-	/** @var array properties to index */
75
-	public static $indexProperties = array(
76
-			'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
77
-			'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
78
-
79
-	/**
80
-	 * @var string[] Map of uid => display name
81
-	 */
82
-	protected $userDisplayNames;
83
-
84
-	/** @var IUserManager */
85
-	private $userManager;
86
-
87
-	/** @var EventDispatcherInterface */
88
-	private $dispatcher;
89
-
90
-	/**
91
-	 * CardDavBackend constructor.
92
-	 *
93
-	 * @param IDBConnection $db
94
-	 * @param Principal $principalBackend
95
-	 * @param IUserManager $userManager
96
-	 * @param IGroupManager $groupManager
97
-	 * @param EventDispatcherInterface $dispatcher
98
-	 */
99
-	public function __construct(IDBConnection $db,
100
-								Principal $principalBackend,
101
-								IUserManager $userManager,
102
-								IGroupManager $groupManager,
103
-								EventDispatcherInterface $dispatcher) {
104
-		$this->db = $db;
105
-		$this->principalBackend = $principalBackend;
106
-		$this->userManager = $userManager;
107
-		$this->dispatcher = $dispatcher;
108
-		$this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook');
109
-	}
110
-
111
-	/**
112
-	 * Return the number of address books for a principal
113
-	 *
114
-	 * @param $principalUri
115
-	 * @return int
116
-	 */
117
-	public function getAddressBooksForUserCount($principalUri) {
118
-		$principalUri = $this->convertPrincipal($principalUri, true);
119
-		$query = $this->db->getQueryBuilder();
120
-		$query->select($query->func()->count('*'))
121
-			->from('addressbooks')
122
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
123
-
124
-		return (int)$query->execute()->fetchColumn();
125
-	}
126
-
127
-	/**
128
-	 * Returns the list of address books for a specific user.
129
-	 *
130
-	 * Every addressbook should have the following properties:
131
-	 *   id - an arbitrary unique id
132
-	 *   uri - the 'basename' part of the url
133
-	 *   principaluri - Same as the passed parameter
134
-	 *
135
-	 * Any additional clark-notation property may be passed besides this. Some
136
-	 * common ones are :
137
-	 *   {DAV:}displayname
138
-	 *   {urn:ietf:params:xml:ns:carddav}addressbook-description
139
-	 *   {http://calendarserver.org/ns/}getctag
140
-	 *
141
-	 * @param string $principalUri
142
-	 * @return array
143
-	 */
144
-	function getAddressBooksForUser($principalUri) {
145
-		$principalUriOriginal = $principalUri;
146
-		$principalUri = $this->convertPrincipal($principalUri, true);
147
-		$query = $this->db->getQueryBuilder();
148
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
149
-			->from('addressbooks')
150
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
151
-
152
-		$addressBooks = [];
153
-
154
-		$result = $query->execute();
155
-		while($row = $result->fetch()) {
156
-			$addressBooks[$row['id']] = [
157
-				'id'  => $row['id'],
158
-				'uri' => $row['uri'],
159
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
160
-				'{DAV:}displayname' => $row['displayname'],
161
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
162
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
163
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
164
-			];
165
-
166
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
167
-		}
168
-		$result->closeCursor();
169
-
170
-		// query for shared calendars
171
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
172
-		$principals = array_map(function($principal) {
173
-			return urldecode($principal);
174
-		}, $principals);
175
-		$principals[]= $principalUri;
176
-
177
-		$query = $this->db->getQueryBuilder();
178
-		$result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
179
-			->from('dav_shares', 's')
180
-			->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
181
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
182
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
183
-			->setParameter('type', 'addressbook')
184
-			->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
185
-			->execute();
186
-
187
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
188
-		while($row = $result->fetch()) {
189
-			if ($row['principaluri'] === $principalUri) {
190
-				continue;
191
-			}
192
-
193
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
194
-			if (isset($addressBooks[$row['id']])) {
195
-				if ($readOnly) {
196
-					// New share can not have more permissions then the old one.
197
-					continue;
198
-				}
199
-				if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
200
-					$addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
201
-					// Old share is already read-write, no more permissions can be gained
202
-					continue;
203
-				}
204
-			}
205
-
206
-			list(, $name) = \Sabre\Uri\split($row['principaluri']);
207
-			$uri = $row['uri'] . '_shared_by_' . $name;
208
-			$displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
209
-
210
-			$addressBooks[$row['id']] = [
211
-				'id'  => $row['id'],
212
-				'uri' => $uri,
213
-				'principaluri' => $principalUriOriginal,
214
-				'{DAV:}displayname' => $displayName,
215
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
216
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
217
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
218
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
219
-				$readOnlyPropertyName => $readOnly,
220
-			];
221
-
222
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
223
-		}
224
-		$result->closeCursor();
225
-
226
-		return array_values($addressBooks);
227
-	}
228
-
229
-	public function getUsersOwnAddressBooks($principalUri) {
230
-		$principalUri = $this->convertPrincipal($principalUri, true);
231
-		$query = $this->db->getQueryBuilder();
232
-		$query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
233
-			  ->from('addressbooks')
234
-			  ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
235
-
236
-		$addressBooks = [];
237
-
238
-		$result = $query->execute();
239
-		while($row = $result->fetch()) {
240
-			$addressBooks[$row['id']] = [
241
-				'id'  => $row['id'],
242
-				'uri' => $row['uri'],
243
-				'principaluri' => $this->convertPrincipal($row['principaluri'], false),
244
-				'{DAV:}displayname' => $row['displayname'],
245
-				'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
246
-				'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
247
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
248
-			];
249
-
250
-			$this->addOwnerPrincipal($addressBooks[$row['id']]);
251
-		}
252
-		$result->closeCursor();
253
-
254
-		return array_values($addressBooks);
255
-	}
256
-
257
-	private function getUserDisplayName($uid) {
258
-		if (!isset($this->userDisplayNames[$uid])) {
259
-			$user = $this->userManager->get($uid);
260
-
261
-			if ($user instanceof IUser) {
262
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
263
-			} else {
264
-				$this->userDisplayNames[$uid] = $uid;
265
-			}
266
-		}
267
-
268
-		return $this->userDisplayNames[$uid];
269
-	}
270
-
271
-	/**
272
-	 * @param int $addressBookId
273
-	 */
274
-	public function getAddressBookById($addressBookId) {
275
-		$query = $this->db->getQueryBuilder();
276
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
277
-			->from('addressbooks')
278
-			->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
279
-			->execute();
280
-
281
-		$row = $result->fetch();
282
-		$result->closeCursor();
283
-		if ($row === false) {
284
-			return null;
285
-		}
286
-
287
-		$addressBook = [
288
-			'id'  => $row['id'],
289
-			'uri' => $row['uri'],
290
-			'principaluri' => $row['principaluri'],
291
-			'{DAV:}displayname' => $row['displayname'],
292
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
293
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
294
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
295
-		];
296
-
297
-		$this->addOwnerPrincipal($addressBook);
298
-
299
-		return $addressBook;
300
-	}
301
-
302
-	/**
303
-	 * @param $addressBookUri
304
-	 * @return array|null
305
-	 */
306
-	public function getAddressBooksByUri($principal, $addressBookUri) {
307
-		$query = $this->db->getQueryBuilder();
308
-		$result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
309
-			->from('addressbooks')
310
-			->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
311
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
312
-			->setMaxResults(1)
313
-			->execute();
314
-
315
-		$row = $result->fetch();
316
-		$result->closeCursor();
317
-		if ($row === false) {
318
-			return null;
319
-		}
320
-
321
-		$addressBook = [
322
-			'id'  => $row['id'],
323
-			'uri' => $row['uri'],
324
-			'principaluri' => $row['principaluri'],
325
-			'{DAV:}displayname' => $row['displayname'],
326
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
327
-			'{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
328
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
329
-		];
330
-
331
-		$this->addOwnerPrincipal($addressBook);
332
-
333
-		return $addressBook;
334
-	}
335
-
336
-	/**
337
-	 * Updates properties for an address book.
338
-	 *
339
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
340
-	 * To do the actual updates, you must tell this object which properties
341
-	 * you're going to process with the handle() method.
342
-	 *
343
-	 * Calling the handle method is like telling the PropPatch object "I
344
-	 * promise I can handle updating this property".
345
-	 *
346
-	 * Read the PropPatch documentation for more info and examples.
347
-	 *
348
-	 * @param string $addressBookId
349
-	 * @param \Sabre\DAV\PropPatch $propPatch
350
-	 * @return void
351
-	 */
352
-	function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
353
-		$supportedProperties = [
354
-			'{DAV:}displayname',
355
-			'{' . Plugin::NS_CARDDAV . '}addressbook-description',
356
-		];
357
-
358
-		/**
359
-		 * @suppress SqlInjectionChecker
360
-		 */
361
-		$propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
362
-
363
-			$updates = [];
364
-			foreach($mutations as $property=>$newValue) {
365
-
366
-				switch($property) {
367
-					case '{DAV:}displayname' :
368
-						$updates['displayname'] = $newValue;
369
-						break;
370
-					case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
371
-						$updates['description'] = $newValue;
372
-						break;
373
-				}
374
-			}
375
-			$query = $this->db->getQueryBuilder();
376
-			$query->update('addressbooks');
377
-
378
-			foreach($updates as $key=>$value) {
379
-				$query->set($key, $query->createNamedParameter($value));
380
-			}
381
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
382
-			->execute();
383
-
384
-			$this->addChange($addressBookId, "", 2);
385
-
386
-			return true;
387
-
388
-		});
389
-	}
390
-
391
-	/**
392
-	 * Creates a new address book
393
-	 *
394
-	 * @param string $principalUri
395
-	 * @param string $url Just the 'basename' of the url.
396
-	 * @param array $properties
397
-	 * @return int
398
-	 * @throws BadRequest
399
-	 */
400
-	function createAddressBook($principalUri, $url, array $properties) {
401
-		$values = [
402
-			'displayname' => null,
403
-			'description' => null,
404
-			'principaluri' => $principalUri,
405
-			'uri' => $url,
406
-			'synctoken' => 1
407
-		];
408
-
409
-		foreach($properties as $property=>$newValue) {
410
-
411
-			switch($property) {
412
-				case '{DAV:}displayname' :
413
-					$values['displayname'] = $newValue;
414
-					break;
415
-				case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
416
-					$values['description'] = $newValue;
417
-					break;
418
-				default :
419
-					throw new BadRequest('Unknown property: ' . $property);
420
-			}
421
-
422
-		}
423
-
424
-		// Fallback to make sure the displayname is set. Some clients may refuse
425
-		// to work with addressbooks not having a displayname.
426
-		if(is_null($values['displayname'])) {
427
-			$values['displayname'] = $url;
428
-		}
429
-
430
-		$query = $this->db->getQueryBuilder();
431
-		$query->insert('addressbooks')
432
-			->values([
433
-				'uri' => $query->createParameter('uri'),
434
-				'displayname' => $query->createParameter('displayname'),
435
-				'description' => $query->createParameter('description'),
436
-				'principaluri' => $query->createParameter('principaluri'),
437
-				'synctoken' => $query->createParameter('synctoken'),
438
-			])
439
-			->setParameters($values)
440
-			->execute();
441
-
442
-		return $query->getLastInsertId();
443
-	}
444
-
445
-	/**
446
-	 * Deletes an entire addressbook and all its contents
447
-	 *
448
-	 * @param mixed $addressBookId
449
-	 * @return void
450
-	 */
451
-	function deleteAddressBook($addressBookId) {
452
-		$query = $this->db->getQueryBuilder();
453
-		$query->delete('cards')
454
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
455
-			->setParameter('addressbookid', $addressBookId)
456
-			->execute();
457
-
458
-		$query->delete('addressbookchanges')
459
-			->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
460
-			->setParameter('addressbookid', $addressBookId)
461
-			->execute();
462
-
463
-		$query->delete('addressbooks')
464
-			->where($query->expr()->eq('id', $query->createParameter('id')))
465
-			->setParameter('id', $addressBookId)
466
-			->execute();
467
-
468
-		$this->sharingBackend->deleteAllShares($addressBookId);
469
-
470
-		$query->delete($this->dbCardsPropertiesTable)
471
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
472
-			->execute();
473
-
474
-	}
475
-
476
-	/**
477
-	 * Returns all cards for a specific addressbook id.
478
-	 *
479
-	 * This method should return the following properties for each card:
480
-	 *   * carddata - raw vcard data
481
-	 *   * uri - Some unique url
482
-	 *   * lastmodified - A unix timestamp
483
-	 *
484
-	 * It's recommended to also return the following properties:
485
-	 *   * etag - A unique etag. This must change every time the card changes.
486
-	 *   * size - The size of the card in bytes.
487
-	 *
488
-	 * If these last two properties are provided, less time will be spent
489
-	 * calculating them. If they are specified, you can also ommit carddata.
490
-	 * This may speed up certain requests, especially with large cards.
491
-	 *
492
-	 * @param mixed $addressBookId
493
-	 * @return array
494
-	 */
495
-	function getCards($addressBookId) {
496
-		$query = $this->db->getQueryBuilder();
497
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
498
-			->from('cards')
499
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
500
-
501
-		$cards = [];
502
-
503
-		$result = $query->execute();
504
-		while($row = $result->fetch()) {
505
-			$row['etag'] = '"' . $row['etag'] . '"';
506
-			$row['carddata'] = $this->readBlob($row['carddata']);
507
-			$cards[] = $row;
508
-		}
509
-		$result->closeCursor();
510
-
511
-		return $cards;
512
-	}
513
-
514
-	/**
515
-	 * Returns a specific card.
516
-	 *
517
-	 * The same set of properties must be returned as with getCards. The only
518
-	 * exception is that 'carddata' is absolutely required.
519
-	 *
520
-	 * If the card does not exist, you must return false.
521
-	 *
522
-	 * @param mixed $addressBookId
523
-	 * @param string $cardUri
524
-	 * @return array
525
-	 */
526
-	function getCard($addressBookId, $cardUri) {
527
-		$query = $this->db->getQueryBuilder();
528
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
529
-			->from('cards')
530
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
531
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
532
-			->setMaxResults(1);
533
-
534
-		$result = $query->execute();
535
-		$row = $result->fetch();
536
-		if (!$row) {
537
-			return false;
538
-		}
539
-		$row['etag'] = '"' . $row['etag'] . '"';
540
-		$row['carddata'] = $this->readBlob($row['carddata']);
541
-
542
-		return $row;
543
-	}
544
-
545
-	/**
546
-	 * Returns a list of cards.
547
-	 *
548
-	 * This method should work identical to getCard, but instead return all the
549
-	 * cards in the list as an array.
550
-	 *
551
-	 * If the backend supports this, it may allow for some speed-ups.
552
-	 *
553
-	 * @param mixed $addressBookId
554
-	 * @param string[] $uris
555
-	 * @return array
556
-	 */
557
-	function getMultipleCards($addressBookId, array $uris) {
558
-		if (empty($uris)) {
559
-			return [];
560
-		}
561
-
562
-		$chunks = array_chunk($uris, 100);
563
-		$cards = [];
564
-
565
-		$query = $this->db->getQueryBuilder();
566
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
567
-			->from('cards')
568
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
569
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
570
-
571
-		foreach ($chunks as $uris) {
572
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
573
-			$result = $query->execute();
574
-
575
-			while ($row = $result->fetch()) {
576
-				$row['etag'] = '"' . $row['etag'] . '"';
577
-				$row['carddata'] = $this->readBlob($row['carddata']);
578
-				$cards[] = $row;
579
-			}
580
-			$result->closeCursor();
581
-		}
582
-		return $cards;
583
-	}
584
-
585
-	/**
586
-	 * Creates a new card.
587
-	 *
588
-	 * The addressbook id will be passed as the first argument. This is the
589
-	 * same id as it is returned from the getAddressBooksForUser method.
590
-	 *
591
-	 * The cardUri is a base uri, and doesn't include the full path. The
592
-	 * cardData argument is the vcard body, and is passed as a string.
593
-	 *
594
-	 * It is possible to return an ETag from this method. This ETag is for the
595
-	 * newly created resource, and must be enclosed with double quotes (that
596
-	 * is, the string itself must contain the double quotes).
597
-	 *
598
-	 * You should only return the ETag if you store the carddata as-is. If a
599
-	 * subsequent GET request on the same card does not have the same body,
600
-	 * byte-by-byte and you did return an ETag here, clients tend to get
601
-	 * confused.
602
-	 *
603
-	 * If you don't return an ETag, you can just return null.
604
-	 *
605
-	 * @param mixed $addressBookId
606
-	 * @param string $cardUri
607
-	 * @param string $cardData
608
-	 * @return string
609
-	 */
610
-	function createCard($addressBookId, $cardUri, $cardData) {
611
-		$etag = md5($cardData);
612
-		$uid = $this->getUID($cardData);
613
-
614
-		$q = $this->db->getQueryBuilder();
615
-		$q->select('uid')
616
-			->from('cards')
617
-			->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId)))
618
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
619
-			->setMaxResults(1);
620
-		$result = $q->execute();
621
-		$count = (bool) $result->fetchColumn();
622
-		$result->closeCursor();
623
-		if ($count) {
624
-			throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
625
-		}
626
-
627
-		$query = $this->db->getQueryBuilder();
628
-		$query->insert('cards')
629
-			->values([
630
-				'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
631
-				'uri' => $query->createNamedParameter($cardUri),
632
-				'lastmodified' => $query->createNamedParameter(time()),
633
-				'addressbookid' => $query->createNamedParameter($addressBookId),
634
-				'size' => $query->createNamedParameter(strlen($cardData)),
635
-				'etag' => $query->createNamedParameter($etag),
636
-				'uid' => $query->createNamedParameter($uid),
637
-			])
638
-			->execute();
639
-
640
-		$this->addChange($addressBookId, $cardUri, 1);
641
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
642
-
643
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
644
-			new GenericEvent(null, [
645
-				'addressBookId' => $addressBookId,
646
-				'cardUri' => $cardUri,
647
-				'cardData' => $cardData]));
648
-
649
-		return '"' . $etag . '"';
650
-	}
651
-
652
-	/**
653
-	 * Updates a card.
654
-	 *
655
-	 * The addressbook id will be passed as the first argument. This is the
656
-	 * same id as it is returned from the getAddressBooksForUser method.
657
-	 *
658
-	 * The cardUri is a base uri, and doesn't include the full path. The
659
-	 * cardData argument is the vcard body, and is passed as a string.
660
-	 *
661
-	 * It is possible to return an ETag from this method. This ETag should
662
-	 * match that of the updated resource, and must be enclosed with double
663
-	 * quotes (that is: the string itself must contain the actual quotes).
664
-	 *
665
-	 * You should only return the ETag if you store the carddata as-is. If a
666
-	 * subsequent GET request on the same card does not have the same body,
667
-	 * byte-by-byte and you did return an ETag here, clients tend to get
668
-	 * confused.
669
-	 *
670
-	 * If you don't return an ETag, you can just return null.
671
-	 *
672
-	 * @param mixed $addressBookId
673
-	 * @param string $cardUri
674
-	 * @param string $cardData
675
-	 * @return string
676
-	 */
677
-	function updateCard($addressBookId, $cardUri, $cardData) {
678
-
679
-		$uid = $this->getUID($cardData);
680
-		$etag = md5($cardData);
681
-		$query = $this->db->getQueryBuilder();
682
-		$query->update('cards')
683
-			->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
684
-			->set('lastmodified', $query->createNamedParameter(time()))
685
-			->set('size', $query->createNamedParameter(strlen($cardData)))
686
-			->set('etag', $query->createNamedParameter($etag))
687
-			->set('uid', $query->createNamedParameter($uid))
688
-			->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
689
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
690
-			->execute();
691
-
692
-		$this->addChange($addressBookId, $cardUri, 2);
693
-		$this->updateProperties($addressBookId, $cardUri, $cardData);
694
-
695
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
696
-			new GenericEvent(null, [
697
-				'addressBookId' => $addressBookId,
698
-				'cardUri' => $cardUri,
699
-				'cardData' => $cardData]));
700
-
701
-		return '"' . $etag . '"';
702
-	}
703
-
704
-	/**
705
-	 * Deletes a card
706
-	 *
707
-	 * @param mixed $addressBookId
708
-	 * @param string $cardUri
709
-	 * @return bool
710
-	 */
711
-	function deleteCard($addressBookId, $cardUri) {
712
-		try {
713
-			$cardId = $this->getCardId($addressBookId, $cardUri);
714
-		} catch (\InvalidArgumentException $e) {
715
-			$cardId = null;
716
-		}
717
-		$query = $this->db->getQueryBuilder();
718
-		$ret = $query->delete('cards')
719
-			->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
720
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
721
-			->execute();
722
-
723
-		$this->addChange($addressBookId, $cardUri, 3);
724
-
725
-		$this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
726
-			new GenericEvent(null, [
727
-				'addressBookId' => $addressBookId,
728
-				'cardUri' => $cardUri]));
729
-
730
-		if ($ret === 1) {
731
-			if ($cardId !== null) {
732
-				$this->purgeProperties($addressBookId, $cardId);
733
-			}
734
-			return true;
735
-		}
736
-
737
-		return false;
738
-	}
739
-
740
-	/**
741
-	 * The getChanges method returns all the changes that have happened, since
742
-	 * the specified syncToken in the specified address book.
743
-	 *
744
-	 * This function should return an array, such as the following:
745
-	 *
746
-	 * [
747
-	 *   'syncToken' => 'The current synctoken',
748
-	 *   'added'   => [
749
-	 *      'new.txt',
750
-	 *   ],
751
-	 *   'modified'   => [
752
-	 *      'modified.txt',
753
-	 *   ],
754
-	 *   'deleted' => [
755
-	 *      'foo.php.bak',
756
-	 *      'old.txt'
757
-	 *   ]
758
-	 * ];
759
-	 *
760
-	 * The returned syncToken property should reflect the *current* syncToken
761
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
762
-	 * property. This is needed here too, to ensure the operation is atomic.
763
-	 *
764
-	 * If the $syncToken argument is specified as null, this is an initial
765
-	 * sync, and all members should be reported.
766
-	 *
767
-	 * The modified property is an array of nodenames that have changed since
768
-	 * the last token.
769
-	 *
770
-	 * The deleted property is an array with nodenames, that have been deleted
771
-	 * from collection.
772
-	 *
773
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
774
-	 * 1, you only have to report changes that happened only directly in
775
-	 * immediate descendants. If it's 2, it should also include changes from
776
-	 * the nodes below the child collections. (grandchildren)
777
-	 *
778
-	 * The $limit argument allows a client to specify how many results should
779
-	 * be returned at most. If the limit is not specified, it should be treated
780
-	 * as infinite.
781
-	 *
782
-	 * If the limit (infinite or not) is higher than you're willing to return,
783
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
784
-	 *
785
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
786
-	 * return null.
787
-	 *
788
-	 * The limit is 'suggestive'. You are free to ignore it.
789
-	 *
790
-	 * @param string $addressBookId
791
-	 * @param string $syncToken
792
-	 * @param int $syncLevel
793
-	 * @param int $limit
794
-	 * @return array
795
-	 */
796
-	function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
797
-		// Current synctoken
798
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
799
-		$stmt->execute([ $addressBookId ]);
800
-		$currentToken = $stmt->fetchColumn(0);
801
-
802
-		if (is_null($currentToken)) return null;
803
-
804
-		$result = [
805
-			'syncToken' => $currentToken,
806
-			'added'     => [],
807
-			'modified'  => [],
808
-			'deleted'   => [],
809
-		];
810
-
811
-		if ($syncToken) {
812
-
813
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
814
-			if ($limit>0) {
815
-				$query .= " `LIMIT` " . (int)$limit;
816
-			}
817
-
818
-			// Fetching all changes
819
-			$stmt = $this->db->prepare($query);
820
-			$stmt->execute([$syncToken, $currentToken, $addressBookId]);
821
-
822
-			$changes = [];
823
-
824
-			// This loop ensures that any duplicates are overwritten, only the
825
-			// last change on a node is relevant.
826
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
827
-
828
-				$changes[$row['uri']] = $row['operation'];
829
-
830
-			}
831
-
832
-			foreach($changes as $uri => $operation) {
833
-
834
-				switch($operation) {
835
-					case 1:
836
-						$result['added'][] = $uri;
837
-						break;
838
-					case 2:
839
-						$result['modified'][] = $uri;
840
-						break;
841
-					case 3:
842
-						$result['deleted'][] = $uri;
843
-						break;
844
-				}
845
-
846
-			}
847
-		} else {
848
-			// No synctoken supplied, this is the initial sync.
849
-			$query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
850
-			$stmt = $this->db->prepare($query);
851
-			$stmt->execute([$addressBookId]);
852
-
853
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
854
-		}
855
-		return $result;
856
-	}
857
-
858
-	/**
859
-	 * Adds a change record to the addressbookchanges table.
860
-	 *
861
-	 * @param mixed $addressBookId
862
-	 * @param string $objectUri
863
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete
864
-	 * @return void
865
-	 */
866
-	protected function addChange($addressBookId, $objectUri, $operation) {
867
-		$sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
868
-		$stmt = $this->db->prepare($sql);
869
-		$stmt->execute([
870
-			$objectUri,
871
-			$addressBookId,
872
-			$operation,
873
-			$addressBookId
874
-		]);
875
-		$stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
876
-		$stmt->execute([
877
-			$addressBookId
878
-		]);
879
-	}
880
-
881
-	private function readBlob($cardData) {
882
-		if (is_resource($cardData)) {
883
-			return stream_get_contents($cardData);
884
-		}
885
-
886
-		return $cardData;
887
-	}
888
-
889
-	/**
890
-	 * @param IShareable $shareable
891
-	 * @param string[] $add
892
-	 * @param string[] $remove
893
-	 */
894
-	public function updateShares(IShareable $shareable, $add, $remove) {
895
-		$this->sharingBackend->updateShares($shareable, $add, $remove);
896
-	}
897
-
898
-	/**
899
-	 * search contact
900
-	 *
901
-	 * @param int $addressBookId
902
-	 * @param string $pattern which should match within the $searchProperties
903
-	 * @param array $searchProperties defines the properties within the query pattern should match
904
-	 * @return array an array of contacts which are arrays of key-value-pairs
905
-	 */
906
-	public function search($addressBookId, $pattern, $searchProperties) {
907
-		$query = $this->db->getQueryBuilder();
908
-		$query2 = $this->db->getQueryBuilder();
909
-
910
-		$query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
911
-		$query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
912
-		$or = $query2->expr()->orX();
913
-		foreach ($searchProperties as $property) {
914
-			$or->add($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
915
-		}
916
-		$query2->andWhere($or);
917
-
918
-		// No need for like when the pattern is empty
919
-		if ('' !== $pattern) {
920
-			$query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
921
-		}
922
-
923
-		$query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
924
-			->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
925
-
926
-		$result = $query->execute();
927
-		$cards = $result->fetchAll();
928
-
929
-		$result->closeCursor();
930
-
931
-		return array_map(function($array) {
932
-			$array['carddata'] = $this->readBlob($array['carddata']);
933
-			return $array;
934
-		}, $cards);
935
-	}
936
-
937
-	/**
938
-	 * @param int $bookId
939
-	 * @param string $name
940
-	 * @return array
941
-	 */
942
-	public function collectCardProperties($bookId, $name) {
943
-		$query = $this->db->getQueryBuilder();
944
-		$result = $query->selectDistinct('value')
945
-			->from($this->dbCardsPropertiesTable)
946
-			->where($query->expr()->eq('name', $query->createNamedParameter($name)))
947
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
948
-			->execute();
949
-
950
-		$all = $result->fetchAll(PDO::FETCH_COLUMN);
951
-		$result->closeCursor();
952
-
953
-		return $all;
954
-	}
955
-
956
-	/**
957
-	 * get URI from a given contact
958
-	 *
959
-	 * @param int $id
960
-	 * @return string
961
-	 */
962
-	public function getCardUri($id) {
963
-		$query = $this->db->getQueryBuilder();
964
-		$query->select('uri')->from($this->dbCardsTable)
965
-				->where($query->expr()->eq('id', $query->createParameter('id')))
966
-				->setParameter('id', $id);
967
-
968
-		$result = $query->execute();
969
-		$uri = $result->fetch();
970
-		$result->closeCursor();
971
-
972
-		if (!isset($uri['uri'])) {
973
-			throw new \InvalidArgumentException('Card does not exists: ' . $id);
974
-		}
975
-
976
-		return $uri['uri'];
977
-	}
978
-
979
-	/**
980
-	 * return contact with the given URI
981
-	 *
982
-	 * @param int $addressBookId
983
-	 * @param string $uri
984
-	 * @returns array
985
-	 */
986
-	public function getContact($addressBookId, $uri) {
987
-		$result = [];
988
-		$query = $this->db->getQueryBuilder();
989
-		$query->select('*')->from($this->dbCardsTable)
990
-				->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
991
-				->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
992
-		$queryResult = $query->execute();
993
-		$contact = $queryResult->fetch();
994
-		$queryResult->closeCursor();
995
-
996
-		if (is_array($contact)) {
997
-			$result = $contact;
998
-		}
999
-
1000
-		return $result;
1001
-	}
1002
-
1003
-	/**
1004
-	 * Returns the list of people whom this address book is shared with.
1005
-	 *
1006
-	 * Every element in this array should have the following properties:
1007
-	 *   * href - Often a mailto: address
1008
-	 *   * commonName - Optional, for example a first + last name
1009
-	 *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
1010
-	 *   * readOnly - boolean
1011
-	 *   * summary - Optional, a description for the share
1012
-	 *
1013
-	 * @return array
1014
-	 */
1015
-	public function getShares($addressBookId) {
1016
-		return $this->sharingBackend->getShares($addressBookId);
1017
-	}
1018
-
1019
-	/**
1020
-	 * update properties table
1021
-	 *
1022
-	 * @param int $addressBookId
1023
-	 * @param string $cardUri
1024
-	 * @param string $vCardSerialized
1025
-	 */
1026
-	protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
1027
-		$cardId = $this->getCardId($addressBookId, $cardUri);
1028
-		$vCard = $this->readCard($vCardSerialized);
1029
-
1030
-		$this->purgeProperties($addressBookId, $cardId);
1031
-
1032
-		$query = $this->db->getQueryBuilder();
1033
-		$query->insert($this->dbCardsPropertiesTable)
1034
-			->values(
1035
-				[
1036
-					'addressbookid' => $query->createNamedParameter($addressBookId),
1037
-					'cardid' => $query->createNamedParameter($cardId),
1038
-					'name' => $query->createParameter('name'),
1039
-					'value' => $query->createParameter('value'),
1040
-					'preferred' => $query->createParameter('preferred')
1041
-				]
1042
-			);
1043
-
1044
-		foreach ($vCard->children() as $property) {
1045
-			if(!in_array($property->name, self::$indexProperties)) {
1046
-				continue;
1047
-			}
1048
-			$preferred = 0;
1049
-			foreach($property->parameters as $parameter) {
1050
-				if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1051
-					$preferred = 1;
1052
-					break;
1053
-				}
1054
-			}
1055
-			$query->setParameter('name', $property->name);
1056
-			$query->setParameter('value', substr($property->getValue(), 0, 254));
1057
-			$query->setParameter('preferred', $preferred);
1058
-			$query->execute();
1059
-		}
1060
-	}
1061
-
1062
-	/**
1063
-	 * read vCard data into a vCard object
1064
-	 *
1065
-	 * @param string $cardData
1066
-	 * @return VCard
1067
-	 */
1068
-	protected function readCard($cardData) {
1069
-		return  Reader::read($cardData);
1070
-	}
1071
-
1072
-	/**
1073
-	 * delete all properties from a given card
1074
-	 *
1075
-	 * @param int $addressBookId
1076
-	 * @param int $cardId
1077
-	 */
1078
-	protected function purgeProperties($addressBookId, $cardId) {
1079
-		$query = $this->db->getQueryBuilder();
1080
-		$query->delete($this->dbCardsPropertiesTable)
1081
-			->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1082
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1083
-		$query->execute();
1084
-	}
1085
-
1086
-	/**
1087
-	 * get ID from a given contact
1088
-	 *
1089
-	 * @param int $addressBookId
1090
-	 * @param string $uri
1091
-	 * @return int
1092
-	 */
1093
-	protected function getCardId($addressBookId, $uri) {
1094
-		$query = $this->db->getQueryBuilder();
1095
-		$query->select('id')->from($this->dbCardsTable)
1096
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1097
-			->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1098
-
1099
-		$result = $query->execute();
1100
-		$cardIds = $result->fetch();
1101
-		$result->closeCursor();
1102
-
1103
-		if (!isset($cardIds['id'])) {
1104
-			throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1105
-		}
1106
-
1107
-		return (int)$cardIds['id'];
1108
-	}
1109
-
1110
-	/**
1111
-	 * For shared address books the sharee is set in the ACL of the address book
1112
-	 * @param $addressBookId
1113
-	 * @param $acl
1114
-	 * @return array
1115
-	 */
1116
-	public function applyShareAcl($addressBookId, $acl) {
1117
-		return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1118
-	}
1119
-
1120
-	private function convertPrincipal($principalUri, $toV2) {
1121
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1122
-			list(, $name) = \Sabre\Uri\split($principalUri);
1123
-			if ($toV2 === true) {
1124
-				return "principals/users/$name";
1125
-			}
1126
-			return "principals/$name";
1127
-		}
1128
-		return $principalUri;
1129
-	}
1130
-
1131
-	private function addOwnerPrincipal(&$addressbookInfo) {
1132
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1133
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1134
-		if (isset($addressbookInfo[$ownerPrincipalKey])) {
1135
-			$uri = $addressbookInfo[$ownerPrincipalKey];
1136
-		} else {
1137
-			$uri = $addressbookInfo['principaluri'];
1138
-		}
1139
-
1140
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1141
-		if (isset($principalInformation['{DAV:}displayname'])) {
1142
-			$addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1143
-		}
1144
-	}
1145
-
1146
-	/**
1147
-	 * Extract UID from vcard
1148
-	 *
1149
-	 * @param string $cardData the vcard raw data
1150
-	 * @return string the uid
1151
-	 * @throws BadRequest if no UID is available
1152
-	 */
1153
-	private function getUID($cardData) {
1154
-		if ($cardData != '') {
1155
-			$vCard = Reader::read($cardData);
1156
-			if ($vCard->UID) {
1157
-				$uid = $vCard->UID->getValue();
1158
-				return $uid;
1159
-			}
1160
-			// should already be handled, but just in case
1161
-			throw new BadRequest('vCards on CardDAV servers MUST have a UID property');
1162
-		}
1163
-		// should already be handled, but just in case
1164
-		throw new BadRequest('vCard can not be empty');
1165
-	}
56
+    const PERSONAL_ADDRESSBOOK_URI = 'contacts';
57
+    const PERSONAL_ADDRESSBOOK_NAME = 'Contacts';
58
+
59
+    /** @var Principal */
60
+    private $principalBackend;
61
+
62
+    /** @var string */
63
+    private $dbCardsTable = 'cards';
64
+
65
+    /** @var string */
66
+    private $dbCardsPropertiesTable = 'cards_properties';
67
+
68
+    /** @var IDBConnection */
69
+    private $db;
70
+
71
+    /** @var Backend */
72
+    private $sharingBackend;
73
+
74
+    /** @var array properties to index */
75
+    public static $indexProperties = array(
76
+            'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
77
+            'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD');
78
+
79
+    /**
80
+     * @var string[] Map of uid => display name
81
+     */
82
+    protected $userDisplayNames;
83
+
84
+    /** @var IUserManager */
85
+    private $userManager;
86
+
87
+    /** @var EventDispatcherInterface */
88
+    private $dispatcher;
89
+
90
+    /**
91
+     * CardDavBackend constructor.
92
+     *
93
+     * @param IDBConnection $db
94
+     * @param Principal $principalBackend
95
+     * @param IUserManager $userManager
96
+     * @param IGroupManager $groupManager
97
+     * @param EventDispatcherInterface $dispatcher
98
+     */
99
+    public function __construct(IDBConnection $db,
100
+                                Principal $principalBackend,
101
+                                IUserManager $userManager,
102
+                                IGroupManager $groupManager,
103
+                                EventDispatcherInterface $dispatcher) {
104
+        $this->db = $db;
105
+        $this->principalBackend = $principalBackend;
106
+        $this->userManager = $userManager;
107
+        $this->dispatcher = $dispatcher;
108
+        $this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook');
109
+    }
110
+
111
+    /**
112
+     * Return the number of address books for a principal
113
+     *
114
+     * @param $principalUri
115
+     * @return int
116
+     */
117
+    public function getAddressBooksForUserCount($principalUri) {
118
+        $principalUri = $this->convertPrincipal($principalUri, true);
119
+        $query = $this->db->getQueryBuilder();
120
+        $query->select($query->func()->count('*'))
121
+            ->from('addressbooks')
122
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
123
+
124
+        return (int)$query->execute()->fetchColumn();
125
+    }
126
+
127
+    /**
128
+     * Returns the list of address books for a specific user.
129
+     *
130
+     * Every addressbook should have the following properties:
131
+     *   id - an arbitrary unique id
132
+     *   uri - the 'basename' part of the url
133
+     *   principaluri - Same as the passed parameter
134
+     *
135
+     * Any additional clark-notation property may be passed besides this. Some
136
+     * common ones are :
137
+     *   {DAV:}displayname
138
+     *   {urn:ietf:params:xml:ns:carddav}addressbook-description
139
+     *   {http://calendarserver.org/ns/}getctag
140
+     *
141
+     * @param string $principalUri
142
+     * @return array
143
+     */
144
+    function getAddressBooksForUser($principalUri) {
145
+        $principalUriOriginal = $principalUri;
146
+        $principalUri = $this->convertPrincipal($principalUri, true);
147
+        $query = $this->db->getQueryBuilder();
148
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
149
+            ->from('addressbooks')
150
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
151
+
152
+        $addressBooks = [];
153
+
154
+        $result = $query->execute();
155
+        while($row = $result->fetch()) {
156
+            $addressBooks[$row['id']] = [
157
+                'id'  => $row['id'],
158
+                'uri' => $row['uri'],
159
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
160
+                '{DAV:}displayname' => $row['displayname'],
161
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
162
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
163
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
164
+            ];
165
+
166
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
167
+        }
168
+        $result->closeCursor();
169
+
170
+        // query for shared calendars
171
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
172
+        $principals = array_map(function($principal) {
173
+            return urldecode($principal);
174
+        }, $principals);
175
+        $principals[]= $principalUri;
176
+
177
+        $query = $this->db->getQueryBuilder();
178
+        $result = $query->select(['a.id', 'a.uri', 'a.displayname', 'a.principaluri', 'a.description', 'a.synctoken', 's.access'])
179
+            ->from('dav_shares', 's')
180
+            ->join('s', 'addressbooks', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
181
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
182
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
183
+            ->setParameter('type', 'addressbook')
184
+            ->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY)
185
+            ->execute();
186
+
187
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
188
+        while($row = $result->fetch()) {
189
+            if ($row['principaluri'] === $principalUri) {
190
+                continue;
191
+            }
192
+
193
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
194
+            if (isset($addressBooks[$row['id']])) {
195
+                if ($readOnly) {
196
+                    // New share can not have more permissions then the old one.
197
+                    continue;
198
+                }
199
+                if (isset($addressBooks[$row['id']][$readOnlyPropertyName]) &&
200
+                    $addressBooks[$row['id']][$readOnlyPropertyName] === 0) {
201
+                    // Old share is already read-write, no more permissions can be gained
202
+                    continue;
203
+                }
204
+            }
205
+
206
+            list(, $name) = \Sabre\Uri\split($row['principaluri']);
207
+            $uri = $row['uri'] . '_shared_by_' . $name;
208
+            $displayName = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
209
+
210
+            $addressBooks[$row['id']] = [
211
+                'id'  => $row['id'],
212
+                'uri' => $uri,
213
+                'principaluri' => $principalUriOriginal,
214
+                '{DAV:}displayname' => $displayName,
215
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
216
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
217
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
218
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $row['principaluri'],
219
+                $readOnlyPropertyName => $readOnly,
220
+            ];
221
+
222
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
223
+        }
224
+        $result->closeCursor();
225
+
226
+        return array_values($addressBooks);
227
+    }
228
+
229
+    public function getUsersOwnAddressBooks($principalUri) {
230
+        $principalUri = $this->convertPrincipal($principalUri, true);
231
+        $query = $this->db->getQueryBuilder();
232
+        $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
233
+                ->from('addressbooks')
234
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
235
+
236
+        $addressBooks = [];
237
+
238
+        $result = $query->execute();
239
+        while($row = $result->fetch()) {
240
+            $addressBooks[$row['id']] = [
241
+                'id'  => $row['id'],
242
+                'uri' => $row['uri'],
243
+                'principaluri' => $this->convertPrincipal($row['principaluri'], false),
244
+                '{DAV:}displayname' => $row['displayname'],
245
+                '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
246
+                '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
247
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
248
+            ];
249
+
250
+            $this->addOwnerPrincipal($addressBooks[$row['id']]);
251
+        }
252
+        $result->closeCursor();
253
+
254
+        return array_values($addressBooks);
255
+    }
256
+
257
+    private function getUserDisplayName($uid) {
258
+        if (!isset($this->userDisplayNames[$uid])) {
259
+            $user = $this->userManager->get($uid);
260
+
261
+            if ($user instanceof IUser) {
262
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
263
+            } else {
264
+                $this->userDisplayNames[$uid] = $uid;
265
+            }
266
+        }
267
+
268
+        return $this->userDisplayNames[$uid];
269
+    }
270
+
271
+    /**
272
+     * @param int $addressBookId
273
+     */
274
+    public function getAddressBookById($addressBookId) {
275
+        $query = $this->db->getQueryBuilder();
276
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
277
+            ->from('addressbooks')
278
+            ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
279
+            ->execute();
280
+
281
+        $row = $result->fetch();
282
+        $result->closeCursor();
283
+        if ($row === false) {
284
+            return null;
285
+        }
286
+
287
+        $addressBook = [
288
+            'id'  => $row['id'],
289
+            'uri' => $row['uri'],
290
+            'principaluri' => $row['principaluri'],
291
+            '{DAV:}displayname' => $row['displayname'],
292
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
293
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
294
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
295
+        ];
296
+
297
+        $this->addOwnerPrincipal($addressBook);
298
+
299
+        return $addressBook;
300
+    }
301
+
302
+    /**
303
+     * @param $addressBookUri
304
+     * @return array|null
305
+     */
306
+    public function getAddressBooksByUri($principal, $addressBookUri) {
307
+        $query = $this->db->getQueryBuilder();
308
+        $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken'])
309
+            ->from('addressbooks')
310
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri)))
311
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
312
+            ->setMaxResults(1)
313
+            ->execute();
314
+
315
+        $row = $result->fetch();
316
+        $result->closeCursor();
317
+        if ($row === false) {
318
+            return null;
319
+        }
320
+
321
+        $addressBook = [
322
+            'id'  => $row['id'],
323
+            'uri' => $row['uri'],
324
+            'principaluri' => $row['principaluri'],
325
+            '{DAV:}displayname' => $row['displayname'],
326
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'],
327
+            '{http://calendarserver.org/ns/}getctag' => $row['synctoken'],
328
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
329
+        ];
330
+
331
+        $this->addOwnerPrincipal($addressBook);
332
+
333
+        return $addressBook;
334
+    }
335
+
336
+    /**
337
+     * Updates properties for an address book.
338
+     *
339
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
340
+     * To do the actual updates, you must tell this object which properties
341
+     * you're going to process with the handle() method.
342
+     *
343
+     * Calling the handle method is like telling the PropPatch object "I
344
+     * promise I can handle updating this property".
345
+     *
346
+     * Read the PropPatch documentation for more info and examples.
347
+     *
348
+     * @param string $addressBookId
349
+     * @param \Sabre\DAV\PropPatch $propPatch
350
+     * @return void
351
+     */
352
+    function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) {
353
+        $supportedProperties = [
354
+            '{DAV:}displayname',
355
+            '{' . Plugin::NS_CARDDAV . '}addressbook-description',
356
+        ];
357
+
358
+        /**
359
+         * @suppress SqlInjectionChecker
360
+         */
361
+        $propPatch->handle($supportedProperties, function($mutations) use ($addressBookId) {
362
+
363
+            $updates = [];
364
+            foreach($mutations as $property=>$newValue) {
365
+
366
+                switch($property) {
367
+                    case '{DAV:}displayname' :
368
+                        $updates['displayname'] = $newValue;
369
+                        break;
370
+                    case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
371
+                        $updates['description'] = $newValue;
372
+                        break;
373
+                }
374
+            }
375
+            $query = $this->db->getQueryBuilder();
376
+            $query->update('addressbooks');
377
+
378
+            foreach($updates as $key=>$value) {
379
+                $query->set($key, $query->createNamedParameter($value));
380
+            }
381
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId)))
382
+            ->execute();
383
+
384
+            $this->addChange($addressBookId, "", 2);
385
+
386
+            return true;
387
+
388
+        });
389
+    }
390
+
391
+    /**
392
+     * Creates a new address book
393
+     *
394
+     * @param string $principalUri
395
+     * @param string $url Just the 'basename' of the url.
396
+     * @param array $properties
397
+     * @return int
398
+     * @throws BadRequest
399
+     */
400
+    function createAddressBook($principalUri, $url, array $properties) {
401
+        $values = [
402
+            'displayname' => null,
403
+            'description' => null,
404
+            'principaluri' => $principalUri,
405
+            'uri' => $url,
406
+            'synctoken' => 1
407
+        ];
408
+
409
+        foreach($properties as $property=>$newValue) {
410
+
411
+            switch($property) {
412
+                case '{DAV:}displayname' :
413
+                    $values['displayname'] = $newValue;
414
+                    break;
415
+                case '{' . Plugin::NS_CARDDAV . '}addressbook-description' :
416
+                    $values['description'] = $newValue;
417
+                    break;
418
+                default :
419
+                    throw new BadRequest('Unknown property: ' . $property);
420
+            }
421
+
422
+        }
423
+
424
+        // Fallback to make sure the displayname is set. Some clients may refuse
425
+        // to work with addressbooks not having a displayname.
426
+        if(is_null($values['displayname'])) {
427
+            $values['displayname'] = $url;
428
+        }
429
+
430
+        $query = $this->db->getQueryBuilder();
431
+        $query->insert('addressbooks')
432
+            ->values([
433
+                'uri' => $query->createParameter('uri'),
434
+                'displayname' => $query->createParameter('displayname'),
435
+                'description' => $query->createParameter('description'),
436
+                'principaluri' => $query->createParameter('principaluri'),
437
+                'synctoken' => $query->createParameter('synctoken'),
438
+            ])
439
+            ->setParameters($values)
440
+            ->execute();
441
+
442
+        return $query->getLastInsertId();
443
+    }
444
+
445
+    /**
446
+     * Deletes an entire addressbook and all its contents
447
+     *
448
+     * @param mixed $addressBookId
449
+     * @return void
450
+     */
451
+    function deleteAddressBook($addressBookId) {
452
+        $query = $this->db->getQueryBuilder();
453
+        $query->delete('cards')
454
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
455
+            ->setParameter('addressbookid', $addressBookId)
456
+            ->execute();
457
+
458
+        $query->delete('addressbookchanges')
459
+            ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid')))
460
+            ->setParameter('addressbookid', $addressBookId)
461
+            ->execute();
462
+
463
+        $query->delete('addressbooks')
464
+            ->where($query->expr()->eq('id', $query->createParameter('id')))
465
+            ->setParameter('id', $addressBookId)
466
+            ->execute();
467
+
468
+        $this->sharingBackend->deleteAllShares($addressBookId);
469
+
470
+        $query->delete($this->dbCardsPropertiesTable)
471
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
472
+            ->execute();
473
+
474
+    }
475
+
476
+    /**
477
+     * Returns all cards for a specific addressbook id.
478
+     *
479
+     * This method should return the following properties for each card:
480
+     *   * carddata - raw vcard data
481
+     *   * uri - Some unique url
482
+     *   * lastmodified - A unix timestamp
483
+     *
484
+     * It's recommended to also return the following properties:
485
+     *   * etag - A unique etag. This must change every time the card changes.
486
+     *   * size - The size of the card in bytes.
487
+     *
488
+     * If these last two properties are provided, less time will be spent
489
+     * calculating them. If they are specified, you can also ommit carddata.
490
+     * This may speed up certain requests, especially with large cards.
491
+     *
492
+     * @param mixed $addressBookId
493
+     * @return array
494
+     */
495
+    function getCards($addressBookId) {
496
+        $query = $this->db->getQueryBuilder();
497
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
498
+            ->from('cards')
499
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
500
+
501
+        $cards = [];
502
+
503
+        $result = $query->execute();
504
+        while($row = $result->fetch()) {
505
+            $row['etag'] = '"' . $row['etag'] . '"';
506
+            $row['carddata'] = $this->readBlob($row['carddata']);
507
+            $cards[] = $row;
508
+        }
509
+        $result->closeCursor();
510
+
511
+        return $cards;
512
+    }
513
+
514
+    /**
515
+     * Returns a specific card.
516
+     *
517
+     * The same set of properties must be returned as with getCards. The only
518
+     * exception is that 'carddata' is absolutely required.
519
+     *
520
+     * If the card does not exist, you must return false.
521
+     *
522
+     * @param mixed $addressBookId
523
+     * @param string $cardUri
524
+     * @return array
525
+     */
526
+    function getCard($addressBookId, $cardUri) {
527
+        $query = $this->db->getQueryBuilder();
528
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
529
+            ->from('cards')
530
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
531
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
532
+            ->setMaxResults(1);
533
+
534
+        $result = $query->execute();
535
+        $row = $result->fetch();
536
+        if (!$row) {
537
+            return false;
538
+        }
539
+        $row['etag'] = '"' . $row['etag'] . '"';
540
+        $row['carddata'] = $this->readBlob($row['carddata']);
541
+
542
+        return $row;
543
+    }
544
+
545
+    /**
546
+     * Returns a list of cards.
547
+     *
548
+     * This method should work identical to getCard, but instead return all the
549
+     * cards in the list as an array.
550
+     *
551
+     * If the backend supports this, it may allow for some speed-ups.
552
+     *
553
+     * @param mixed $addressBookId
554
+     * @param string[] $uris
555
+     * @return array
556
+     */
557
+    function getMultipleCards($addressBookId, array $uris) {
558
+        if (empty($uris)) {
559
+            return [];
560
+        }
561
+
562
+        $chunks = array_chunk($uris, 100);
563
+        $cards = [];
564
+
565
+        $query = $this->db->getQueryBuilder();
566
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'size', 'carddata', 'uid'])
567
+            ->from('cards')
568
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
569
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')));
570
+
571
+        foreach ($chunks as $uris) {
572
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
573
+            $result = $query->execute();
574
+
575
+            while ($row = $result->fetch()) {
576
+                $row['etag'] = '"' . $row['etag'] . '"';
577
+                $row['carddata'] = $this->readBlob($row['carddata']);
578
+                $cards[] = $row;
579
+            }
580
+            $result->closeCursor();
581
+        }
582
+        return $cards;
583
+    }
584
+
585
+    /**
586
+     * Creates a new card.
587
+     *
588
+     * The addressbook id will be passed as the first argument. This is the
589
+     * same id as it is returned from the getAddressBooksForUser method.
590
+     *
591
+     * The cardUri is a base uri, and doesn't include the full path. The
592
+     * cardData argument is the vcard body, and is passed as a string.
593
+     *
594
+     * It is possible to return an ETag from this method. This ETag is for the
595
+     * newly created resource, and must be enclosed with double quotes (that
596
+     * is, the string itself must contain the double quotes).
597
+     *
598
+     * You should only return the ETag if you store the carddata as-is. If a
599
+     * subsequent GET request on the same card does not have the same body,
600
+     * byte-by-byte and you did return an ETag here, clients tend to get
601
+     * confused.
602
+     *
603
+     * If you don't return an ETag, you can just return null.
604
+     *
605
+     * @param mixed $addressBookId
606
+     * @param string $cardUri
607
+     * @param string $cardData
608
+     * @return string
609
+     */
610
+    function createCard($addressBookId, $cardUri, $cardData) {
611
+        $etag = md5($cardData);
612
+        $uid = $this->getUID($cardData);
613
+
614
+        $q = $this->db->getQueryBuilder();
615
+        $q->select('uid')
616
+            ->from('cards')
617
+            ->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId)))
618
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid)))
619
+            ->setMaxResults(1);
620
+        $result = $q->execute();
621
+        $count = (bool) $result->fetchColumn();
622
+        $result->closeCursor();
623
+        if ($count) {
624
+            throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.');
625
+        }
626
+
627
+        $query = $this->db->getQueryBuilder();
628
+        $query->insert('cards')
629
+            ->values([
630
+                'carddata' => $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB),
631
+                'uri' => $query->createNamedParameter($cardUri),
632
+                'lastmodified' => $query->createNamedParameter(time()),
633
+                'addressbookid' => $query->createNamedParameter($addressBookId),
634
+                'size' => $query->createNamedParameter(strlen($cardData)),
635
+                'etag' => $query->createNamedParameter($etag),
636
+                'uid' => $query->createNamedParameter($uid),
637
+            ])
638
+            ->execute();
639
+
640
+        $this->addChange($addressBookId, $cardUri, 1);
641
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
642
+
643
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard',
644
+            new GenericEvent(null, [
645
+                'addressBookId' => $addressBookId,
646
+                'cardUri' => $cardUri,
647
+                'cardData' => $cardData]));
648
+
649
+        return '"' . $etag . '"';
650
+    }
651
+
652
+    /**
653
+     * Updates a card.
654
+     *
655
+     * The addressbook id will be passed as the first argument. This is the
656
+     * same id as it is returned from the getAddressBooksForUser method.
657
+     *
658
+     * The cardUri is a base uri, and doesn't include the full path. The
659
+     * cardData argument is the vcard body, and is passed as a string.
660
+     *
661
+     * It is possible to return an ETag from this method. This ETag should
662
+     * match that of the updated resource, and must be enclosed with double
663
+     * quotes (that is: the string itself must contain the actual quotes).
664
+     *
665
+     * You should only return the ETag if you store the carddata as-is. If a
666
+     * subsequent GET request on the same card does not have the same body,
667
+     * byte-by-byte and you did return an ETag here, clients tend to get
668
+     * confused.
669
+     *
670
+     * If you don't return an ETag, you can just return null.
671
+     *
672
+     * @param mixed $addressBookId
673
+     * @param string $cardUri
674
+     * @param string $cardData
675
+     * @return string
676
+     */
677
+    function updateCard($addressBookId, $cardUri, $cardData) {
678
+
679
+        $uid = $this->getUID($cardData);
680
+        $etag = md5($cardData);
681
+        $query = $this->db->getQueryBuilder();
682
+        $query->update('cards')
683
+            ->set('carddata', $query->createNamedParameter($cardData, IQueryBuilder::PARAM_LOB))
684
+            ->set('lastmodified', $query->createNamedParameter(time()))
685
+            ->set('size', $query->createNamedParameter(strlen($cardData)))
686
+            ->set('etag', $query->createNamedParameter($etag))
687
+            ->set('uid', $query->createNamedParameter($uid))
688
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
689
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
690
+            ->execute();
691
+
692
+        $this->addChange($addressBookId, $cardUri, 2);
693
+        $this->updateProperties($addressBookId, $cardUri, $cardData);
694
+
695
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard',
696
+            new GenericEvent(null, [
697
+                'addressBookId' => $addressBookId,
698
+                'cardUri' => $cardUri,
699
+                'cardData' => $cardData]));
700
+
701
+        return '"' . $etag . '"';
702
+    }
703
+
704
+    /**
705
+     * Deletes a card
706
+     *
707
+     * @param mixed $addressBookId
708
+     * @param string $cardUri
709
+     * @return bool
710
+     */
711
+    function deleteCard($addressBookId, $cardUri) {
712
+        try {
713
+            $cardId = $this->getCardId($addressBookId, $cardUri);
714
+        } catch (\InvalidArgumentException $e) {
715
+            $cardId = null;
716
+        }
717
+        $query = $this->db->getQueryBuilder();
718
+        $ret = $query->delete('cards')
719
+            ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)))
720
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri)))
721
+            ->execute();
722
+
723
+        $this->addChange($addressBookId, $cardUri, 3);
724
+
725
+        $this->dispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard',
726
+            new GenericEvent(null, [
727
+                'addressBookId' => $addressBookId,
728
+                'cardUri' => $cardUri]));
729
+
730
+        if ($ret === 1) {
731
+            if ($cardId !== null) {
732
+                $this->purgeProperties($addressBookId, $cardId);
733
+            }
734
+            return true;
735
+        }
736
+
737
+        return false;
738
+    }
739
+
740
+    /**
741
+     * The getChanges method returns all the changes that have happened, since
742
+     * the specified syncToken in the specified address book.
743
+     *
744
+     * This function should return an array, such as the following:
745
+     *
746
+     * [
747
+     *   'syncToken' => 'The current synctoken',
748
+     *   'added'   => [
749
+     *      'new.txt',
750
+     *   ],
751
+     *   'modified'   => [
752
+     *      'modified.txt',
753
+     *   ],
754
+     *   'deleted' => [
755
+     *      'foo.php.bak',
756
+     *      'old.txt'
757
+     *   ]
758
+     * ];
759
+     *
760
+     * The returned syncToken property should reflect the *current* syncToken
761
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
762
+     * property. This is needed here too, to ensure the operation is atomic.
763
+     *
764
+     * If the $syncToken argument is specified as null, this is an initial
765
+     * sync, and all members should be reported.
766
+     *
767
+     * The modified property is an array of nodenames that have changed since
768
+     * the last token.
769
+     *
770
+     * The deleted property is an array with nodenames, that have been deleted
771
+     * from collection.
772
+     *
773
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
774
+     * 1, you only have to report changes that happened only directly in
775
+     * immediate descendants. If it's 2, it should also include changes from
776
+     * the nodes below the child collections. (grandchildren)
777
+     *
778
+     * The $limit argument allows a client to specify how many results should
779
+     * be returned at most. If the limit is not specified, it should be treated
780
+     * as infinite.
781
+     *
782
+     * If the limit (infinite or not) is higher than you're willing to return,
783
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
784
+     *
785
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
786
+     * return null.
787
+     *
788
+     * The limit is 'suggestive'. You are free to ignore it.
789
+     *
790
+     * @param string $addressBookId
791
+     * @param string $syncToken
792
+     * @param int $syncLevel
793
+     * @param int $limit
794
+     * @return array
795
+     */
796
+    function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) {
797
+        // Current synctoken
798
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*addressbooks` WHERE `id` = ?');
799
+        $stmt->execute([ $addressBookId ]);
800
+        $currentToken = $stmt->fetchColumn(0);
801
+
802
+        if (is_null($currentToken)) return null;
803
+
804
+        $result = [
805
+            'syncToken' => $currentToken,
806
+            'added'     => [],
807
+            'modified'  => [],
808
+            'deleted'   => [],
809
+        ];
810
+
811
+        if ($syncToken) {
812
+
813
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*addressbookchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `addressbookid` = ? ORDER BY `synctoken`";
814
+            if ($limit>0) {
815
+                $query .= " `LIMIT` " . (int)$limit;
816
+            }
817
+
818
+            // Fetching all changes
819
+            $stmt = $this->db->prepare($query);
820
+            $stmt->execute([$syncToken, $currentToken, $addressBookId]);
821
+
822
+            $changes = [];
823
+
824
+            // This loop ensures that any duplicates are overwritten, only the
825
+            // last change on a node is relevant.
826
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
827
+
828
+                $changes[$row['uri']] = $row['operation'];
829
+
830
+            }
831
+
832
+            foreach($changes as $uri => $operation) {
833
+
834
+                switch($operation) {
835
+                    case 1:
836
+                        $result['added'][] = $uri;
837
+                        break;
838
+                    case 2:
839
+                        $result['modified'][] = $uri;
840
+                        break;
841
+                    case 3:
842
+                        $result['deleted'][] = $uri;
843
+                        break;
844
+                }
845
+
846
+            }
847
+        } else {
848
+            // No synctoken supplied, this is the initial sync.
849
+            $query = "SELECT `uri` FROM `*PREFIX*cards` WHERE `addressbookid` = ?";
850
+            $stmt = $this->db->prepare($query);
851
+            $stmt->execute([$addressBookId]);
852
+
853
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
854
+        }
855
+        return $result;
856
+    }
857
+
858
+    /**
859
+     * Adds a change record to the addressbookchanges table.
860
+     *
861
+     * @param mixed $addressBookId
862
+     * @param string $objectUri
863
+     * @param int $operation 1 = add, 2 = modify, 3 = delete
864
+     * @return void
865
+     */
866
+    protected function addChange($addressBookId, $objectUri, $operation) {
867
+        $sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?';
868
+        $stmt = $this->db->prepare($sql);
869
+        $stmt->execute([
870
+            $objectUri,
871
+            $addressBookId,
872
+            $operation,
873
+            $addressBookId
874
+        ]);
875
+        $stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?');
876
+        $stmt->execute([
877
+            $addressBookId
878
+        ]);
879
+    }
880
+
881
+    private function readBlob($cardData) {
882
+        if (is_resource($cardData)) {
883
+            return stream_get_contents($cardData);
884
+        }
885
+
886
+        return $cardData;
887
+    }
888
+
889
+    /**
890
+     * @param IShareable $shareable
891
+     * @param string[] $add
892
+     * @param string[] $remove
893
+     */
894
+    public function updateShares(IShareable $shareable, $add, $remove) {
895
+        $this->sharingBackend->updateShares($shareable, $add, $remove);
896
+    }
897
+
898
+    /**
899
+     * search contact
900
+     *
901
+     * @param int $addressBookId
902
+     * @param string $pattern which should match within the $searchProperties
903
+     * @param array $searchProperties defines the properties within the query pattern should match
904
+     * @return array an array of contacts which are arrays of key-value-pairs
905
+     */
906
+    public function search($addressBookId, $pattern, $searchProperties) {
907
+        $query = $this->db->getQueryBuilder();
908
+        $query2 = $this->db->getQueryBuilder();
909
+
910
+        $query2->selectDistinct('cp.cardid')->from($this->dbCardsPropertiesTable, 'cp');
911
+        $query2->andWhere($query2->expr()->eq('cp.addressbookid', $query->createNamedParameter($addressBookId)));
912
+        $or = $query2->expr()->orX();
913
+        foreach ($searchProperties as $property) {
914
+            $or->add($query2->expr()->eq('cp.name', $query->createNamedParameter($property)));
915
+        }
916
+        $query2->andWhere($or);
917
+
918
+        // No need for like when the pattern is empty
919
+        if ('' !== $pattern) {
920
+            $query2->andWhere($query2->expr()->ilike('cp.value', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($pattern) . '%')));
921
+        }
922
+
923
+        $query->select('c.carddata', 'c.uri')->from($this->dbCardsTable, 'c')
924
+            ->where($query->expr()->in('c.id', $query->createFunction($query2->getSQL())));
925
+
926
+        $result = $query->execute();
927
+        $cards = $result->fetchAll();
928
+
929
+        $result->closeCursor();
930
+
931
+        return array_map(function($array) {
932
+            $array['carddata'] = $this->readBlob($array['carddata']);
933
+            return $array;
934
+        }, $cards);
935
+    }
936
+
937
+    /**
938
+     * @param int $bookId
939
+     * @param string $name
940
+     * @return array
941
+     */
942
+    public function collectCardProperties($bookId, $name) {
943
+        $query = $this->db->getQueryBuilder();
944
+        $result = $query->selectDistinct('value')
945
+            ->from($this->dbCardsPropertiesTable)
946
+            ->where($query->expr()->eq('name', $query->createNamedParameter($name)))
947
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId)))
948
+            ->execute();
949
+
950
+        $all = $result->fetchAll(PDO::FETCH_COLUMN);
951
+        $result->closeCursor();
952
+
953
+        return $all;
954
+    }
955
+
956
+    /**
957
+     * get URI from a given contact
958
+     *
959
+     * @param int $id
960
+     * @return string
961
+     */
962
+    public function getCardUri($id) {
963
+        $query = $this->db->getQueryBuilder();
964
+        $query->select('uri')->from($this->dbCardsTable)
965
+                ->where($query->expr()->eq('id', $query->createParameter('id')))
966
+                ->setParameter('id', $id);
967
+
968
+        $result = $query->execute();
969
+        $uri = $result->fetch();
970
+        $result->closeCursor();
971
+
972
+        if (!isset($uri['uri'])) {
973
+            throw new \InvalidArgumentException('Card does not exists: ' . $id);
974
+        }
975
+
976
+        return $uri['uri'];
977
+    }
978
+
979
+    /**
980
+     * return contact with the given URI
981
+     *
982
+     * @param int $addressBookId
983
+     * @param string $uri
984
+     * @returns array
985
+     */
986
+    public function getContact($addressBookId, $uri) {
987
+        $result = [];
988
+        $query = $this->db->getQueryBuilder();
989
+        $query->select('*')->from($this->dbCardsTable)
990
+                ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
991
+                ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
992
+        $queryResult = $query->execute();
993
+        $contact = $queryResult->fetch();
994
+        $queryResult->closeCursor();
995
+
996
+        if (is_array($contact)) {
997
+            $result = $contact;
998
+        }
999
+
1000
+        return $result;
1001
+    }
1002
+
1003
+    /**
1004
+     * Returns the list of people whom this address book is shared with.
1005
+     *
1006
+     * Every element in this array should have the following properties:
1007
+     *   * href - Often a mailto: address
1008
+     *   * commonName - Optional, for example a first + last name
1009
+     *   * status - See the Sabre\CalDAV\SharingPlugin::STATUS_ constants.
1010
+     *   * readOnly - boolean
1011
+     *   * summary - Optional, a description for the share
1012
+     *
1013
+     * @return array
1014
+     */
1015
+    public function getShares($addressBookId) {
1016
+        return $this->sharingBackend->getShares($addressBookId);
1017
+    }
1018
+
1019
+    /**
1020
+     * update properties table
1021
+     *
1022
+     * @param int $addressBookId
1023
+     * @param string $cardUri
1024
+     * @param string $vCardSerialized
1025
+     */
1026
+    protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) {
1027
+        $cardId = $this->getCardId($addressBookId, $cardUri);
1028
+        $vCard = $this->readCard($vCardSerialized);
1029
+
1030
+        $this->purgeProperties($addressBookId, $cardId);
1031
+
1032
+        $query = $this->db->getQueryBuilder();
1033
+        $query->insert($this->dbCardsPropertiesTable)
1034
+            ->values(
1035
+                [
1036
+                    'addressbookid' => $query->createNamedParameter($addressBookId),
1037
+                    'cardid' => $query->createNamedParameter($cardId),
1038
+                    'name' => $query->createParameter('name'),
1039
+                    'value' => $query->createParameter('value'),
1040
+                    'preferred' => $query->createParameter('preferred')
1041
+                ]
1042
+            );
1043
+
1044
+        foreach ($vCard->children() as $property) {
1045
+            if(!in_array($property->name, self::$indexProperties)) {
1046
+                continue;
1047
+            }
1048
+            $preferred = 0;
1049
+            foreach($property->parameters as $parameter) {
1050
+                if ($parameter->name === 'TYPE' && strtoupper($parameter->getValue()) === 'PREF') {
1051
+                    $preferred = 1;
1052
+                    break;
1053
+                }
1054
+            }
1055
+            $query->setParameter('name', $property->name);
1056
+            $query->setParameter('value', substr($property->getValue(), 0, 254));
1057
+            $query->setParameter('preferred', $preferred);
1058
+            $query->execute();
1059
+        }
1060
+    }
1061
+
1062
+    /**
1063
+     * read vCard data into a vCard object
1064
+     *
1065
+     * @param string $cardData
1066
+     * @return VCard
1067
+     */
1068
+    protected function readCard($cardData) {
1069
+        return  Reader::read($cardData);
1070
+    }
1071
+
1072
+    /**
1073
+     * delete all properties from a given card
1074
+     *
1075
+     * @param int $addressBookId
1076
+     * @param int $cardId
1077
+     */
1078
+    protected function purgeProperties($addressBookId, $cardId) {
1079
+        $query = $this->db->getQueryBuilder();
1080
+        $query->delete($this->dbCardsPropertiesTable)
1081
+            ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId)))
1082
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1083
+        $query->execute();
1084
+    }
1085
+
1086
+    /**
1087
+     * get ID from a given contact
1088
+     *
1089
+     * @param int $addressBookId
1090
+     * @param string $uri
1091
+     * @return int
1092
+     */
1093
+    protected function getCardId($addressBookId, $uri) {
1094
+        $query = $this->db->getQueryBuilder();
1095
+        $query->select('id')->from($this->dbCardsTable)
1096
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
1097
+            ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId)));
1098
+
1099
+        $result = $query->execute();
1100
+        $cardIds = $result->fetch();
1101
+        $result->closeCursor();
1102
+
1103
+        if (!isset($cardIds['id'])) {
1104
+            throw new \InvalidArgumentException('Card does not exists: ' . $uri);
1105
+        }
1106
+
1107
+        return (int)$cardIds['id'];
1108
+    }
1109
+
1110
+    /**
1111
+     * For shared address books the sharee is set in the ACL of the address book
1112
+     * @param $addressBookId
1113
+     * @param $acl
1114
+     * @return array
1115
+     */
1116
+    public function applyShareAcl($addressBookId, $acl) {
1117
+        return $this->sharingBackend->applyShareAcl($addressBookId, $acl);
1118
+    }
1119
+
1120
+    private function convertPrincipal($principalUri, $toV2) {
1121
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
1122
+            list(, $name) = \Sabre\Uri\split($principalUri);
1123
+            if ($toV2 === true) {
1124
+                return "principals/users/$name";
1125
+            }
1126
+            return "principals/$name";
1127
+        }
1128
+        return $principalUri;
1129
+    }
1130
+
1131
+    private function addOwnerPrincipal(&$addressbookInfo) {
1132
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
1133
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
1134
+        if (isset($addressbookInfo[$ownerPrincipalKey])) {
1135
+            $uri = $addressbookInfo[$ownerPrincipalKey];
1136
+        } else {
1137
+            $uri = $addressbookInfo['principaluri'];
1138
+        }
1139
+
1140
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
1141
+        if (isset($principalInformation['{DAV:}displayname'])) {
1142
+            $addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
1143
+        }
1144
+    }
1145
+
1146
+    /**
1147
+     * Extract UID from vcard
1148
+     *
1149
+     * @param string $cardData the vcard raw data
1150
+     * @return string the uid
1151
+     * @throws BadRequest if no UID is available
1152
+     */
1153
+    private function getUID($cardData) {
1154
+        if ($cardData != '') {
1155
+            $vCard = Reader::read($cardData);
1156
+            if ($vCard->UID) {
1157
+                $uid = $vCard->UID->getValue();
1158
+                return $uid;
1159
+            }
1160
+            // should already be handled, but just in case
1161
+            throw new BadRequest('vCards on CardDAV servers MUST have a UID property');
1162
+        }
1163
+        // should already be handled, but just in case
1164
+        throw new BadRequest('vCard can not be empty');
1165
+    }
1166 1166
 }
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/CalDavBackend.php 1 patch
Indentation   +2535 added lines, -2535 removed lines patch added patch discarded remove patch
@@ -73,2540 +73,2540 @@
 block discarded – undo
73 73
  */
74 74
 class CalDavBackend extends AbstractBackend implements SyncSupport, SubscriptionSupport, SchedulingSupport {
75 75
 
76
-	const CALENDAR_TYPE_CALENDAR = 0;
77
-	const CALENDAR_TYPE_SUBSCRIPTION = 1;
78
-
79
-	const PERSONAL_CALENDAR_URI = 'personal';
80
-	const PERSONAL_CALENDAR_NAME = 'Personal';
81
-
82
-	const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
83
-	const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
84
-
85
-	/**
86
-	 * We need to specify a max date, because we need to stop *somewhere*
87
-	 *
88
-	 * On 32 bit system the maximum for a signed integer is 2147483647, so
89
-	 * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
90
-	 * in 2038-01-19 to avoid problems when the date is converted
91
-	 * to a unix timestamp.
92
-	 */
93
-	const MAX_DATE = '2038-01-01';
94
-
95
-	const ACCESS_PUBLIC = 4;
96
-	const CLASSIFICATION_PUBLIC = 0;
97
-	const CLASSIFICATION_PRIVATE = 1;
98
-	const CLASSIFICATION_CONFIDENTIAL = 2;
99
-
100
-	/**
101
-	 * List of CalDAV properties, and how they map to database field names
102
-	 * Add your own properties by simply adding on to this array.
103
-	 *
104
-	 * Note that only string-based properties are supported here.
105
-	 *
106
-	 * @var array
107
-	 */
108
-	public $propertyMap = [
109
-		'{DAV:}displayname'                          => 'displayname',
110
-		'{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
111
-		'{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
112
-		'{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
113
-		'{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
114
-	];
115
-
116
-	/**
117
-	 * List of subscription properties, and how they map to database field names.
118
-	 *
119
-	 * @var array
120
-	 */
121
-	public $subscriptionPropertyMap = [
122
-		'{DAV:}displayname'                                           => 'displayname',
123
-		'{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
124
-		'{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
125
-		'{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
126
-		'{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
127
-		'{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
128
-		'{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
129
-	];
130
-
131
-	/** @var array properties to index */
132
-	public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
133
-		'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
134
-		'ORGANIZER'];
135
-
136
-	/** @var array parameters to index */
137
-	public static $indexParameters = [
138
-		'ATTENDEE' => ['CN'],
139
-		'ORGANIZER' => ['CN'],
140
-	];
141
-
142
-	/**
143
-	 * @var string[] Map of uid => display name
144
-	 */
145
-	protected $userDisplayNames;
146
-
147
-	/** @var IDBConnection */
148
-	private $db;
149
-
150
-	/** @var Backend */
151
-	private $calendarSharingBackend;
152
-
153
-	/** @var Principal */
154
-	private $principalBackend;
155
-
156
-	/** @var IUserManager */
157
-	private $userManager;
158
-
159
-	/** @var ISecureRandom */
160
-	private $random;
161
-
162
-	/** @var ILogger */
163
-	private $logger;
164
-
165
-	/** @var EventDispatcherInterface */
166
-	private $dispatcher;
167
-
168
-	/** @var bool */
169
-	private $legacyEndpoint;
170
-
171
-	/** @var string */
172
-	private $dbObjectPropertiesTable = 'calendarobjects_props';
173
-
174
-	/**
175
-	 * CalDavBackend constructor.
176
-	 *
177
-	 * @param IDBConnection $db
178
-	 * @param Principal $principalBackend
179
-	 * @param IUserManager $userManager
180
-	 * @param IGroupManager $groupManager
181
-	 * @param ISecureRandom $random
182
-	 * @param ILogger $logger
183
-	 * @param EventDispatcherInterface $dispatcher
184
-	 * @param bool $legacyEndpoint
185
-	 */
186
-	public function __construct(IDBConnection $db,
187
-								Principal $principalBackend,
188
-								IUserManager $userManager,
189
-								IGroupManager $groupManager,
190
-								ISecureRandom $random,
191
-								ILogger $logger,
192
-								EventDispatcherInterface $dispatcher,
193
-								$legacyEndpoint = false) {
194
-		$this->db = $db;
195
-		$this->principalBackend = $principalBackend;
196
-		$this->userManager = $userManager;
197
-		$this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
198
-		$this->random = $random;
199
-		$this->logger = $logger;
200
-		$this->dispatcher = $dispatcher;
201
-		$this->legacyEndpoint = $legacyEndpoint;
202
-	}
203
-
204
-	/**
205
-	 * Return the number of calendars for a principal
206
-	 *
207
-	 * By default this excludes the automatically generated birthday calendar
208
-	 *
209
-	 * @param $principalUri
210
-	 * @param bool $excludeBirthday
211
-	 * @return int
212
-	 */
213
-	public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
214
-		$principalUri = $this->convertPrincipal($principalUri, true);
215
-		$query = $this->db->getQueryBuilder();
216
-		$query->select($query->func()->count('*'))
217
-			->from('calendars')
218
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
219
-
220
-		if ($excludeBirthday) {
221
-			$query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
222
-		}
223
-
224
-		return (int)$query->execute()->fetchColumn();
225
-	}
226
-
227
-	/**
228
-	 * Returns a list of calendars for a principal.
229
-	 *
230
-	 * Every project is an array with the following keys:
231
-	 *  * id, a unique id that will be used by other functions to modify the
232
-	 *    calendar. This can be the same as the uri or a database key.
233
-	 *  * uri, which the basename of the uri with which the calendar is
234
-	 *    accessed.
235
-	 *  * principaluri. The owner of the calendar. Almost always the same as
236
-	 *    principalUri passed to this method.
237
-	 *
238
-	 * Furthermore it can contain webdav properties in clark notation. A very
239
-	 * common one is '{DAV:}displayname'.
240
-	 *
241
-	 * Many clients also require:
242
-	 * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
243
-	 * For this property, you can just return an instance of
244
-	 * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
245
-	 *
246
-	 * If you return {http://sabredav.org/ns}read-only and set the value to 1,
247
-	 * ACL will automatically be put in read-only mode.
248
-	 *
249
-	 * @param string $principalUri
250
-	 * @return array
251
-	 */
252
-	function getCalendarsForUser($principalUri) {
253
-		$principalUriOriginal = $principalUri;
254
-		$principalUri = $this->convertPrincipal($principalUri, true);
255
-		$fields = array_values($this->propertyMap);
256
-		$fields[] = 'id';
257
-		$fields[] = 'uri';
258
-		$fields[] = 'synctoken';
259
-		$fields[] = 'components';
260
-		$fields[] = 'principaluri';
261
-		$fields[] = 'transparent';
262
-
263
-		// Making fields a comma-delimited list
264
-		$query = $this->db->getQueryBuilder();
265
-		$query->select($fields)->from('calendars')
266
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
267
-				->orderBy('calendarorder', 'ASC');
268
-		$stmt = $query->execute();
269
-
270
-		$calendars = [];
271
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
272
-
273
-			$components = [];
274
-			if ($row['components']) {
275
-				$components = explode(',',$row['components']);
276
-			}
277
-
278
-			$calendar = [
279
-				'id' => $row['id'],
280
-				'uri' => $row['uri'],
281
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
282
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
283
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
284
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
285
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
286
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
287
-			];
288
-
289
-			foreach($this->propertyMap as $xmlName=>$dbName) {
290
-				$calendar[$xmlName] = $row[$dbName];
291
-			}
292
-
293
-			$this->addOwnerPrincipal($calendar);
294
-
295
-			if (!isset($calendars[$calendar['id']])) {
296
-				$calendars[$calendar['id']] = $calendar;
297
-			}
298
-		}
299
-
300
-		$stmt->closeCursor();
301
-
302
-		// query for shared calendars
303
-		$principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
304
-		$principals = array_map(function($principal) {
305
-			return urldecode($principal);
306
-		}, $principals);
307
-		$principals[]= $principalUri;
308
-
309
-		$fields = array_values($this->propertyMap);
310
-		$fields[] = 'a.id';
311
-		$fields[] = 'a.uri';
312
-		$fields[] = 'a.synctoken';
313
-		$fields[] = 'a.components';
314
-		$fields[] = 'a.principaluri';
315
-		$fields[] = 'a.transparent';
316
-		$fields[] = 's.access';
317
-		$query = $this->db->getQueryBuilder();
318
-		$result = $query->select($fields)
319
-			->from('dav_shares', 's')
320
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
321
-			->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
322
-			->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
323
-			->setParameter('type', 'calendar')
324
-			->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
325
-			->execute();
326
-
327
-		$readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
328
-		while($row = $result->fetch()) {
329
-			if ($row['principaluri'] === $principalUri) {
330
-				continue;
331
-			}
332
-
333
-			$readOnly = (int) $row['access'] === Backend::ACCESS_READ;
334
-			if (isset($calendars[$row['id']])) {
335
-				if ($readOnly) {
336
-					// New share can not have more permissions then the old one.
337
-					continue;
338
-				}
339
-				if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
340
-					$calendars[$row['id']][$readOnlyPropertyName] === 0) {
341
-					// Old share is already read-write, no more permissions can be gained
342
-					continue;
343
-				}
344
-			}
345
-
346
-			list(, $name) = Uri\split($row['principaluri']);
347
-			$uri = $row['uri'] . '_shared_by_' . $name;
348
-			$row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
349
-			$components = [];
350
-			if ($row['components']) {
351
-				$components = explode(',',$row['components']);
352
-			}
353
-			$calendar = [
354
-				'id' => $row['id'],
355
-				'uri' => $uri,
356
-				'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
357
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
358
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
359
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
360
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
361
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
362
-				$readOnlyPropertyName => $readOnly,
363
-			];
364
-
365
-			foreach($this->propertyMap as $xmlName=>$dbName) {
366
-				$calendar[$xmlName] = $row[$dbName];
367
-			}
368
-
369
-			$this->addOwnerPrincipal($calendar);
370
-
371
-			$calendars[$calendar['id']] = $calendar;
372
-		}
373
-		$result->closeCursor();
374
-
375
-		return array_values($calendars);
376
-	}
377
-
378
-	/**
379
-	 * @param $principalUri
380
-	 * @return array
381
-	 */
382
-	public function getUsersOwnCalendars($principalUri) {
383
-		$principalUri = $this->convertPrincipal($principalUri, true);
384
-		$fields = array_values($this->propertyMap);
385
-		$fields[] = 'id';
386
-		$fields[] = 'uri';
387
-		$fields[] = 'synctoken';
388
-		$fields[] = 'components';
389
-		$fields[] = 'principaluri';
390
-		$fields[] = 'transparent';
391
-		// Making fields a comma-delimited list
392
-		$query = $this->db->getQueryBuilder();
393
-		$query->select($fields)->from('calendars')
394
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
395
-			->orderBy('calendarorder', 'ASC');
396
-		$stmt = $query->execute();
397
-		$calendars = [];
398
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
399
-			$components = [];
400
-			if ($row['components']) {
401
-				$components = explode(',',$row['components']);
402
-			}
403
-			$calendar = [
404
-				'id' => $row['id'],
405
-				'uri' => $row['uri'],
406
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
407
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
408
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
409
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
410
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
411
-			];
412
-			foreach($this->propertyMap as $xmlName=>$dbName) {
413
-				$calendar[$xmlName] = $row[$dbName];
414
-			}
415
-
416
-			$this->addOwnerPrincipal($calendar);
417
-
418
-			if (!isset($calendars[$calendar['id']])) {
419
-				$calendars[$calendar['id']] = $calendar;
420
-			}
421
-		}
422
-		$stmt->closeCursor();
423
-		return array_values($calendars);
424
-	}
425
-
426
-
427
-	/**
428
-	 * @param $uid
429
-	 * @return string
430
-	 */
431
-	private function getUserDisplayName($uid) {
432
-		if (!isset($this->userDisplayNames[$uid])) {
433
-			$user = $this->userManager->get($uid);
434
-
435
-			if ($user instanceof IUser) {
436
-				$this->userDisplayNames[$uid] = $user->getDisplayName();
437
-			} else {
438
-				$this->userDisplayNames[$uid] = $uid;
439
-			}
440
-		}
441
-
442
-		return $this->userDisplayNames[$uid];
443
-	}
76
+    const CALENDAR_TYPE_CALENDAR = 0;
77
+    const CALENDAR_TYPE_SUBSCRIPTION = 1;
78
+
79
+    const PERSONAL_CALENDAR_URI = 'personal';
80
+    const PERSONAL_CALENDAR_NAME = 'Personal';
81
+
82
+    const RESOURCE_BOOKING_CALENDAR_URI = 'calendar';
83
+    const RESOURCE_BOOKING_CALENDAR_NAME = 'Calendar';
84
+
85
+    /**
86
+     * We need to specify a max date, because we need to stop *somewhere*
87
+     *
88
+     * On 32 bit system the maximum for a signed integer is 2147483647, so
89
+     * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results
90
+     * in 2038-01-19 to avoid problems when the date is converted
91
+     * to a unix timestamp.
92
+     */
93
+    const MAX_DATE = '2038-01-01';
94
+
95
+    const ACCESS_PUBLIC = 4;
96
+    const CLASSIFICATION_PUBLIC = 0;
97
+    const CLASSIFICATION_PRIVATE = 1;
98
+    const CLASSIFICATION_CONFIDENTIAL = 2;
99
+
100
+    /**
101
+     * List of CalDAV properties, and how they map to database field names
102
+     * Add your own properties by simply adding on to this array.
103
+     *
104
+     * Note that only string-based properties are supported here.
105
+     *
106
+     * @var array
107
+     */
108
+    public $propertyMap = [
109
+        '{DAV:}displayname'                          => 'displayname',
110
+        '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description',
111
+        '{urn:ietf:params:xml:ns:caldav}calendar-timezone'    => 'timezone',
112
+        '{http://apple.com/ns/ical/}calendar-order'  => 'calendarorder',
113
+        '{http://apple.com/ns/ical/}calendar-color'  => 'calendarcolor',
114
+    ];
115
+
116
+    /**
117
+     * List of subscription properties, and how they map to database field names.
118
+     *
119
+     * @var array
120
+     */
121
+    public $subscriptionPropertyMap = [
122
+        '{DAV:}displayname'                                           => 'displayname',
123
+        '{http://apple.com/ns/ical/}refreshrate'                      => 'refreshrate',
124
+        '{http://apple.com/ns/ical/}calendar-order'                   => 'calendarorder',
125
+        '{http://apple.com/ns/ical/}calendar-color'                   => 'calendarcolor',
126
+        '{http://calendarserver.org/ns/}subscribed-strip-todos'       => 'striptodos',
127
+        '{http://calendarserver.org/ns/}subscribed-strip-alarms'      => 'stripalarms',
128
+        '{http://calendarserver.org/ns/}subscribed-strip-attachments' => 'stripattachments',
129
+    ];
130
+
131
+    /** @var array properties to index */
132
+    public static $indexProperties = ['CATEGORIES', 'COMMENT', 'DESCRIPTION',
133
+        'LOCATION', 'RESOURCES', 'STATUS', 'SUMMARY', 'ATTENDEE', 'CONTACT',
134
+        'ORGANIZER'];
135
+
136
+    /** @var array parameters to index */
137
+    public static $indexParameters = [
138
+        'ATTENDEE' => ['CN'],
139
+        'ORGANIZER' => ['CN'],
140
+    ];
141
+
142
+    /**
143
+     * @var string[] Map of uid => display name
144
+     */
145
+    protected $userDisplayNames;
146
+
147
+    /** @var IDBConnection */
148
+    private $db;
149
+
150
+    /** @var Backend */
151
+    private $calendarSharingBackend;
152
+
153
+    /** @var Principal */
154
+    private $principalBackend;
155
+
156
+    /** @var IUserManager */
157
+    private $userManager;
158
+
159
+    /** @var ISecureRandom */
160
+    private $random;
161
+
162
+    /** @var ILogger */
163
+    private $logger;
164
+
165
+    /** @var EventDispatcherInterface */
166
+    private $dispatcher;
167
+
168
+    /** @var bool */
169
+    private $legacyEndpoint;
170
+
171
+    /** @var string */
172
+    private $dbObjectPropertiesTable = 'calendarobjects_props';
173
+
174
+    /**
175
+     * CalDavBackend constructor.
176
+     *
177
+     * @param IDBConnection $db
178
+     * @param Principal $principalBackend
179
+     * @param IUserManager $userManager
180
+     * @param IGroupManager $groupManager
181
+     * @param ISecureRandom $random
182
+     * @param ILogger $logger
183
+     * @param EventDispatcherInterface $dispatcher
184
+     * @param bool $legacyEndpoint
185
+     */
186
+    public function __construct(IDBConnection $db,
187
+                                Principal $principalBackend,
188
+                                IUserManager $userManager,
189
+                                IGroupManager $groupManager,
190
+                                ISecureRandom $random,
191
+                                ILogger $logger,
192
+                                EventDispatcherInterface $dispatcher,
193
+                                $legacyEndpoint = false) {
194
+        $this->db = $db;
195
+        $this->principalBackend = $principalBackend;
196
+        $this->userManager = $userManager;
197
+        $this->calendarSharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'calendar');
198
+        $this->random = $random;
199
+        $this->logger = $logger;
200
+        $this->dispatcher = $dispatcher;
201
+        $this->legacyEndpoint = $legacyEndpoint;
202
+    }
203
+
204
+    /**
205
+     * Return the number of calendars for a principal
206
+     *
207
+     * By default this excludes the automatically generated birthday calendar
208
+     *
209
+     * @param $principalUri
210
+     * @param bool $excludeBirthday
211
+     * @return int
212
+     */
213
+    public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) {
214
+        $principalUri = $this->convertPrincipal($principalUri, true);
215
+        $query = $this->db->getQueryBuilder();
216
+        $query->select($query->func()->count('*'))
217
+            ->from('calendars')
218
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)));
219
+
220
+        if ($excludeBirthday) {
221
+            $query->andWhere($query->expr()->neq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)));
222
+        }
223
+
224
+        return (int)$query->execute()->fetchColumn();
225
+    }
226
+
227
+    /**
228
+     * Returns a list of calendars for a principal.
229
+     *
230
+     * Every project is an array with the following keys:
231
+     *  * id, a unique id that will be used by other functions to modify the
232
+     *    calendar. This can be the same as the uri or a database key.
233
+     *  * uri, which the basename of the uri with which the calendar is
234
+     *    accessed.
235
+     *  * principaluri. The owner of the calendar. Almost always the same as
236
+     *    principalUri passed to this method.
237
+     *
238
+     * Furthermore it can contain webdav properties in clark notation. A very
239
+     * common one is '{DAV:}displayname'.
240
+     *
241
+     * Many clients also require:
242
+     * {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
243
+     * For this property, you can just return an instance of
244
+     * Sabre\CalDAV\Property\SupportedCalendarComponentSet.
245
+     *
246
+     * If you return {http://sabredav.org/ns}read-only and set the value to 1,
247
+     * ACL will automatically be put in read-only mode.
248
+     *
249
+     * @param string $principalUri
250
+     * @return array
251
+     */
252
+    function getCalendarsForUser($principalUri) {
253
+        $principalUriOriginal = $principalUri;
254
+        $principalUri = $this->convertPrincipal($principalUri, true);
255
+        $fields = array_values($this->propertyMap);
256
+        $fields[] = 'id';
257
+        $fields[] = 'uri';
258
+        $fields[] = 'synctoken';
259
+        $fields[] = 'components';
260
+        $fields[] = 'principaluri';
261
+        $fields[] = 'transparent';
262
+
263
+        // Making fields a comma-delimited list
264
+        $query = $this->db->getQueryBuilder();
265
+        $query->select($fields)->from('calendars')
266
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
267
+                ->orderBy('calendarorder', 'ASC');
268
+        $stmt = $query->execute();
269
+
270
+        $calendars = [];
271
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
272
+
273
+            $components = [];
274
+            if ($row['components']) {
275
+                $components = explode(',',$row['components']);
276
+            }
277
+
278
+            $calendar = [
279
+                'id' => $row['id'],
280
+                'uri' => $row['uri'],
281
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
282
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
283
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
284
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
285
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
286
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
287
+            ];
288
+
289
+            foreach($this->propertyMap as $xmlName=>$dbName) {
290
+                $calendar[$xmlName] = $row[$dbName];
291
+            }
292
+
293
+            $this->addOwnerPrincipal($calendar);
294
+
295
+            if (!isset($calendars[$calendar['id']])) {
296
+                $calendars[$calendar['id']] = $calendar;
297
+            }
298
+        }
299
+
300
+        $stmt->closeCursor();
301
+
302
+        // query for shared calendars
303
+        $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true);
304
+        $principals = array_map(function($principal) {
305
+            return urldecode($principal);
306
+        }, $principals);
307
+        $principals[]= $principalUri;
308
+
309
+        $fields = array_values($this->propertyMap);
310
+        $fields[] = 'a.id';
311
+        $fields[] = 'a.uri';
312
+        $fields[] = 'a.synctoken';
313
+        $fields[] = 'a.components';
314
+        $fields[] = 'a.principaluri';
315
+        $fields[] = 'a.transparent';
316
+        $fields[] = 's.access';
317
+        $query = $this->db->getQueryBuilder();
318
+        $result = $query->select($fields)
319
+            ->from('dav_shares', 's')
320
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
321
+            ->where($query->expr()->in('s.principaluri', $query->createParameter('principaluri')))
322
+            ->andWhere($query->expr()->eq('s.type', $query->createParameter('type')))
323
+            ->setParameter('type', 'calendar')
324
+            ->setParameter('principaluri', $principals, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
325
+            ->execute();
326
+
327
+        $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only';
328
+        while($row = $result->fetch()) {
329
+            if ($row['principaluri'] === $principalUri) {
330
+                continue;
331
+            }
332
+
333
+            $readOnly = (int) $row['access'] === Backend::ACCESS_READ;
334
+            if (isset($calendars[$row['id']])) {
335
+                if ($readOnly) {
336
+                    // New share can not have more permissions then the old one.
337
+                    continue;
338
+                }
339
+                if (isset($calendars[$row['id']][$readOnlyPropertyName]) &&
340
+                    $calendars[$row['id']][$readOnlyPropertyName] === 0) {
341
+                    // Old share is already read-write, no more permissions can be gained
342
+                    continue;
343
+                }
344
+            }
345
+
346
+            list(, $name) = Uri\split($row['principaluri']);
347
+            $uri = $row['uri'] . '_shared_by_' . $name;
348
+            $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')';
349
+            $components = [];
350
+            if ($row['components']) {
351
+                $components = explode(',',$row['components']);
352
+            }
353
+            $calendar = [
354
+                'id' => $row['id'],
355
+                'uri' => $uri,
356
+                'principaluri' => $this->convertPrincipal($principalUri, !$this->legacyEndpoint),
357
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
358
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
359
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
360
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp('transparent'),
361
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
362
+                $readOnlyPropertyName => $readOnly,
363
+            ];
364
+
365
+            foreach($this->propertyMap as $xmlName=>$dbName) {
366
+                $calendar[$xmlName] = $row[$dbName];
367
+            }
368
+
369
+            $this->addOwnerPrincipal($calendar);
370
+
371
+            $calendars[$calendar['id']] = $calendar;
372
+        }
373
+        $result->closeCursor();
374
+
375
+        return array_values($calendars);
376
+    }
377
+
378
+    /**
379
+     * @param $principalUri
380
+     * @return array
381
+     */
382
+    public function getUsersOwnCalendars($principalUri) {
383
+        $principalUri = $this->convertPrincipal($principalUri, true);
384
+        $fields = array_values($this->propertyMap);
385
+        $fields[] = 'id';
386
+        $fields[] = 'uri';
387
+        $fields[] = 'synctoken';
388
+        $fields[] = 'components';
389
+        $fields[] = 'principaluri';
390
+        $fields[] = 'transparent';
391
+        // Making fields a comma-delimited list
392
+        $query = $this->db->getQueryBuilder();
393
+        $query->select($fields)->from('calendars')
394
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
395
+            ->orderBy('calendarorder', 'ASC');
396
+        $stmt = $query->execute();
397
+        $calendars = [];
398
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
399
+            $components = [];
400
+            if ($row['components']) {
401
+                $components = explode(',',$row['components']);
402
+            }
403
+            $calendar = [
404
+                'id' => $row['id'],
405
+                'uri' => $row['uri'],
406
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
407
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
408
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
409
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
410
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
411
+            ];
412
+            foreach($this->propertyMap as $xmlName=>$dbName) {
413
+                $calendar[$xmlName] = $row[$dbName];
414
+            }
415
+
416
+            $this->addOwnerPrincipal($calendar);
417
+
418
+            if (!isset($calendars[$calendar['id']])) {
419
+                $calendars[$calendar['id']] = $calendar;
420
+            }
421
+        }
422
+        $stmt->closeCursor();
423
+        return array_values($calendars);
424
+    }
425
+
426
+
427
+    /**
428
+     * @param $uid
429
+     * @return string
430
+     */
431
+    private function getUserDisplayName($uid) {
432
+        if (!isset($this->userDisplayNames[$uid])) {
433
+            $user = $this->userManager->get($uid);
434
+
435
+            if ($user instanceof IUser) {
436
+                $this->userDisplayNames[$uid] = $user->getDisplayName();
437
+            } else {
438
+                $this->userDisplayNames[$uid] = $uid;
439
+            }
440
+        }
441
+
442
+        return $this->userDisplayNames[$uid];
443
+    }
444 444
 	
445
-	/**
446
-	 * @return array
447
-	 */
448
-	public function getPublicCalendars() {
449
-		$fields = array_values($this->propertyMap);
450
-		$fields[] = 'a.id';
451
-		$fields[] = 'a.uri';
452
-		$fields[] = 'a.synctoken';
453
-		$fields[] = 'a.components';
454
-		$fields[] = 'a.principaluri';
455
-		$fields[] = 'a.transparent';
456
-		$fields[] = 's.access';
457
-		$fields[] = 's.publicuri';
458
-		$calendars = [];
459
-		$query = $this->db->getQueryBuilder();
460
-		$result = $query->select($fields)
461
-			->from('dav_shares', 's')
462
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
463
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
464
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
465
-			->execute();
466
-
467
-		while($row = $result->fetch()) {
468
-			list(, $name) = Uri\split($row['principaluri']);
469
-			$row['displayname'] = $row['displayname'] . "($name)";
470
-			$components = [];
471
-			if ($row['components']) {
472
-				$components = explode(',',$row['components']);
473
-			}
474
-			$calendar = [
475
-				'id' => $row['id'],
476
-				'uri' => $row['publicuri'],
477
-				'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
478
-				'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
479
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
480
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
481
-				'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
482
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
483
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
484
-				'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
485
-			];
486
-
487
-			foreach($this->propertyMap as $xmlName=>$dbName) {
488
-				$calendar[$xmlName] = $row[$dbName];
489
-			}
490
-
491
-			$this->addOwnerPrincipal($calendar);
492
-
493
-			if (!isset($calendars[$calendar['id']])) {
494
-				$calendars[$calendar['id']] = $calendar;
495
-			}
496
-		}
497
-		$result->closeCursor();
498
-
499
-		return array_values($calendars);
500
-	}
501
-
502
-	/**
503
-	 * @param string $uri
504
-	 * @return array
505
-	 * @throws NotFound
506
-	 */
507
-	public function getPublicCalendar($uri) {
508
-		$fields = array_values($this->propertyMap);
509
-		$fields[] = 'a.id';
510
-		$fields[] = 'a.uri';
511
-		$fields[] = 'a.synctoken';
512
-		$fields[] = 'a.components';
513
-		$fields[] = 'a.principaluri';
514
-		$fields[] = 'a.transparent';
515
-		$fields[] = 's.access';
516
-		$fields[] = 's.publicuri';
517
-		$query = $this->db->getQueryBuilder();
518
-		$result = $query->select($fields)
519
-			->from('dav_shares', 's')
520
-			->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
521
-			->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
522
-			->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
523
-			->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
524
-			->execute();
525
-
526
-		$row = $result->fetch(\PDO::FETCH_ASSOC);
527
-
528
-		$result->closeCursor();
529
-
530
-		if ($row === false) {
531
-			throw new NotFound('Node with name \'' . $uri . '\' could not be found');
532
-		}
533
-
534
-		list(, $name) = Uri\split($row['principaluri']);
535
-		$row['displayname'] = $row['displayname'] . ' ' . "($name)";
536
-		$components = [];
537
-		if ($row['components']) {
538
-			$components = explode(',',$row['components']);
539
-		}
540
-		$calendar = [
541
-			'id' => $row['id'],
542
-			'uri' => $row['publicuri'],
543
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
544
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
545
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
546
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
547
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
548
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
549
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
550
-			'{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
551
-		];
552
-
553
-		foreach($this->propertyMap as $xmlName=>$dbName) {
554
-			$calendar[$xmlName] = $row[$dbName];
555
-		}
556
-
557
-		$this->addOwnerPrincipal($calendar);
558
-
559
-		return $calendar;
560
-
561
-	}
562
-
563
-	/**
564
-	 * @param string $principal
565
-	 * @param string $uri
566
-	 * @return array|null
567
-	 */
568
-	public function getCalendarByUri($principal, $uri) {
569
-		$fields = array_values($this->propertyMap);
570
-		$fields[] = 'id';
571
-		$fields[] = 'uri';
572
-		$fields[] = 'synctoken';
573
-		$fields[] = 'components';
574
-		$fields[] = 'principaluri';
575
-		$fields[] = 'transparent';
576
-
577
-		// Making fields a comma-delimited list
578
-		$query = $this->db->getQueryBuilder();
579
-		$query->select($fields)->from('calendars')
580
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
581
-			->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
582
-			->setMaxResults(1);
583
-		$stmt = $query->execute();
584
-
585
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
586
-		$stmt->closeCursor();
587
-		if ($row === false) {
588
-			return null;
589
-		}
590
-
591
-		$components = [];
592
-		if ($row['components']) {
593
-			$components = explode(',',$row['components']);
594
-		}
595
-
596
-		$calendar = [
597
-			'id' => $row['id'],
598
-			'uri' => $row['uri'],
599
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
600
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
601
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
602
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
603
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
604
-		];
605
-
606
-		foreach($this->propertyMap as $xmlName=>$dbName) {
607
-			$calendar[$xmlName] = $row[$dbName];
608
-		}
609
-
610
-		$this->addOwnerPrincipal($calendar);
611
-
612
-		return $calendar;
613
-	}
614
-
615
-	/**
616
-	 * @param $calendarId
617
-	 * @return array|null
618
-	 */
619
-	public function getCalendarById($calendarId) {
620
-		$fields = array_values($this->propertyMap);
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('id', $query->createNamedParameter($calendarId)))
632
-			->setMaxResults(1);
633
-		$stmt = $query->execute();
634
-
635
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
636
-		$stmt->closeCursor();
637
-		if ($row === false) {
638
-			return null;
639
-		}
640
-
641
-		$components = [];
642
-		if ($row['components']) {
643
-			$components = explode(',',$row['components']);
644
-		}
645
-
646
-		$calendar = [
647
-			'id' => $row['id'],
648
-			'uri' => $row['uri'],
649
-			'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
650
-			'{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
651
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
652
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
653
-			'{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
654
-		];
655
-
656
-		foreach($this->propertyMap as $xmlName=>$dbName) {
657
-			$calendar[$xmlName] = $row[$dbName];
658
-		}
659
-
660
-		$this->addOwnerPrincipal($calendar);
661
-
662
-		return $calendar;
663
-	}
664
-
665
-	/**
666
-	 * @param $subscriptionId
667
-	 */
668
-	public function getSubscriptionById($subscriptionId) {
669
-		$fields = array_values($this->subscriptionPropertyMap);
670
-		$fields[] = 'id';
671
-		$fields[] = 'uri';
672
-		$fields[] = 'source';
673
-		$fields[] = 'synctoken';
674
-		$fields[] = 'principaluri';
675
-		$fields[] = 'lastmodified';
676
-
677
-		$query = $this->db->getQueryBuilder();
678
-		$query->select($fields)
679
-			->from('calendarsubscriptions')
680
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
681
-			->orderBy('calendarorder', 'asc');
682
-		$stmt =$query->execute();
683
-
684
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
685
-		$stmt->closeCursor();
686
-		if ($row === false) {
687
-			return null;
688
-		}
689
-
690
-		$subscription = [
691
-			'id'           => $row['id'],
692
-			'uri'          => $row['uri'],
693
-			'principaluri' => $row['principaluri'],
694
-			'source'       => $row['source'],
695
-			'lastmodified' => $row['lastmodified'],
696
-			'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
697
-			'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
698
-		];
699
-
700
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
701
-			if (!is_null($row[$dbName])) {
702
-				$subscription[$xmlName] = $row[$dbName];
703
-			}
704
-		}
705
-
706
-		return $subscription;
707
-	}
708
-
709
-	/**
710
-	 * Creates a new calendar for a principal.
711
-	 *
712
-	 * If the creation was a success, an id must be returned that can be used to reference
713
-	 * this calendar in other methods, such as updateCalendar.
714
-	 *
715
-	 * @param string $principalUri
716
-	 * @param string $calendarUri
717
-	 * @param array $properties
718
-	 * @return int
719
-	 * @suppress SqlInjectionChecker
720
-	 */
721
-	function createCalendar($principalUri, $calendarUri, array $properties) {
722
-		$values = [
723
-			'principaluri' => $this->convertPrincipal($principalUri, true),
724
-			'uri'          => $calendarUri,
725
-			'synctoken'    => 1,
726
-			'transparent'  => 0,
727
-			'components'   => 'VEVENT,VTODO',
728
-			'displayname'  => $calendarUri
729
-		];
730
-
731
-		// Default value
732
-		$sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
733
-		if (isset($properties[$sccs])) {
734
-			if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
735
-				throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
736
-			}
737
-			$values['components'] = implode(',',$properties[$sccs]->getValue());
738
-		}
739
-		$transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
740
-		if (isset($properties[$transp])) {
741
-			$values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
742
-		}
743
-
744
-		foreach($this->propertyMap as $xmlName=>$dbName) {
745
-			if (isset($properties[$xmlName])) {
746
-				$values[$dbName] = $properties[$xmlName];
747
-			}
748
-		}
749
-
750
-		$query = $this->db->getQueryBuilder();
751
-		$query->insert('calendars');
752
-		foreach($values as $column => $value) {
753
-			$query->setValue($column, $query->createNamedParameter($value));
754
-		}
755
-		$query->execute();
756
-		$calendarId = $query->getLastInsertId();
757
-
758
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
759
-			'\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
760
-			[
761
-				'calendarId' => $calendarId,
762
-				'calendarData' => $this->getCalendarById($calendarId),
763
-		]));
764
-
765
-		return $calendarId;
766
-	}
767
-
768
-	/**
769
-	 * Updates properties for a calendar.
770
-	 *
771
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
772
-	 * To do the actual updates, you must tell this object which properties
773
-	 * you're going to process with the handle() method.
774
-	 *
775
-	 * Calling the handle method is like telling the PropPatch object "I
776
-	 * promise I can handle updating this property".
777
-	 *
778
-	 * Read the PropPatch documentation for more info and examples.
779
-	 *
780
-	 * @param mixed $calendarId
781
-	 * @param PropPatch $propPatch
782
-	 * @return void
783
-	 */
784
-	function updateCalendar($calendarId, PropPatch $propPatch) {
785
-		$supportedProperties = array_keys($this->propertyMap);
786
-		$supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
787
-
788
-		/**
789
-		 * @suppress SqlInjectionChecker
790
-		 */
791
-		$propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
792
-			$newValues = [];
793
-			foreach ($mutations as $propertyName => $propertyValue) {
794
-
795
-				switch ($propertyName) {
796
-					case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
797
-						$fieldName = 'transparent';
798
-						$newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
799
-						break;
800
-					default :
801
-						$fieldName = $this->propertyMap[$propertyName];
802
-						$newValues[$fieldName] = $propertyValue;
803
-						break;
804
-				}
805
-
806
-			}
807
-			$query = $this->db->getQueryBuilder();
808
-			$query->update('calendars');
809
-			foreach ($newValues as $fieldName => $value) {
810
-				$query->set($fieldName, $query->createNamedParameter($value));
811
-			}
812
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
813
-			$query->execute();
814
-
815
-			$this->addChange($calendarId, "", 2);
816
-
817
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
818
-				'\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
819
-				[
820
-					'calendarId' => $calendarId,
821
-					'calendarData' => $this->getCalendarById($calendarId),
822
-					'shares' => $this->getShares($calendarId),
823
-					'propertyMutations' => $mutations,
824
-			]));
825
-
826
-			return true;
827
-		});
828
-	}
829
-
830
-	/**
831
-	 * Delete a calendar and all it's objects
832
-	 *
833
-	 * @param mixed $calendarId
834
-	 * @return void
835
-	 */
836
-	function deleteCalendar($calendarId) {
837
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
838
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
839
-			[
840
-				'calendarId' => $calendarId,
841
-				'calendarData' => $this->getCalendarById($calendarId),
842
-				'shares' => $this->getShares($calendarId),
843
-		]));
844
-
845
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
846
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
847
-
848
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
849
-		$stmt->execute([$calendarId]);
850
-
851
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
852
-		$stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
853
-
854
-		$this->calendarSharingBackend->deleteAllShares($calendarId);
855
-
856
-		$query = $this->db->getQueryBuilder();
857
-		$query->delete($this->dbObjectPropertiesTable)
858
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
859
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
860
-			->execute();
861
-	}
862
-
863
-	/**
864
-	 * Delete all of an user's shares
865
-	 *
866
-	 * @param string $principaluri
867
-	 * @return void
868
-	 */
869
-	function deleteAllSharesByUser($principaluri) {
870
-		$this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
871
-	}
872
-
873
-	/**
874
-	 * Returns all calendar objects within a calendar.
875
-	 *
876
-	 * Every item contains an array with the following keys:
877
-	 *   * calendardata - The iCalendar-compatible calendar data
878
-	 *   * uri - a unique key which will be used to construct the uri. This can
879
-	 *     be any arbitrary string, but making sure it ends with '.ics' is a
880
-	 *     good idea. This is only the basename, or filename, not the full
881
-	 *     path.
882
-	 *   * lastmodified - a timestamp of the last modification time
883
-	 *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
884
-	 *   '"abcdef"')
885
-	 *   * size - The size of the calendar objects, in bytes.
886
-	 *   * component - optional, a string containing the type of object, such
887
-	 *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
888
-	 *     the Content-Type header.
889
-	 *
890
-	 * Note that the etag is optional, but it's highly encouraged to return for
891
-	 * speed reasons.
892
-	 *
893
-	 * The calendardata is also optional. If it's not returned
894
-	 * 'getCalendarObject' will be called later, which *is* expected to return
895
-	 * calendardata.
896
-	 *
897
-	 * If neither etag or size are specified, the calendardata will be
898
-	 * used/fetched to determine these numbers. If both are specified the
899
-	 * amount of times this is needed is reduced by a great degree.
900
-	 *
901
-	 * @param mixed $id
902
-	 * @param int $calendarType
903
-	 * @return array
904
-	 */
905
-	public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
906
-		$query = $this->db->getQueryBuilder();
907
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
908
-			->from('calendarobjects')
909
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
910
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
911
-		$stmt = $query->execute();
912
-
913
-		$result = [];
914
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
915
-			$result[] = [
916
-				'id'           => $row['id'],
917
-				'uri'          => $row['uri'],
918
-				'lastmodified' => $row['lastmodified'],
919
-				'etag'         => '"' . $row['etag'] . '"',
920
-				'calendarid'   => $row['calendarid'],
921
-				'size'         => (int)$row['size'],
922
-				'component'    => strtolower($row['componenttype']),
923
-				'classification'=> (int)$row['classification']
924
-			];
925
-		}
926
-
927
-		return $result;
928
-	}
929
-
930
-	/**
931
-	 * Returns information from a single calendar object, based on it's object
932
-	 * uri.
933
-	 *
934
-	 * The object uri is only the basename, or filename and not a full path.
935
-	 *
936
-	 * The returned array must have the same keys as getCalendarObjects. The
937
-	 * 'calendardata' object is required here though, while it's not required
938
-	 * for getCalendarObjects.
939
-	 *
940
-	 * This method must return null if the object did not exist.
941
-	 *
942
-	 * @param mixed $id
943
-	 * @param string $objectUri
944
-	 * @param int $calendarType
945
-	 * @return array|null
946
-	 */
947
-	public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
948
-		$query = $this->db->getQueryBuilder();
949
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
950
-			->from('calendarobjects')
951
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
952
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
953
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
954
-		$stmt = $query->execute();
955
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
956
-
957
-		if(!$row) {
958
-			return null;
959
-		}
960
-
961
-		return [
962
-			'id'            => $row['id'],
963
-			'uri'           => $row['uri'],
964
-			'lastmodified'  => $row['lastmodified'],
965
-			'etag'          => '"' . $row['etag'] . '"',
966
-			'calendarid'    => $row['calendarid'],
967
-			'size'          => (int)$row['size'],
968
-			'calendardata'  => $this->readBlob($row['calendardata']),
969
-			'component'     => strtolower($row['componenttype']),
970
-			'classification'=> (int)$row['classification']
971
-		];
972
-	}
973
-
974
-	/**
975
-	 * Returns a list of calendar objects.
976
-	 *
977
-	 * This method should work identical to getCalendarObject, but instead
978
-	 * return all the calendar objects in the list as an array.
979
-	 *
980
-	 * If the backend supports this, it may allow for some speed-ups.
981
-	 *
982
-	 * @param mixed $calendarId
983
-	 * @param string[] $uris
984
-	 * @param int $calendarType
985
-	 * @return array
986
-	 */
987
-	public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
988
-		if (empty($uris)) {
989
-			return [];
990
-		}
991
-
992
-		$chunks = array_chunk($uris, 100);
993
-		$objects = [];
994
-
995
-		$query = $this->db->getQueryBuilder();
996
-		$query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
997
-			->from('calendarobjects')
998
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
999
-			->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1000
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1001
-
1002
-		foreach ($chunks as $uris) {
1003
-			$query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1004
-			$result = $query->execute();
1005
-
1006
-			while ($row = $result->fetch()) {
1007
-				$objects[] = [
1008
-					'id'           => $row['id'],
1009
-					'uri'          => $row['uri'],
1010
-					'lastmodified' => $row['lastmodified'],
1011
-					'etag'         => '"' . $row['etag'] . '"',
1012
-					'calendarid'   => $row['calendarid'],
1013
-					'size'         => (int)$row['size'],
1014
-					'calendardata' => $this->readBlob($row['calendardata']),
1015
-					'component'    => strtolower($row['componenttype']),
1016
-					'classification' => (int)$row['classification']
1017
-				];
1018
-			}
1019
-			$result->closeCursor();
1020
-		}
1021
-
1022
-		return $objects;
1023
-	}
1024
-
1025
-	/**
1026
-	 * Creates a new calendar object.
1027
-	 *
1028
-	 * The object uri is only the basename, or filename and not a full path.
1029
-	 *
1030
-	 * It is possible return an etag from this function, which will be used in
1031
-	 * the response to this PUT request. Note that the ETag must be surrounded
1032
-	 * by double-quotes.
1033
-	 *
1034
-	 * However, you should only really return this ETag if you don't mangle the
1035
-	 * calendar-data. If the result of a subsequent GET to this object is not
1036
-	 * the exact same as this request body, you should omit the ETag.
1037
-	 *
1038
-	 * @param mixed $calendarId
1039
-	 * @param string $objectUri
1040
-	 * @param string $calendarData
1041
-	 * @param int $calendarType
1042
-	 * @return string
1043
-	 */
1044
-	function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1045
-		$extraData = $this->getDenormalizedData($calendarData);
1046
-
1047
-		$q = $this->db->getQueryBuilder();
1048
-		$q->select($q->func()->count('*'))
1049
-			->from('calendarobjects')
1050
-			->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1051
-			->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1052
-			->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1053
-
1054
-		$result = $q->execute();
1055
-		$count = (int) $result->fetchColumn();
1056
-		$result->closeCursor();
1057
-
1058
-		if ($count !== 0) {
1059
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1060
-		}
1061
-
1062
-		$query = $this->db->getQueryBuilder();
1063
-		$query->insert('calendarobjects')
1064
-			->values([
1065
-				'calendarid' => $query->createNamedParameter($calendarId),
1066
-				'uri' => $query->createNamedParameter($objectUri),
1067
-				'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1068
-				'lastmodified' => $query->createNamedParameter(time()),
1069
-				'etag' => $query->createNamedParameter($extraData['etag']),
1070
-				'size' => $query->createNamedParameter($extraData['size']),
1071
-				'componenttype' => $query->createNamedParameter($extraData['componentType']),
1072
-				'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1073
-				'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1074
-				'classification' => $query->createNamedParameter($extraData['classification']),
1075
-				'uid' => $query->createNamedParameter($extraData['uid']),
1076
-				'calendartype' => $query->createNamedParameter($calendarType),
1077
-			])
1078
-			->execute();
1079
-
1080
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1081
-
1082
-		if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1083
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1084
-				'\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1085
-				[
1086
-					'calendarId' => $calendarId,
1087
-					'calendarData' => $this->getCalendarById($calendarId),
1088
-					'shares' => $this->getShares($calendarId),
1089
-					'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1090
-				]
1091
-			));
1092
-		} else {
1093
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1094
-				'\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1095
-				[
1096
-					'subscriptionId' => $calendarId,
1097
-					'calendarData' => $this->getCalendarById($calendarId),
1098
-					'shares' => $this->getShares($calendarId),
1099
-					'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1100
-				]
1101
-			));
1102
-		}
1103
-		$this->addChange($calendarId, $objectUri, 1, $calendarType);
1104
-
1105
-		return '"' . $extraData['etag'] . '"';
1106
-	}
1107
-
1108
-	/**
1109
-	 * Updates an existing calendarobject, based on it's uri.
1110
-	 *
1111
-	 * The object uri is only the basename, or filename and not a full path.
1112
-	 *
1113
-	 * It is possible return an etag from this function, which will be used in
1114
-	 * the response to this PUT request. Note that the ETag must be surrounded
1115
-	 * by double-quotes.
1116
-	 *
1117
-	 * However, you should only really return this ETag if you don't mangle the
1118
-	 * calendar-data. If the result of a subsequent GET to this object is not
1119
-	 * the exact same as this request body, you should omit the ETag.
1120
-	 *
1121
-	 * @param mixed $calendarId
1122
-	 * @param string $objectUri
1123
-	 * @param string $calendarData
1124
-	 * @param int $calendarType
1125
-	 * @return string
1126
-	 */
1127
-	function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1128
-		$extraData = $this->getDenormalizedData($calendarData);
1129
-
1130
-		$query = $this->db->getQueryBuilder();
1131
-		$query->update('calendarobjects')
1132
-				->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1133
-				->set('lastmodified', $query->createNamedParameter(time()))
1134
-				->set('etag', $query->createNamedParameter($extraData['etag']))
1135
-				->set('size', $query->createNamedParameter($extraData['size']))
1136
-				->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1137
-				->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1138
-				->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1139
-				->set('classification', $query->createNamedParameter($extraData['classification']))
1140
-				->set('uid', $query->createNamedParameter($extraData['uid']))
1141
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1142
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1143
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1144
-			->execute();
1145
-
1146
-		$this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1147
-
1148
-		$data = $this->getCalendarObject($calendarId, $objectUri);
1149
-		if (is_array($data)) {
1150
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1151
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1152
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1153
-					[
1154
-						'calendarId' => $calendarId,
1155
-						'calendarData' => $this->getCalendarById($calendarId),
1156
-						'shares' => $this->getShares($calendarId),
1157
-						'objectData' => $data,
1158
-					]
1159
-				));
1160
-			} else {
1161
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1162
-					'\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1163
-					[
1164
-						'subscriptionId' => $calendarId,
1165
-						'calendarData' => $this->getCalendarById($calendarId),
1166
-						'shares' => $this->getShares($calendarId),
1167
-						'objectData' => $data,
1168
-					]
1169
-				));
1170
-			}
1171
-		}
1172
-		$this->addChange($calendarId, $objectUri, 2, $calendarType);
1173
-
1174
-		return '"' . $extraData['etag'] . '"';
1175
-	}
1176
-
1177
-	/**
1178
-	 * @param int $calendarObjectId
1179
-	 * @param int $classification
1180
-	 */
1181
-	public function setClassification($calendarObjectId, $classification) {
1182
-		if (!in_array($classification, [
1183
-			self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1184
-		])) {
1185
-			throw new \InvalidArgumentException();
1186
-		}
1187
-		$query = $this->db->getQueryBuilder();
1188
-		$query->update('calendarobjects')
1189
-			->set('classification', $query->createNamedParameter($classification))
1190
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1191
-			->execute();
1192
-	}
1193
-
1194
-	/**
1195
-	 * Deletes an existing calendar object.
1196
-	 *
1197
-	 * The object uri is only the basename, or filename and not a full path.
1198
-	 *
1199
-	 * @param mixed $calendarId
1200
-	 * @param string $objectUri
1201
-	 * @param int $calendarType
1202
-	 * @return void
1203
-	 */
1204
-	function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1205
-		$data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1206
-		if (is_array($data)) {
1207
-			if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1208
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1209
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1210
-					[
1211
-						'calendarId' => $calendarId,
1212
-						'calendarData' => $this->getCalendarById($calendarId),
1213
-						'shares' => $this->getShares($calendarId),
1214
-						'objectData' => $data,
1215
-					]
1216
-				));
1217
-			} else {
1218
-				$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1219
-					'\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1220
-					[
1221
-						'subscriptionId' => $calendarId,
1222
-						'calendarData' => $this->getCalendarById($calendarId),
1223
-						'shares' => $this->getShares($calendarId),
1224
-						'objectData' => $data,
1225
-					]
1226
-				));
1227
-			}
1228
-		}
1229
-
1230
-		$stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1231
-		$stmt->execute([$calendarId, $objectUri, $calendarType]);
1232
-
1233
-		$this->purgeProperties($calendarId, $data['id'], $calendarType);
1234
-
1235
-		$this->addChange($calendarId, $objectUri, 3, $calendarType);
1236
-	}
1237
-
1238
-	/**
1239
-	 * Performs a calendar-query on the contents of this calendar.
1240
-	 *
1241
-	 * The calendar-query is defined in RFC4791 : CalDAV. Using the
1242
-	 * calendar-query it is possible for a client to request a specific set of
1243
-	 * object, based on contents of iCalendar properties, date-ranges and
1244
-	 * iCalendar component types (VTODO, VEVENT).
1245
-	 *
1246
-	 * This method should just return a list of (relative) urls that match this
1247
-	 * query.
1248
-	 *
1249
-	 * The list of filters are specified as an array. The exact array is
1250
-	 * documented by Sabre\CalDAV\CalendarQueryParser.
1251
-	 *
1252
-	 * Note that it is extremely likely that getCalendarObject for every path
1253
-	 * returned from this method will be called almost immediately after. You
1254
-	 * may want to anticipate this to speed up these requests.
1255
-	 *
1256
-	 * This method provides a default implementation, which parses *all* the
1257
-	 * iCalendar objects in the specified calendar.
1258
-	 *
1259
-	 * This default may well be good enough for personal use, and calendars
1260
-	 * that aren't very large. But if you anticipate high usage, big calendars
1261
-	 * or high loads, you are strongly advised to optimize certain paths.
1262
-	 *
1263
-	 * The best way to do so is override this method and to optimize
1264
-	 * specifically for 'common filters'.
1265
-	 *
1266
-	 * Requests that are extremely common are:
1267
-	 *   * requests for just VEVENTS
1268
-	 *   * requests for just VTODO
1269
-	 *   * requests with a time-range-filter on either VEVENT or VTODO.
1270
-	 *
1271
-	 * ..and combinations of these requests. It may not be worth it to try to
1272
-	 * handle every possible situation and just rely on the (relatively
1273
-	 * easy to use) CalendarQueryValidator to handle the rest.
1274
-	 *
1275
-	 * Note that especially time-range-filters may be difficult to parse. A
1276
-	 * time-range filter specified on a VEVENT must for instance also handle
1277
-	 * recurrence rules correctly.
1278
-	 * A good example of how to interprete all these filters can also simply
1279
-	 * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1280
-	 * as possible, so it gives you a good idea on what type of stuff you need
1281
-	 * to think of.
1282
-	 *
1283
-	 * @param mixed $id
1284
-	 * @param array $filters
1285
-	 * @param int $calendarType
1286
-	 * @return array
1287
-	 */
1288
-	public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1289
-		$componentType = null;
1290
-		$requirePostFilter = true;
1291
-		$timeRange = null;
1292
-
1293
-		// if no filters were specified, we don't need to filter after a query
1294
-		if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1295
-			$requirePostFilter = false;
1296
-		}
1297
-
1298
-		// Figuring out if there's a component filter
1299
-		if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1300
-			$componentType = $filters['comp-filters'][0]['name'];
1301
-
1302
-			// Checking if we need post-filters
1303
-			if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1304
-				$requirePostFilter = false;
1305
-			}
1306
-			// There was a time-range filter
1307
-			if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1308
-				$timeRange = $filters['comp-filters'][0]['time-range'];
1309
-
1310
-				// If start time OR the end time is not specified, we can do a
1311
-				// 100% accurate mysql query.
1312
-				if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1313
-					$requirePostFilter = false;
1314
-				}
1315
-			}
1316
-
1317
-		}
1318
-		$columns = ['uri'];
1319
-		if ($requirePostFilter) {
1320
-			$columns = ['uri', 'calendardata'];
1321
-		}
1322
-		$query = $this->db->getQueryBuilder();
1323
-		$query->select($columns)
1324
-			->from('calendarobjects')
1325
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1326
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1327
-
1328
-		if ($componentType) {
1329
-			$query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1330
-		}
1331
-
1332
-		if ($timeRange && $timeRange['start']) {
1333
-			$query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1334
-		}
1335
-		if ($timeRange && $timeRange['end']) {
1336
-			$query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1337
-		}
1338
-
1339
-		$stmt = $query->execute();
1340
-
1341
-		$result = [];
1342
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1343
-			if ($requirePostFilter) {
1344
-				// validateFilterForObject will parse the calendar data
1345
-				// catch parsing errors
1346
-				try {
1347
-					$matches = $this->validateFilterForObject($row, $filters);
1348
-				} catch(ParseException $ex) {
1349
-					$this->logger->logException($ex, [
1350
-						'app' => 'dav',
1351
-						'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1352
-					]);
1353
-					continue;
1354
-				} catch (InvalidDataException $ex) {
1355
-					$this->logger->logException($ex, [
1356
-						'app' => 'dav',
1357
-						'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1358
-					]);
1359
-					continue;
1360
-				}
1361
-
1362
-				if (!$matches) {
1363
-					continue;
1364
-				}
1365
-			}
1366
-			$result[] = $row['uri'];
1367
-		}
1368
-
1369
-		return $result;
1370
-	}
1371
-
1372
-	/**
1373
-	 * custom Nextcloud search extension for CalDAV
1374
-	 *
1375
-	 * TODO - this should optionally cover cached calendar objects as well
1376
-	 *
1377
-	 * @param string $principalUri
1378
-	 * @param array $filters
1379
-	 * @param integer|null $limit
1380
-	 * @param integer|null $offset
1381
-	 * @return array
1382
-	 */
1383
-	public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1384
-		$calendars = $this->getCalendarsForUser($principalUri);
1385
-		$ownCalendars = [];
1386
-		$sharedCalendars = [];
1387
-
1388
-		$uriMapper = [];
1389
-
1390
-		foreach($calendars as $calendar) {
1391
-			if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1392
-				$ownCalendars[] = $calendar['id'];
1393
-			} else {
1394
-				$sharedCalendars[] = $calendar['id'];
1395
-			}
1396
-			$uriMapper[$calendar['id']] = $calendar['uri'];
1397
-		}
1398
-		if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1399
-			return [];
1400
-		}
1401
-
1402
-		$query = $this->db->getQueryBuilder();
1403
-		// Calendar id expressions
1404
-		$calendarExpressions = [];
1405
-		foreach($ownCalendars as $id) {
1406
-			$calendarExpressions[] = $query->expr()->andX(
1407
-				$query->expr()->eq('c.calendarid',
1408
-					$query->createNamedParameter($id)),
1409
-				$query->expr()->eq('c.calendartype',
1410
-						$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1411
-		}
1412
-		foreach($sharedCalendars as $id) {
1413
-			$calendarExpressions[] = $query->expr()->andX(
1414
-				$query->expr()->eq('c.calendarid',
1415
-					$query->createNamedParameter($id)),
1416
-				$query->expr()->eq('c.classification',
1417
-					$query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1418
-				$query->expr()->eq('c.calendartype',
1419
-					$query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1420
-		}
1421
-
1422
-		if (count($calendarExpressions) === 1) {
1423
-			$calExpr = $calendarExpressions[0];
1424
-		} else {
1425
-			$calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1426
-		}
1427
-
1428
-		// Component expressions
1429
-		$compExpressions = [];
1430
-		foreach($filters['comps'] as $comp) {
1431
-			$compExpressions[] = $query->expr()
1432
-				->eq('c.componenttype', $query->createNamedParameter($comp));
1433
-		}
1434
-
1435
-		if (count($compExpressions) === 1) {
1436
-			$compExpr = $compExpressions[0];
1437
-		} else {
1438
-			$compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1439
-		}
1440
-
1441
-		if (!isset($filters['props'])) {
1442
-			$filters['props'] = [];
1443
-		}
1444
-		if (!isset($filters['params'])) {
1445
-			$filters['params'] = [];
1446
-		}
1447
-
1448
-		$propParamExpressions = [];
1449
-		foreach($filters['props'] as $prop) {
1450
-			$propParamExpressions[] = $query->expr()->andX(
1451
-				$query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1452
-				$query->expr()->isNull('i.parameter')
1453
-			);
1454
-		}
1455
-		foreach($filters['params'] as $param) {
1456
-			$propParamExpressions[] = $query->expr()->andX(
1457
-				$query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1458
-				$query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1459
-			);
1460
-		}
1461
-
1462
-		if (count($propParamExpressions) === 1) {
1463
-			$propParamExpr = $propParamExpressions[0];
1464
-		} else {
1465
-			$propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1466
-		}
1467
-
1468
-		$query->select(['c.calendarid', 'c.uri'])
1469
-			->from($this->dbObjectPropertiesTable, 'i')
1470
-			->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1471
-			->where($calExpr)
1472
-			->andWhere($compExpr)
1473
-			->andWhere($propParamExpr)
1474
-			->andWhere($query->expr()->iLike('i.value',
1475
-				$query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1476
-
1477
-		if ($offset) {
1478
-			$query->setFirstResult($offset);
1479
-		}
1480
-		if ($limit) {
1481
-			$query->setMaxResults($limit);
1482
-		}
1483
-
1484
-		$stmt = $query->execute();
1485
-
1486
-		$result = [];
1487
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1488
-			$path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1489
-			if (!in_array($path, $result)) {
1490
-				$result[] = $path;
1491
-			}
1492
-		}
1493
-
1494
-		return $result;
1495
-	}
1496
-
1497
-	/**
1498
-	 * used for Nextcloud's calendar API
1499
-	 *
1500
-	 * @param array $calendarInfo
1501
-	 * @param string $pattern
1502
-	 * @param array $searchProperties
1503
-	 * @param array $options
1504
-	 * @param integer|null $limit
1505
-	 * @param integer|null $offset
1506
-	 *
1507
-	 * @return array
1508
-	 */
1509
-	public function search(array $calendarInfo, $pattern, array $searchProperties,
1510
-						   array $options, $limit, $offset) {
1511
-		$outerQuery = $this->db->getQueryBuilder();
1512
-		$innerQuery = $this->db->getQueryBuilder();
1513
-
1514
-		$innerQuery->selectDistinct('op.objectid')
1515
-			->from($this->dbObjectPropertiesTable, 'op')
1516
-			->andWhere($innerQuery->expr()->eq('op.calendarid',
1517
-				$outerQuery->createNamedParameter($calendarInfo['id'])))
1518
-			->andWhere($innerQuery->expr()->eq('op.calendartype',
1519
-				$outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1520
-
1521
-		// only return public items for shared calendars for now
1522
-		if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1523
-			$innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1524
-				$outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1525
-		}
1526
-
1527
-		$or = $innerQuery->expr()->orX();
1528
-		foreach($searchProperties as $searchProperty) {
1529
-			$or->add($innerQuery->expr()->eq('op.name',
1530
-				$outerQuery->createNamedParameter($searchProperty)));
1531
-		}
1532
-		$innerQuery->andWhere($or);
1533
-
1534
-		if ($pattern !== '') {
1535
-			$innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1536
-				$outerQuery->createNamedParameter('%' .
1537
-					$this->db->escapeLikeParameter($pattern) . '%')));
1538
-		}
1539
-
1540
-		$outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1541
-			->from('calendarobjects', 'c');
1542
-
1543
-		if (isset($options['timerange'])) {
1544
-			if (isset($options['timerange']['start'])) {
1545
-				$outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1546
-					$outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
1547
-
1548
-			}
1549
-			if (isset($options['timerange']['end'])) {
1550
-				$outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1551
-					$outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
1552
-			}
1553
-		}
1554
-
1555
-		if (isset($options['types'])) {
1556
-			$or = $outerQuery->expr()->orX();
1557
-			foreach($options['types'] as $type) {
1558
-				$or->add($outerQuery->expr()->eq('componenttype',
1559
-					$outerQuery->createNamedParameter($type)));
1560
-			}
1561
-			$outerQuery->andWhere($or);
1562
-		}
1563
-
1564
-		$outerQuery->andWhere($outerQuery->expr()->in('c.id',
1565
-			$outerQuery->createFunction($innerQuery->getSQL())));
1566
-
1567
-		if ($offset) {
1568
-			$outerQuery->setFirstResult($offset);
1569
-		}
1570
-		if ($limit) {
1571
-			$outerQuery->setMaxResults($limit);
1572
-		}
1573
-
1574
-		$result = $outerQuery->execute();
1575
-		$calendarObjects = $result->fetchAll();
1576
-
1577
-		return array_map(function($o) {
1578
-			$calendarData = Reader::read($o['calendardata']);
1579
-			$comps = $calendarData->getComponents();
1580
-			$objects = [];
1581
-			$timezones = [];
1582
-			foreach($comps as $comp) {
1583
-				if ($comp instanceof VTimeZone) {
1584
-					$timezones[] = $comp;
1585
-				} else {
1586
-					$objects[] = $comp;
1587
-				}
1588
-			}
1589
-
1590
-			return [
1591
-				'id' => $o['id'],
1592
-				'type' => $o['componenttype'],
1593
-				'uid' => $o['uid'],
1594
-				'uri' => $o['uri'],
1595
-				'objects' => array_map(function($c) {
1596
-					return $this->transformSearchData($c);
1597
-				}, $objects),
1598
-				'timezones' => array_map(function($c) {
1599
-					return $this->transformSearchData($c);
1600
-				}, $timezones),
1601
-			];
1602
-		}, $calendarObjects);
1603
-	}
1604
-
1605
-	/**
1606
-	 * @param Component $comp
1607
-	 * @return array
1608
-	 */
1609
-	private function transformSearchData(Component $comp) {
1610
-		$data = [];
1611
-		/** @var Component[] $subComponents */
1612
-		$subComponents = $comp->getComponents();
1613
-		/** @var Property[] $properties */
1614
-		$properties = array_filter($comp->children(), function($c) {
1615
-			return $c instanceof Property;
1616
-		});
1617
-		$validationRules = $comp->getValidationRules();
1618
-
1619
-		foreach($subComponents as $subComponent) {
1620
-			$name = $subComponent->name;
1621
-			if (!isset($data[$name])) {
1622
-				$data[$name] = [];
1623
-			}
1624
-			$data[$name][] = $this->transformSearchData($subComponent);
1625
-		}
1626
-
1627
-		foreach($properties as $property) {
1628
-			$name = $property->name;
1629
-			if (!isset($validationRules[$name])) {
1630
-				$validationRules[$name] = '*';
1631
-			}
1632
-
1633
-			$rule = $validationRules[$property->name];
1634
-			if ($rule === '+' || $rule === '*') { // multiple
1635
-				if (!isset($data[$name])) {
1636
-					$data[$name] = [];
1637
-				}
1638
-
1639
-				$data[$name][] = $this->transformSearchProperty($property);
1640
-			} else { // once
1641
-				$data[$name] = $this->transformSearchProperty($property);
1642
-			}
1643
-		}
1644
-
1645
-		return $data;
1646
-	}
1647
-
1648
-	/**
1649
-	 * @param Property $prop
1650
-	 * @return array
1651
-	 */
1652
-	private function transformSearchProperty(Property $prop) {
1653
-		// No need to check Date, as it extends DateTime
1654
-		if ($prop instanceof Property\ICalendar\DateTime) {
1655
-			$value = $prop->getDateTime();
1656
-		} else {
1657
-			$value = $prop->getValue();
1658
-		}
1659
-
1660
-		return [
1661
-			$value,
1662
-			$prop->parameters()
1663
-		];
1664
-	}
1665
-
1666
-	/**
1667
-	 * Searches through all of a users calendars and calendar objects to find
1668
-	 * an object with a specific UID.
1669
-	 *
1670
-	 * This method should return the path to this object, relative to the
1671
-	 * calendar home, so this path usually only contains two parts:
1672
-	 *
1673
-	 * calendarpath/objectpath.ics
1674
-	 *
1675
-	 * If the uid is not found, return null.
1676
-	 *
1677
-	 * This method should only consider * objects that the principal owns, so
1678
-	 * any calendars owned by other principals that also appear in this
1679
-	 * collection should be ignored.
1680
-	 *
1681
-	 * @param string $principalUri
1682
-	 * @param string $uid
1683
-	 * @return string|null
1684
-	 */
1685
-	function getCalendarObjectByUID($principalUri, $uid) {
1686
-
1687
-		$query = $this->db->getQueryBuilder();
1688
-		$query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1689
-			->from('calendarobjects', 'co')
1690
-			->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1691
-			->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1692
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
1693
-			->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1694
-
1695
-		$stmt = $query->execute();
1696
-
1697
-		if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1698
-			return $row['calendaruri'] . '/' . $row['objecturi'];
1699
-		}
1700
-
1701
-		return null;
1702
-	}
1703
-
1704
-	/**
1705
-	 * The getChanges method returns all the changes that have happened, since
1706
-	 * the specified syncToken in the specified calendar.
1707
-	 *
1708
-	 * This function should return an array, such as the following:
1709
-	 *
1710
-	 * [
1711
-	 *   'syncToken' => 'The current synctoken',
1712
-	 *   'added'   => [
1713
-	 *      'new.txt',
1714
-	 *   ],
1715
-	 *   'modified'   => [
1716
-	 *      'modified.txt',
1717
-	 *   ],
1718
-	 *   'deleted' => [
1719
-	 *      'foo.php.bak',
1720
-	 *      'old.txt'
1721
-	 *   ]
1722
-	 * );
1723
-	 *
1724
-	 * The returned syncToken property should reflect the *current* syncToken
1725
-	 * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1726
-	 * property This is * needed here too, to ensure the operation is atomic.
1727
-	 *
1728
-	 * If the $syncToken argument is specified as null, this is an initial
1729
-	 * sync, and all members should be reported.
1730
-	 *
1731
-	 * The modified property is an array of nodenames that have changed since
1732
-	 * the last token.
1733
-	 *
1734
-	 * The deleted property is an array with nodenames, that have been deleted
1735
-	 * from collection.
1736
-	 *
1737
-	 * The $syncLevel argument is basically the 'depth' of the report. If it's
1738
-	 * 1, you only have to report changes that happened only directly in
1739
-	 * immediate descendants. If it's 2, it should also include changes from
1740
-	 * the nodes below the child collections. (grandchildren)
1741
-	 *
1742
-	 * The $limit argument allows a client to specify how many results should
1743
-	 * be returned at most. If the limit is not specified, it should be treated
1744
-	 * as infinite.
1745
-	 *
1746
-	 * If the limit (infinite or not) is higher than you're willing to return,
1747
-	 * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1748
-	 *
1749
-	 * If the syncToken is expired (due to data cleanup) or unknown, you must
1750
-	 * return null.
1751
-	 *
1752
-	 * The limit is 'suggestive'. You are free to ignore it.
1753
-	 *
1754
-	 * @param string $calendarId
1755
-	 * @param string $syncToken
1756
-	 * @param int $syncLevel
1757
-	 * @param int $limit
1758
-	 * @param int $calendarType
1759
-	 * @return array
1760
-	 */
1761
-	function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1762
-		// Current synctoken
1763
-		$stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1764
-		$stmt->execute([ $calendarId ]);
1765
-		$currentToken = $stmt->fetchColumn(0);
1766
-
1767
-		if (is_null($currentToken)) {
1768
-			return null;
1769
-		}
1770
-
1771
-		$result = [
1772
-			'syncToken' => $currentToken,
1773
-			'added'     => [],
1774
-			'modified'  => [],
1775
-			'deleted'   => [],
1776
-		];
1777
-
1778
-		if ($syncToken) {
1779
-
1780
-			$query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1781
-			if ($limit>0) {
1782
-				$query.= " LIMIT " . (int)$limit;
1783
-			}
1784
-
1785
-			// Fetching all changes
1786
-			$stmt = $this->db->prepare($query);
1787
-			$stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
1788
-
1789
-			$changes = [];
1790
-
1791
-			// This loop ensures that any duplicates are overwritten, only the
1792
-			// last change on a node is relevant.
1793
-			while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1794
-
1795
-				$changes[$row['uri']] = $row['operation'];
1796
-
1797
-			}
1798
-
1799
-			foreach($changes as $uri => $operation) {
1800
-
1801
-				switch($operation) {
1802
-					case 1 :
1803
-						$result['added'][] = $uri;
1804
-						break;
1805
-					case 2 :
1806
-						$result['modified'][] = $uri;
1807
-						break;
1808
-					case 3 :
1809
-						$result['deleted'][] = $uri;
1810
-						break;
1811
-				}
1812
-
1813
-			}
1814
-		} else {
1815
-			// No synctoken supplied, this is the initial sync.
1816
-			$query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
1817
-			$stmt = $this->db->prepare($query);
1818
-			$stmt->execute([$calendarId, $calendarType]);
1819
-
1820
-			$result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1821
-		}
1822
-		return $result;
1823
-
1824
-	}
1825
-
1826
-	/**
1827
-	 * Returns a list of subscriptions for a principal.
1828
-	 *
1829
-	 * Every subscription is an array with the following keys:
1830
-	 *  * id, a unique id that will be used by other functions to modify the
1831
-	 *    subscription. This can be the same as the uri or a database key.
1832
-	 *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1833
-	 *  * principaluri. The owner of the subscription. Almost always the same as
1834
-	 *    principalUri passed to this method.
1835
-	 *
1836
-	 * Furthermore, all the subscription info must be returned too:
1837
-	 *
1838
-	 * 1. {DAV:}displayname
1839
-	 * 2. {http://apple.com/ns/ical/}refreshrate
1840
-	 * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1841
-	 *    should not be stripped).
1842
-	 * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1843
-	 *    should not be stripped).
1844
-	 * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1845
-	 *    attachments should not be stripped).
1846
-	 * 6. {http://calendarserver.org/ns/}source (Must be a
1847
-	 *     Sabre\DAV\Property\Href).
1848
-	 * 7. {http://apple.com/ns/ical/}calendar-color
1849
-	 * 8. {http://apple.com/ns/ical/}calendar-order
1850
-	 * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1851
-	 *    (should just be an instance of
1852
-	 *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1853
-	 *    default components).
1854
-	 *
1855
-	 * @param string $principalUri
1856
-	 * @return array
1857
-	 */
1858
-	function getSubscriptionsForUser($principalUri) {
1859
-		$fields = array_values($this->subscriptionPropertyMap);
1860
-		$fields[] = 'id';
1861
-		$fields[] = 'uri';
1862
-		$fields[] = 'source';
1863
-		$fields[] = 'principaluri';
1864
-		$fields[] = 'lastmodified';
1865
-		$fields[] = 'synctoken';
1866
-
1867
-		$query = $this->db->getQueryBuilder();
1868
-		$query->select($fields)
1869
-			->from('calendarsubscriptions')
1870
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1871
-			->orderBy('calendarorder', 'asc');
1872
-		$stmt =$query->execute();
1873
-
1874
-		$subscriptions = [];
1875
-		while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1876
-
1877
-			$subscription = [
1878
-				'id'           => $row['id'],
1879
-				'uri'          => $row['uri'],
1880
-				'principaluri' => $row['principaluri'],
1881
-				'source'       => $row['source'],
1882
-				'lastmodified' => $row['lastmodified'],
1883
-
1884
-				'{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1885
-				'{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
1886
-			];
1887
-
1888
-			foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1889
-				if (!is_null($row[$dbName])) {
1890
-					$subscription[$xmlName] = $row[$dbName];
1891
-				}
1892
-			}
1893
-
1894
-			$subscriptions[] = $subscription;
1895
-
1896
-		}
1897
-
1898
-		return $subscriptions;
1899
-	}
1900
-
1901
-	/**
1902
-	 * Creates a new subscription for a principal.
1903
-	 *
1904
-	 * If the creation was a success, an id must be returned that can be used to reference
1905
-	 * this subscription in other methods, such as updateSubscription.
1906
-	 *
1907
-	 * @param string $principalUri
1908
-	 * @param string $uri
1909
-	 * @param array $properties
1910
-	 * @return mixed
1911
-	 */
1912
-	function createSubscription($principalUri, $uri, array $properties) {
1913
-
1914
-		if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1915
-			throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1916
-		}
1917
-
1918
-		$values = [
1919
-			'principaluri' => $principalUri,
1920
-			'uri'          => $uri,
1921
-			'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1922
-			'lastmodified' => time(),
1923
-		];
1924
-
1925
-		$propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1926
-
1927
-		foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1928
-			if (array_key_exists($xmlName, $properties)) {
1929
-					$values[$dbName] = $properties[$xmlName];
1930
-					if (in_array($dbName, $propertiesBoolean)) {
1931
-						$values[$dbName] = true;
1932
-				}
1933
-			}
1934
-		}
1935
-
1936
-		$valuesToInsert = array();
1937
-
1938
-		$query = $this->db->getQueryBuilder();
1939
-
1940
-		foreach (array_keys($values) as $name) {
1941
-			$valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1942
-		}
1943
-
1944
-		$query->insert('calendarsubscriptions')
1945
-			->values($valuesToInsert)
1946
-			->execute();
1947
-
1948
-		$subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1949
-
1950
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
1951
-			'\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
1952
-			[
1953
-				'subscriptionId' => $subscriptionId,
1954
-				'subscriptionData' => $this->getSubscriptionById($subscriptionId),
1955
-			]));
1956
-
1957
-		return $subscriptionId;
1958
-	}
1959
-
1960
-	/**
1961
-	 * Updates a subscription
1962
-	 *
1963
-	 * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1964
-	 * To do the actual updates, you must tell this object which properties
1965
-	 * you're going to process with the handle() method.
1966
-	 *
1967
-	 * Calling the handle method is like telling the PropPatch object "I
1968
-	 * promise I can handle updating this property".
1969
-	 *
1970
-	 * Read the PropPatch documentation for more info and examples.
1971
-	 *
1972
-	 * @param mixed $subscriptionId
1973
-	 * @param PropPatch $propPatch
1974
-	 * @return void
1975
-	 */
1976
-	function updateSubscription($subscriptionId, PropPatch $propPatch) {
1977
-		$supportedProperties = array_keys($this->subscriptionPropertyMap);
1978
-		$supportedProperties[] = '{http://calendarserver.org/ns/}source';
1979
-
1980
-		/**
1981
-		 * @suppress SqlInjectionChecker
1982
-		 */
1983
-		$propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1984
-
1985
-			$newValues = [];
1986
-
1987
-			foreach($mutations as $propertyName=>$propertyValue) {
1988
-				if ($propertyName === '{http://calendarserver.org/ns/}source') {
1989
-					$newValues['source'] = $propertyValue->getHref();
1990
-				} else {
1991
-					$fieldName = $this->subscriptionPropertyMap[$propertyName];
1992
-					$newValues[$fieldName] = $propertyValue;
1993
-				}
1994
-			}
1995
-
1996
-			$query = $this->db->getQueryBuilder();
1997
-			$query->update('calendarsubscriptions')
1998
-				->set('lastmodified', $query->createNamedParameter(time()));
1999
-			foreach($newValues as $fieldName=>$value) {
2000
-				$query->set($fieldName, $query->createNamedParameter($value));
2001
-			}
2002
-			$query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2003
-				->execute();
2004
-
2005
-			$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2006
-				'\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2007
-				[
2008
-					'subscriptionId' => $subscriptionId,
2009
-					'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2010
-					'propertyMutations' => $mutations,
2011
-				]));
2012
-
2013
-			return true;
2014
-
2015
-		});
2016
-	}
2017
-
2018
-	/**
2019
-	 * Deletes a subscription.
2020
-	 *
2021
-	 * @param mixed $subscriptionId
2022
-	 * @return void
2023
-	 */
2024
-	function deleteSubscription($subscriptionId) {
2025
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2026
-			'\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2027
-			[
2028
-				'subscriptionId' => $subscriptionId,
2029
-				'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2030
-			]));
2031
-
2032
-		$query = $this->db->getQueryBuilder();
2033
-		$query->delete('calendarsubscriptions')
2034
-			->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2035
-			->execute();
2036
-
2037
-		$query = $this->db->getQueryBuilder();
2038
-		$query->delete('calendarobjects')
2039
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2040
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2041
-			->execute();
2042
-
2043
-		$query->delete('calendarchanges')
2044
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2045
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2046
-			->execute();
2047
-
2048
-		$query->delete($this->dbObjectPropertiesTable)
2049
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2050
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2051
-			->execute();
2052
-	}
2053
-
2054
-	/**
2055
-	 * Returns a single scheduling object for the inbox collection.
2056
-	 *
2057
-	 * The returned array should contain the following elements:
2058
-	 *   * uri - A unique basename for the object. This will be used to
2059
-	 *           construct a full uri.
2060
-	 *   * calendardata - The iCalendar object
2061
-	 *   * lastmodified - The last modification date. Can be an int for a unix
2062
-	 *                    timestamp, or a PHP DateTime object.
2063
-	 *   * etag - A unique token that must change if the object changed.
2064
-	 *   * size - The size of the object, in bytes.
2065
-	 *
2066
-	 * @param string $principalUri
2067
-	 * @param string $objectUri
2068
-	 * @return array
2069
-	 */
2070
-	function getSchedulingObject($principalUri, $objectUri) {
2071
-		$query = $this->db->getQueryBuilder();
2072
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2073
-			->from('schedulingobjects')
2074
-			->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2075
-			->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2076
-			->execute();
2077
-
2078
-		$row = $stmt->fetch(\PDO::FETCH_ASSOC);
2079
-
2080
-		if(!$row) {
2081
-			return null;
2082
-		}
2083
-
2084
-		return [
2085
-				'uri'          => $row['uri'],
2086
-				'calendardata' => $row['calendardata'],
2087
-				'lastmodified' => $row['lastmodified'],
2088
-				'etag'         => '"' . $row['etag'] . '"',
2089
-				'size'         => (int)$row['size'],
2090
-		];
2091
-	}
2092
-
2093
-	/**
2094
-	 * Returns all scheduling objects for the inbox collection.
2095
-	 *
2096
-	 * These objects should be returned as an array. Every item in the array
2097
-	 * should follow the same structure as returned from getSchedulingObject.
2098
-	 *
2099
-	 * The main difference is that 'calendardata' is optional.
2100
-	 *
2101
-	 * @param string $principalUri
2102
-	 * @return array
2103
-	 */
2104
-	function getSchedulingObjects($principalUri) {
2105
-		$query = $this->db->getQueryBuilder();
2106
-		$stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2107
-				->from('schedulingobjects')
2108
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2109
-				->execute();
2110
-
2111
-		$result = [];
2112
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2113
-			$result[] = [
2114
-					'calendardata' => $row['calendardata'],
2115
-					'uri'          => $row['uri'],
2116
-					'lastmodified' => $row['lastmodified'],
2117
-					'etag'         => '"' . $row['etag'] . '"',
2118
-					'size'         => (int)$row['size'],
2119
-			];
2120
-		}
2121
-
2122
-		return $result;
2123
-	}
2124
-
2125
-	/**
2126
-	 * Deletes a scheduling object from the inbox collection.
2127
-	 *
2128
-	 * @param string $principalUri
2129
-	 * @param string $objectUri
2130
-	 * @return void
2131
-	 */
2132
-	function deleteSchedulingObject($principalUri, $objectUri) {
2133
-		$query = $this->db->getQueryBuilder();
2134
-		$query->delete('schedulingobjects')
2135
-				->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2136
-				->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2137
-				->execute();
2138
-	}
2139
-
2140
-	/**
2141
-	 * Creates a new scheduling object. This should land in a users' inbox.
2142
-	 *
2143
-	 * @param string $principalUri
2144
-	 * @param string $objectUri
2145
-	 * @param string $objectData
2146
-	 * @return void
2147
-	 */
2148
-	function createSchedulingObject($principalUri, $objectUri, $objectData) {
2149
-		$query = $this->db->getQueryBuilder();
2150
-		$query->insert('schedulingobjects')
2151
-			->values([
2152
-				'principaluri' => $query->createNamedParameter($principalUri),
2153
-				'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2154
-				'uri' => $query->createNamedParameter($objectUri),
2155
-				'lastmodified' => $query->createNamedParameter(time()),
2156
-				'etag' => $query->createNamedParameter(md5($objectData)),
2157
-				'size' => $query->createNamedParameter(strlen($objectData))
2158
-			])
2159
-			->execute();
2160
-	}
2161
-
2162
-	/**
2163
-	 * Adds a change record to the calendarchanges table.
2164
-	 *
2165
-	 * @param mixed $calendarId
2166
-	 * @param string $objectUri
2167
-	 * @param int $operation 1 = add, 2 = modify, 3 = delete.
2168
-	 * @param int $calendarType
2169
-	 * @return void
2170
-	 */
2171
-	protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2172
-		$table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2173
-
2174
-		$query = $this->db->getQueryBuilder();
2175
-		$query->select('synctoken')
2176
-			->from($table)
2177
-			->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2178
-		$syncToken = (int)$query->execute()->fetchColumn();
2179
-
2180
-		$query = $this->db->getQueryBuilder();
2181
-		$query->insert('calendarchanges')
2182
-			->values([
2183
-				'uri' => $query->createNamedParameter($objectUri),
2184
-				'synctoken' => $query->createNamedParameter($syncToken),
2185
-				'calendarid' => $query->createNamedParameter($calendarId),
2186
-				'operation' => $query->createNamedParameter($operation),
2187
-				'calendartype' => $query->createNamedParameter($calendarType),
2188
-			])
2189
-			->execute();
2190
-
2191
-		$stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2192
-		$stmt->execute([
2193
-			$calendarId
2194
-		]);
2195
-
2196
-	}
2197
-
2198
-	/**
2199
-	 * Parses some information from calendar objects, used for optimized
2200
-	 * calendar-queries.
2201
-	 *
2202
-	 * Returns an array with the following keys:
2203
-	 *   * etag - An md5 checksum of the object without the quotes.
2204
-	 *   * size - Size of the object in bytes
2205
-	 *   * componentType - VEVENT, VTODO or VJOURNAL
2206
-	 *   * firstOccurence
2207
-	 *   * lastOccurence
2208
-	 *   * uid - value of the UID property
2209
-	 *
2210
-	 * @param string $calendarData
2211
-	 * @return array
2212
-	 */
2213
-	public function getDenormalizedData($calendarData) {
2214
-
2215
-		$vObject = Reader::read($calendarData);
2216
-		$componentType = null;
2217
-		$component = null;
2218
-		$firstOccurrence = null;
2219
-		$lastOccurrence = null;
2220
-		$uid = null;
2221
-		$classification = self::CLASSIFICATION_PUBLIC;
2222
-		foreach($vObject->getComponents() as $component) {
2223
-			if ($component->name!=='VTIMEZONE') {
2224
-				$componentType = $component->name;
2225
-				$uid = (string)$component->UID;
2226
-				break;
2227
-			}
2228
-		}
2229
-		if (!$componentType) {
2230
-			throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2231
-		}
2232
-		if ($componentType === 'VEVENT' && $component->DTSTART) {
2233
-			$firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2234
-			// Finding the last occurrence is a bit harder
2235
-			if (!isset($component->RRULE)) {
2236
-				if (isset($component->DTEND)) {
2237
-					$lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2238
-				} elseif (isset($component->DURATION)) {
2239
-					$endDate = clone $component->DTSTART->getDateTime();
2240
-					$endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2241
-					$lastOccurrence = $endDate->getTimeStamp();
2242
-				} elseif (!$component->DTSTART->hasTime()) {
2243
-					$endDate = clone $component->DTSTART->getDateTime();
2244
-					$endDate->modify('+1 day');
2245
-					$lastOccurrence = $endDate->getTimeStamp();
2246
-				} else {
2247
-					$lastOccurrence = $firstOccurrence;
2248
-				}
2249
-			} else {
2250
-				$it = new EventIterator($vObject, (string)$component->UID);
2251
-				$maxDate = new \DateTime(self::MAX_DATE);
2252
-				if ($it->isInfinite()) {
2253
-					$lastOccurrence = $maxDate->getTimestamp();
2254
-				} else {
2255
-					$end = $it->getDtEnd();
2256
-					while($it->valid() && $end < $maxDate) {
2257
-						$end = $it->getDtEnd();
2258
-						$it->next();
2259
-
2260
-					}
2261
-					$lastOccurrence = $end->getTimestamp();
2262
-				}
2263
-
2264
-			}
2265
-		}
2266
-
2267
-		if ($component->CLASS) {
2268
-			$classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2269
-			switch ($component->CLASS->getValue()) {
2270
-				case 'PUBLIC':
2271
-					$classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2272
-					break;
2273
-				case 'CONFIDENTIAL':
2274
-					$classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2275
-					break;
2276
-			}
2277
-		}
2278
-		return [
2279
-			'etag' => md5($calendarData),
2280
-			'size' => strlen($calendarData),
2281
-			'componentType' => $componentType,
2282
-			'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2283
-			'lastOccurence'  => $lastOccurrence,
2284
-			'uid' => $uid,
2285
-			'classification' => $classification
2286
-		];
2287
-
2288
-	}
2289
-
2290
-	/**
2291
-	 * @param $cardData
2292
-	 * @return bool|string
2293
-	 */
2294
-	private function readBlob($cardData) {
2295
-		if (is_resource($cardData)) {
2296
-			return stream_get_contents($cardData);
2297
-		}
2298
-
2299
-		return $cardData;
2300
-	}
2301
-
2302
-	/**
2303
-	 * @param IShareable $shareable
2304
-	 * @param array $add
2305
-	 * @param array $remove
2306
-	 */
2307
-	public function updateShares($shareable, $add, $remove) {
2308
-		$calendarId = $shareable->getResourceId();
2309
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2310
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2311
-			[
2312
-				'calendarId' => $calendarId,
2313
-				'calendarData' => $this->getCalendarById($calendarId),
2314
-				'shares' => $this->getShares($calendarId),
2315
-				'add' => $add,
2316
-				'remove' => $remove,
2317
-			]));
2318
-		$this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2319
-	}
2320
-
2321
-	/**
2322
-	 * @param int $resourceId
2323
-	 * @param int $calendarType
2324
-	 * @return array
2325
-	 */
2326
-	public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2327
-		return $this->calendarSharingBackend->getShares($resourceId);
2328
-	}
2329
-
2330
-	/**
2331
-	 * @param boolean $value
2332
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2333
-	 * @return string|null
2334
-	 */
2335
-	public function setPublishStatus($value, $calendar) {
2336
-
2337
-		$calendarId = $calendar->getResourceId();
2338
-		$this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2339
-			'\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2340
-			[
2341
-				'calendarId' => $calendarId,
2342
-				'calendarData' => $this->getCalendarById($calendarId),
2343
-				'public' => $value,
2344
-			]));
2345
-
2346
-		$query = $this->db->getQueryBuilder();
2347
-		if ($value) {
2348
-			$publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2349
-			$query->insert('dav_shares')
2350
-				->values([
2351
-					'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2352
-					'type' => $query->createNamedParameter('calendar'),
2353
-					'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2354
-					'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2355
-					'publicuri' => $query->createNamedParameter($publicUri)
2356
-				]);
2357
-			$query->execute();
2358
-			return $publicUri;
2359
-		}
2360
-		$query->delete('dav_shares')
2361
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2362
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2363
-		$query->execute();
2364
-		return null;
2365
-	}
2366
-
2367
-	/**
2368
-	 * @param \OCA\DAV\CalDAV\Calendar $calendar
2369
-	 * @return mixed
2370
-	 */
2371
-	public function getPublishStatus($calendar) {
2372
-		$query = $this->db->getQueryBuilder();
2373
-		$result = $query->select('publicuri')
2374
-			->from('dav_shares')
2375
-			->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2376
-			->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2377
-			->execute();
2378
-
2379
-		$row = $result->fetch();
2380
-		$result->closeCursor();
2381
-		return $row ? reset($row) : false;
2382
-	}
2383
-
2384
-	/**
2385
-	 * @param int $resourceId
2386
-	 * @param array $acl
2387
-	 * @return array
2388
-	 */
2389
-	public function applyShareAcl($resourceId, $acl) {
2390
-		return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2391
-	}
2392
-
2393
-
2394
-
2395
-	/**
2396
-	 * update properties table
2397
-	 *
2398
-	 * @param int $calendarId
2399
-	 * @param string $objectUri
2400
-	 * @param string $calendarData
2401
-	 * @param int $calendarType
2402
-	 */
2403
-	public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2404
-		$objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2405
-
2406
-		try {
2407
-			$vCalendar = $this->readCalendarData($calendarData);
2408
-		} catch (\Exception $ex) {
2409
-			return;
2410
-		}
2411
-
2412
-		$this->purgeProperties($calendarId, $objectId);
2413
-
2414
-		$query = $this->db->getQueryBuilder();
2415
-		$query->insert($this->dbObjectPropertiesTable)
2416
-			->values(
2417
-				[
2418
-					'calendarid' => $query->createNamedParameter($calendarId),
2419
-					'calendartype' => $query->createNamedParameter($calendarType),
2420
-					'objectid' => $query->createNamedParameter($objectId),
2421
-					'name' => $query->createParameter('name'),
2422
-					'parameter' => $query->createParameter('parameter'),
2423
-					'value' => $query->createParameter('value'),
2424
-				]
2425
-			);
2426
-
2427
-		$indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2428
-		foreach ($vCalendar->getComponents() as $component) {
2429
-			if (!in_array($component->name, $indexComponents)) {
2430
-				continue;
2431
-			}
2432
-
2433
-			foreach ($component->children() as $property) {
2434
-				if (in_array($property->name, self::$indexProperties)) {
2435
-					$value = $property->getValue();
2436
-					// is this a shitty db?
2437
-					if (!$this->db->supports4ByteText()) {
2438
-						$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2439
-					}
2440
-					$value = mb_substr($value, 0, 254);
2441
-
2442
-					$query->setParameter('name', $property->name);
2443
-					$query->setParameter('parameter', null);
2444
-					$query->setParameter('value', $value);
2445
-					$query->execute();
2446
-				}
2447
-
2448
-				if (array_key_exists($property->name, self::$indexParameters)) {
2449
-					$parameters = $property->parameters();
2450
-					$indexedParametersForProperty = self::$indexParameters[$property->name];
2451
-
2452
-					foreach ($parameters as $key => $value) {
2453
-						if (in_array($key, $indexedParametersForProperty)) {
2454
-							// is this a shitty db?
2455
-							if ($this->db->supports4ByteText()) {
2456
-								$value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2457
-							}
2458
-							$value = mb_substr($value, 0, 254);
2459
-
2460
-							$query->setParameter('name', $property->name);
2461
-							$query->setParameter('parameter', substr($key, 0, 254));
2462
-							$query->setParameter('value', substr($value, 0, 254));
2463
-							$query->execute();
2464
-						}
2465
-					}
2466
-				}
2467
-			}
2468
-		}
2469
-	}
2470
-
2471
-	/**
2472
-	 * deletes all birthday calendars
2473
-	 */
2474
-	public function deleteAllBirthdayCalendars() {
2475
-		$query = $this->db->getQueryBuilder();
2476
-		$result = $query->select(['id'])->from('calendars')
2477
-			->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2478
-			->execute();
2479
-
2480
-		$ids = $result->fetchAll();
2481
-		foreach($ids as $id) {
2482
-			$this->deleteCalendar($id['id']);
2483
-		}
2484
-	}
2485
-
2486
-	/**
2487
-	 * @param $subscriptionId
2488
-	 */
2489
-	public function purgeAllCachedEventsForSubscription($subscriptionId) {
2490
-		$query = $this->db->getQueryBuilder();
2491
-		$query->select('uri')
2492
-			->from('calendarobjects')
2493
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2494
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2495
-		$stmt = $query->execute();
2496
-
2497
-		$uris = [];
2498
-		foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2499
-			$uris[] = $row['uri'];
2500
-		}
2501
-		$stmt->closeCursor();
2502
-
2503
-		$query = $this->db->getQueryBuilder();
2504
-		$query->delete('calendarobjects')
2505
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2506
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2507
-			->execute();
2508
-
2509
-		$query->delete('calendarchanges')
2510
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2511
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2512
-			->execute();
2513
-
2514
-		$query->delete($this->dbObjectPropertiesTable)
2515
-			->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2516
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2517
-			->execute();
2518
-
2519
-		foreach($uris as $uri) {
2520
-			$this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2521
-		}
2522
-	}
2523
-
2524
-	/**
2525
-	 * read VCalendar data into a VCalendar object
2526
-	 *
2527
-	 * @param string $objectData
2528
-	 * @return VCalendar
2529
-	 */
2530
-	protected function readCalendarData($objectData) {
2531
-		return Reader::read($objectData);
2532
-	}
2533
-
2534
-	/**
2535
-	 * delete all properties from a given calendar object
2536
-	 *
2537
-	 * @param int $calendarId
2538
-	 * @param int $objectId
2539
-	 */
2540
-	protected function purgeProperties($calendarId, $objectId) {
2541
-		$query = $this->db->getQueryBuilder();
2542
-		$query->delete($this->dbObjectPropertiesTable)
2543
-			->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2544
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2545
-		$query->execute();
2546
-	}
2547
-
2548
-	/**
2549
-	 * get ID from a given calendar object
2550
-	 *
2551
-	 * @param int $calendarId
2552
-	 * @param string $uri
2553
-	 * @param int $calendarType
2554
-	 * @return int
2555
-	 */
2556
-	protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2557
-		$query = $this->db->getQueryBuilder();
2558
-		$query->select('id')
2559
-			->from('calendarobjects')
2560
-			->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2561
-			->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2562
-			->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2563
-
2564
-		$result = $query->execute();
2565
-		$objectIds = $result->fetch();
2566
-		$result->closeCursor();
2567
-
2568
-		if (!isset($objectIds['id'])) {
2569
-			throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2570
-		}
2571
-
2572
-		return (int)$objectIds['id'];
2573
-	}
2574
-
2575
-	/**
2576
-	 * return legacy endpoint principal name to new principal name
2577
-	 *
2578
-	 * @param $principalUri
2579
-	 * @param $toV2
2580
-	 * @return string
2581
-	 */
2582
-	private function convertPrincipal($principalUri, $toV2) {
2583
-		if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2584
-			list(, $name) = Uri\split($principalUri);
2585
-			if ($toV2 === true) {
2586
-				return "principals/users/$name";
2587
-			}
2588
-			return "principals/$name";
2589
-		}
2590
-		return $principalUri;
2591
-	}
2592
-
2593
-	/**
2594
-	 * adds information about an owner to the calendar data
2595
-	 *
2596
-	 * @param $calendarInfo
2597
-	 */
2598
-	private function addOwnerPrincipal(&$calendarInfo) {
2599
-		$ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2600
-		$displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2601
-		if (isset($calendarInfo[$ownerPrincipalKey])) {
2602
-			$uri = $calendarInfo[$ownerPrincipalKey];
2603
-		} else {
2604
-			$uri = $calendarInfo['principaluri'];
2605
-		}
2606
-
2607
-		$principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2608
-		if (isset($principalInformation['{DAV:}displayname'])) {
2609
-			$calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2610
-		}
2611
-	}
445
+    /**
446
+     * @return array
447
+     */
448
+    public function getPublicCalendars() {
449
+        $fields = array_values($this->propertyMap);
450
+        $fields[] = 'a.id';
451
+        $fields[] = 'a.uri';
452
+        $fields[] = 'a.synctoken';
453
+        $fields[] = 'a.components';
454
+        $fields[] = 'a.principaluri';
455
+        $fields[] = 'a.transparent';
456
+        $fields[] = 's.access';
457
+        $fields[] = 's.publicuri';
458
+        $calendars = [];
459
+        $query = $this->db->getQueryBuilder();
460
+        $result = $query->select($fields)
461
+            ->from('dav_shares', 's')
462
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
463
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
464
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
465
+            ->execute();
466
+
467
+        while($row = $result->fetch()) {
468
+            list(, $name) = Uri\split($row['principaluri']);
469
+            $row['displayname'] = $row['displayname'] . "($name)";
470
+            $components = [];
471
+            if ($row['components']) {
472
+                $components = explode(',',$row['components']);
473
+            }
474
+            $calendar = [
475
+                'id' => $row['id'],
476
+                'uri' => $row['publicuri'],
477
+                'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
478
+                '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
479
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
480
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
481
+                '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
482
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], $this->legacyEndpoint),
483
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
484
+                '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
485
+            ];
486
+
487
+            foreach($this->propertyMap as $xmlName=>$dbName) {
488
+                $calendar[$xmlName] = $row[$dbName];
489
+            }
490
+
491
+            $this->addOwnerPrincipal($calendar);
492
+
493
+            if (!isset($calendars[$calendar['id']])) {
494
+                $calendars[$calendar['id']] = $calendar;
495
+            }
496
+        }
497
+        $result->closeCursor();
498
+
499
+        return array_values($calendars);
500
+    }
501
+
502
+    /**
503
+     * @param string $uri
504
+     * @return array
505
+     * @throws NotFound
506
+     */
507
+    public function getPublicCalendar($uri) {
508
+        $fields = array_values($this->propertyMap);
509
+        $fields[] = 'a.id';
510
+        $fields[] = 'a.uri';
511
+        $fields[] = 'a.synctoken';
512
+        $fields[] = 'a.components';
513
+        $fields[] = 'a.principaluri';
514
+        $fields[] = 'a.transparent';
515
+        $fields[] = 's.access';
516
+        $fields[] = 's.publicuri';
517
+        $query = $this->db->getQueryBuilder();
518
+        $result = $query->select($fields)
519
+            ->from('dav_shares', 's')
520
+            ->join('s', 'calendars', 'a', $query->expr()->eq('s.resourceid', 'a.id'))
521
+            ->where($query->expr()->in('s.access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
522
+            ->andWhere($query->expr()->eq('s.type', $query->createNamedParameter('calendar')))
523
+            ->andWhere($query->expr()->eq('s.publicuri', $query->createNamedParameter($uri)))
524
+            ->execute();
525
+
526
+        $row = $result->fetch(\PDO::FETCH_ASSOC);
527
+
528
+        $result->closeCursor();
529
+
530
+        if ($row === false) {
531
+            throw new NotFound('Node with name \'' . $uri . '\' could not be found');
532
+        }
533
+
534
+        list(, $name) = Uri\split($row['principaluri']);
535
+        $row['displayname'] = $row['displayname'] . ' ' . "($name)";
536
+        $components = [];
537
+        if ($row['components']) {
538
+            $components = explode(',',$row['components']);
539
+        }
540
+        $calendar = [
541
+            'id' => $row['id'],
542
+            'uri' => $row['publicuri'],
543
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
544
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
545
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
546
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
547
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
548
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
549
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => (int)$row['access'] === Backend::ACCESS_READ,
550
+            '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}public' => (int)$row['access'] === self::ACCESS_PUBLIC,
551
+        ];
552
+
553
+        foreach($this->propertyMap as $xmlName=>$dbName) {
554
+            $calendar[$xmlName] = $row[$dbName];
555
+        }
556
+
557
+        $this->addOwnerPrincipal($calendar);
558
+
559
+        return $calendar;
560
+
561
+    }
562
+
563
+    /**
564
+     * @param string $principal
565
+     * @param string $uri
566
+     * @return array|null
567
+     */
568
+    public function getCalendarByUri($principal, $uri) {
569
+        $fields = array_values($this->propertyMap);
570
+        $fields[] = 'id';
571
+        $fields[] = 'uri';
572
+        $fields[] = 'synctoken';
573
+        $fields[] = 'components';
574
+        $fields[] = 'principaluri';
575
+        $fields[] = 'transparent';
576
+
577
+        // Making fields a comma-delimited list
578
+        $query = $this->db->getQueryBuilder();
579
+        $query->select($fields)->from('calendars')
580
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
581
+            ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal)))
582
+            ->setMaxResults(1);
583
+        $stmt = $query->execute();
584
+
585
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
586
+        $stmt->closeCursor();
587
+        if ($row === false) {
588
+            return null;
589
+        }
590
+
591
+        $components = [];
592
+        if ($row['components']) {
593
+            $components = explode(',',$row['components']);
594
+        }
595
+
596
+        $calendar = [
597
+            'id' => $row['id'],
598
+            'uri' => $row['uri'],
599
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
600
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
601
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
602
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
603
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
604
+        ];
605
+
606
+        foreach($this->propertyMap as $xmlName=>$dbName) {
607
+            $calendar[$xmlName] = $row[$dbName];
608
+        }
609
+
610
+        $this->addOwnerPrincipal($calendar);
611
+
612
+        return $calendar;
613
+    }
614
+
615
+    /**
616
+     * @param $calendarId
617
+     * @return array|null
618
+     */
619
+    public function getCalendarById($calendarId) {
620
+        $fields = array_values($this->propertyMap);
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('id', $query->createNamedParameter($calendarId)))
632
+            ->setMaxResults(1);
633
+        $stmt = $query->execute();
634
+
635
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
636
+        $stmt->closeCursor();
637
+        if ($row === false) {
638
+            return null;
639
+        }
640
+
641
+        $components = [];
642
+        if ($row['components']) {
643
+            $components = explode(',',$row['components']);
644
+        }
645
+
646
+        $calendar = [
647
+            'id' => $row['id'],
648
+            'uri' => $row['uri'],
649
+            'principaluri' => $this->convertPrincipal($row['principaluri'], !$this->legacyEndpoint),
650
+            '{' . Plugin::NS_CALENDARSERVER . '}getctag' => 'http://sabre.io/ns/sync/' . ($row['synctoken']?$row['synctoken']:'0'),
651
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
652
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet($components),
653
+            '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' => new ScheduleCalendarTransp($row['transparent']?'transparent':'opaque'),
654
+        ];
655
+
656
+        foreach($this->propertyMap as $xmlName=>$dbName) {
657
+            $calendar[$xmlName] = $row[$dbName];
658
+        }
659
+
660
+        $this->addOwnerPrincipal($calendar);
661
+
662
+        return $calendar;
663
+    }
664
+
665
+    /**
666
+     * @param $subscriptionId
667
+     */
668
+    public function getSubscriptionById($subscriptionId) {
669
+        $fields = array_values($this->subscriptionPropertyMap);
670
+        $fields[] = 'id';
671
+        $fields[] = 'uri';
672
+        $fields[] = 'source';
673
+        $fields[] = 'synctoken';
674
+        $fields[] = 'principaluri';
675
+        $fields[] = 'lastmodified';
676
+
677
+        $query = $this->db->getQueryBuilder();
678
+        $query->select($fields)
679
+            ->from('calendarsubscriptions')
680
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
681
+            ->orderBy('calendarorder', 'asc');
682
+        $stmt =$query->execute();
683
+
684
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
685
+        $stmt->closeCursor();
686
+        if ($row === false) {
687
+            return null;
688
+        }
689
+
690
+        $subscription = [
691
+            'id'           => $row['id'],
692
+            'uri'          => $row['uri'],
693
+            'principaluri' => $row['principaluri'],
694
+            'source'       => $row['source'],
695
+            'lastmodified' => $row['lastmodified'],
696
+            '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
697
+            '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
698
+        ];
699
+
700
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
701
+            if (!is_null($row[$dbName])) {
702
+                $subscription[$xmlName] = $row[$dbName];
703
+            }
704
+        }
705
+
706
+        return $subscription;
707
+    }
708
+
709
+    /**
710
+     * Creates a new calendar for a principal.
711
+     *
712
+     * If the creation was a success, an id must be returned that can be used to reference
713
+     * this calendar in other methods, such as updateCalendar.
714
+     *
715
+     * @param string $principalUri
716
+     * @param string $calendarUri
717
+     * @param array $properties
718
+     * @return int
719
+     * @suppress SqlInjectionChecker
720
+     */
721
+    function createCalendar($principalUri, $calendarUri, array $properties) {
722
+        $values = [
723
+            'principaluri' => $this->convertPrincipal($principalUri, true),
724
+            'uri'          => $calendarUri,
725
+            'synctoken'    => 1,
726
+            'transparent'  => 0,
727
+            'components'   => 'VEVENT,VTODO',
728
+            'displayname'  => $calendarUri
729
+        ];
730
+
731
+        // Default value
732
+        $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set';
733
+        if (isset($properties[$sccs])) {
734
+            if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) {
735
+                throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet');
736
+            }
737
+            $values['components'] = implode(',',$properties[$sccs]->getValue());
738
+        }
739
+        $transp = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
740
+        if (isset($properties[$transp])) {
741
+            $values['transparent'] = (int) ($properties[$transp]->getValue() === 'transparent');
742
+        }
743
+
744
+        foreach($this->propertyMap as $xmlName=>$dbName) {
745
+            if (isset($properties[$xmlName])) {
746
+                $values[$dbName] = $properties[$xmlName];
747
+            }
748
+        }
749
+
750
+        $query = $this->db->getQueryBuilder();
751
+        $query->insert('calendars');
752
+        foreach($values as $column => $value) {
753
+            $query->setValue($column, $query->createNamedParameter($value));
754
+        }
755
+        $query->execute();
756
+        $calendarId = $query->getLastInsertId();
757
+
758
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendar', new GenericEvent(
759
+            '\OCA\DAV\CalDAV\CalDavBackend::createCalendar',
760
+            [
761
+                'calendarId' => $calendarId,
762
+                'calendarData' => $this->getCalendarById($calendarId),
763
+        ]));
764
+
765
+        return $calendarId;
766
+    }
767
+
768
+    /**
769
+     * Updates properties for a calendar.
770
+     *
771
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
772
+     * To do the actual updates, you must tell this object which properties
773
+     * you're going to process with the handle() method.
774
+     *
775
+     * Calling the handle method is like telling the PropPatch object "I
776
+     * promise I can handle updating this property".
777
+     *
778
+     * Read the PropPatch documentation for more info and examples.
779
+     *
780
+     * @param mixed $calendarId
781
+     * @param PropPatch $propPatch
782
+     * @return void
783
+     */
784
+    function updateCalendar($calendarId, PropPatch $propPatch) {
785
+        $supportedProperties = array_keys($this->propertyMap);
786
+        $supportedProperties[] = '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp';
787
+
788
+        /**
789
+         * @suppress SqlInjectionChecker
790
+         */
791
+        $propPatch->handle($supportedProperties, function($mutations) use ($calendarId) {
792
+            $newValues = [];
793
+            foreach ($mutations as $propertyName => $propertyValue) {
794
+
795
+                switch ($propertyName) {
796
+                    case '{' . Plugin::NS_CALDAV . '}schedule-calendar-transp' :
797
+                        $fieldName = 'transparent';
798
+                        $newValues[$fieldName] = (int) ($propertyValue->getValue() === 'transparent');
799
+                        break;
800
+                    default :
801
+                        $fieldName = $this->propertyMap[$propertyName];
802
+                        $newValues[$fieldName] = $propertyValue;
803
+                        break;
804
+                }
805
+
806
+            }
807
+            $query = $this->db->getQueryBuilder();
808
+            $query->update('calendars');
809
+            foreach ($newValues as $fieldName => $value) {
810
+                $query->set($fieldName, $query->createNamedParameter($value));
811
+            }
812
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
813
+            $query->execute();
814
+
815
+            $this->addChange($calendarId, "", 2);
816
+
817
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendar', new GenericEvent(
818
+                '\OCA\DAV\CalDAV\CalDavBackend::updateCalendar',
819
+                [
820
+                    'calendarId' => $calendarId,
821
+                    'calendarData' => $this->getCalendarById($calendarId),
822
+                    'shares' => $this->getShares($calendarId),
823
+                    'propertyMutations' => $mutations,
824
+            ]));
825
+
826
+            return true;
827
+        });
828
+    }
829
+
830
+    /**
831
+     * Delete a calendar and all it's objects
832
+     *
833
+     * @param mixed $calendarId
834
+     * @return void
835
+     */
836
+    function deleteCalendar($calendarId) {
837
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar', new GenericEvent(
838
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendar',
839
+            [
840
+                'calendarId' => $calendarId,
841
+                'calendarData' => $this->getCalendarById($calendarId),
842
+                'shares' => $this->getShares($calendarId),
843
+        ]));
844
+
845
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?');
846
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
847
+
848
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendars` WHERE `id` = ?');
849
+        $stmt->execute([$calendarId]);
850
+
851
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarchanges` WHERE `calendarid` = ? AND `calendartype` = ?');
852
+        $stmt->execute([$calendarId, self::CALENDAR_TYPE_CALENDAR]);
853
+
854
+        $this->calendarSharingBackend->deleteAllShares($calendarId);
855
+
856
+        $query = $this->db->getQueryBuilder();
857
+        $query->delete($this->dbObjectPropertiesTable)
858
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
859
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)))
860
+            ->execute();
861
+    }
862
+
863
+    /**
864
+     * Delete all of an user's shares
865
+     *
866
+     * @param string $principaluri
867
+     * @return void
868
+     */
869
+    function deleteAllSharesByUser($principaluri) {
870
+        $this->calendarSharingBackend->deleteAllSharesByUser($principaluri);
871
+    }
872
+
873
+    /**
874
+     * Returns all calendar objects within a calendar.
875
+     *
876
+     * Every item contains an array with the following keys:
877
+     *   * calendardata - The iCalendar-compatible calendar data
878
+     *   * uri - a unique key which will be used to construct the uri. This can
879
+     *     be any arbitrary string, but making sure it ends with '.ics' is a
880
+     *     good idea. This is only the basename, or filename, not the full
881
+     *     path.
882
+     *   * lastmodified - a timestamp of the last modification time
883
+     *   * etag - An arbitrary string, surrounded by double-quotes. (e.g.:
884
+     *   '"abcdef"')
885
+     *   * size - The size of the calendar objects, in bytes.
886
+     *   * component - optional, a string containing the type of object, such
887
+     *     as 'vevent' or 'vtodo'. If specified, this will be used to populate
888
+     *     the Content-Type header.
889
+     *
890
+     * Note that the etag is optional, but it's highly encouraged to return for
891
+     * speed reasons.
892
+     *
893
+     * The calendardata is also optional. If it's not returned
894
+     * 'getCalendarObject' will be called later, which *is* expected to return
895
+     * calendardata.
896
+     *
897
+     * If neither etag or size are specified, the calendardata will be
898
+     * used/fetched to determine these numbers. If both are specified the
899
+     * amount of times this is needed is reduced by a great degree.
900
+     *
901
+     * @param mixed $id
902
+     * @param int $calendarType
903
+     * @return array
904
+     */
905
+    public function getCalendarObjects($id, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
906
+        $query = $this->db->getQueryBuilder();
907
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'componenttype', 'classification'])
908
+            ->from('calendarobjects')
909
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
910
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
911
+        $stmt = $query->execute();
912
+
913
+        $result = [];
914
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
915
+            $result[] = [
916
+                'id'           => $row['id'],
917
+                'uri'          => $row['uri'],
918
+                'lastmodified' => $row['lastmodified'],
919
+                'etag'         => '"' . $row['etag'] . '"',
920
+                'calendarid'   => $row['calendarid'],
921
+                'size'         => (int)$row['size'],
922
+                'component'    => strtolower($row['componenttype']),
923
+                'classification'=> (int)$row['classification']
924
+            ];
925
+        }
926
+
927
+        return $result;
928
+    }
929
+
930
+    /**
931
+     * Returns information from a single calendar object, based on it's object
932
+     * uri.
933
+     *
934
+     * The object uri is only the basename, or filename and not a full path.
935
+     *
936
+     * The returned array must have the same keys as getCalendarObjects. The
937
+     * 'calendardata' object is required here though, while it's not required
938
+     * for getCalendarObjects.
939
+     *
940
+     * This method must return null if the object did not exist.
941
+     *
942
+     * @param mixed $id
943
+     * @param string $objectUri
944
+     * @param int $calendarType
945
+     * @return array|null
946
+     */
947
+    public function getCalendarObject($id, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
948
+        $query = $this->db->getQueryBuilder();
949
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
950
+            ->from('calendarobjects')
951
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
952
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
953
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
954
+        $stmt = $query->execute();
955
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
956
+
957
+        if(!$row) {
958
+            return null;
959
+        }
960
+
961
+        return [
962
+            'id'            => $row['id'],
963
+            'uri'           => $row['uri'],
964
+            'lastmodified'  => $row['lastmodified'],
965
+            'etag'          => '"' . $row['etag'] . '"',
966
+            'calendarid'    => $row['calendarid'],
967
+            'size'          => (int)$row['size'],
968
+            'calendardata'  => $this->readBlob($row['calendardata']),
969
+            'component'     => strtolower($row['componenttype']),
970
+            'classification'=> (int)$row['classification']
971
+        ];
972
+    }
973
+
974
+    /**
975
+     * Returns a list of calendar objects.
976
+     *
977
+     * This method should work identical to getCalendarObject, but instead
978
+     * return all the calendar objects in the list as an array.
979
+     *
980
+     * If the backend supports this, it may allow for some speed-ups.
981
+     *
982
+     * @param mixed $calendarId
983
+     * @param string[] $uris
984
+     * @param int $calendarType
985
+     * @return array
986
+     */
987
+    public function getMultipleCalendarObjects($id, array $uris, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
988
+        if (empty($uris)) {
989
+            return [];
990
+        }
991
+
992
+        $chunks = array_chunk($uris, 100);
993
+        $objects = [];
994
+
995
+        $query = $this->db->getQueryBuilder();
996
+        $query->select(['id', 'uri', 'lastmodified', 'etag', 'calendarid', 'size', 'calendardata', 'componenttype', 'classification'])
997
+            ->from('calendarobjects')
998
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
999
+            ->andWhere($query->expr()->in('uri', $query->createParameter('uri')))
1000
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1001
+
1002
+        foreach ($chunks as $uris) {
1003
+            $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY);
1004
+            $result = $query->execute();
1005
+
1006
+            while ($row = $result->fetch()) {
1007
+                $objects[] = [
1008
+                    'id'           => $row['id'],
1009
+                    'uri'          => $row['uri'],
1010
+                    'lastmodified' => $row['lastmodified'],
1011
+                    'etag'         => '"' . $row['etag'] . '"',
1012
+                    'calendarid'   => $row['calendarid'],
1013
+                    'size'         => (int)$row['size'],
1014
+                    'calendardata' => $this->readBlob($row['calendardata']),
1015
+                    'component'    => strtolower($row['componenttype']),
1016
+                    'classification' => (int)$row['classification']
1017
+                ];
1018
+            }
1019
+            $result->closeCursor();
1020
+        }
1021
+
1022
+        return $objects;
1023
+    }
1024
+
1025
+    /**
1026
+     * Creates a new calendar object.
1027
+     *
1028
+     * The object uri is only the basename, or filename and not a full path.
1029
+     *
1030
+     * It is possible return an etag from this function, which will be used in
1031
+     * the response to this PUT request. Note that the ETag must be surrounded
1032
+     * by double-quotes.
1033
+     *
1034
+     * However, you should only really return this ETag if you don't mangle the
1035
+     * calendar-data. If the result of a subsequent GET to this object is not
1036
+     * the exact same as this request body, you should omit the ETag.
1037
+     *
1038
+     * @param mixed $calendarId
1039
+     * @param string $objectUri
1040
+     * @param string $calendarData
1041
+     * @param int $calendarType
1042
+     * @return string
1043
+     */
1044
+    function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1045
+        $extraData = $this->getDenormalizedData($calendarData);
1046
+
1047
+        $q = $this->db->getQueryBuilder();
1048
+        $q->select($q->func()->count('*'))
1049
+            ->from('calendarobjects')
1050
+            ->where($q->expr()->eq('calendarid', $q->createNamedParameter($calendarId)))
1051
+            ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($extraData['uid'])))
1052
+            ->andWhere($q->expr()->eq('calendartype', $q->createNamedParameter($calendarType)));
1053
+
1054
+        $result = $q->execute();
1055
+        $count = (int) $result->fetchColumn();
1056
+        $result->closeCursor();
1057
+
1058
+        if ($count !== 0) {
1059
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar object with uid already exists in this calendar collection.');
1060
+        }
1061
+
1062
+        $query = $this->db->getQueryBuilder();
1063
+        $query->insert('calendarobjects')
1064
+            ->values([
1065
+                'calendarid' => $query->createNamedParameter($calendarId),
1066
+                'uri' => $query->createNamedParameter($objectUri),
1067
+                'calendardata' => $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB),
1068
+                'lastmodified' => $query->createNamedParameter(time()),
1069
+                'etag' => $query->createNamedParameter($extraData['etag']),
1070
+                'size' => $query->createNamedParameter($extraData['size']),
1071
+                'componenttype' => $query->createNamedParameter($extraData['componentType']),
1072
+                'firstoccurence' => $query->createNamedParameter($extraData['firstOccurence']),
1073
+                'lastoccurence' => $query->createNamedParameter($extraData['lastOccurence']),
1074
+                'classification' => $query->createNamedParameter($extraData['classification']),
1075
+                'uid' => $query->createNamedParameter($extraData['uid']),
1076
+                'calendartype' => $query->createNamedParameter($calendarType),
1077
+            ])
1078
+            ->execute();
1079
+
1080
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1081
+
1082
+        if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1083
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject', new GenericEvent(
1084
+                '\OCA\DAV\CalDAV\CalDavBackend::createCalendarObject',
1085
+                [
1086
+                    'calendarId' => $calendarId,
1087
+                    'calendarData' => $this->getCalendarById($calendarId),
1088
+                    'shares' => $this->getShares($calendarId),
1089
+                    'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1090
+                ]
1091
+            ));
1092
+        } else {
1093
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent(
1094
+                '\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject',
1095
+                [
1096
+                    'subscriptionId' => $calendarId,
1097
+                    'calendarData' => $this->getCalendarById($calendarId),
1098
+                    'shares' => $this->getShares($calendarId),
1099
+                    'objectData' => $this->getCalendarObject($calendarId, $objectUri),
1100
+                ]
1101
+            ));
1102
+        }
1103
+        $this->addChange($calendarId, $objectUri, 1, $calendarType);
1104
+
1105
+        return '"' . $extraData['etag'] . '"';
1106
+    }
1107
+
1108
+    /**
1109
+     * Updates an existing calendarobject, based on it's uri.
1110
+     *
1111
+     * The object uri is only the basename, or filename and not a full path.
1112
+     *
1113
+     * It is possible return an etag from this function, which will be used in
1114
+     * the response to this PUT request. Note that the ETag must be surrounded
1115
+     * by double-quotes.
1116
+     *
1117
+     * However, you should only really return this ETag if you don't mangle the
1118
+     * calendar-data. If the result of a subsequent GET to this object is not
1119
+     * the exact same as this request body, you should omit the ETag.
1120
+     *
1121
+     * @param mixed $calendarId
1122
+     * @param string $objectUri
1123
+     * @param string $calendarData
1124
+     * @param int $calendarType
1125
+     * @return string
1126
+     */
1127
+    function updateCalendarObject($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1128
+        $extraData = $this->getDenormalizedData($calendarData);
1129
+
1130
+        $query = $this->db->getQueryBuilder();
1131
+        $query->update('calendarobjects')
1132
+                ->set('calendardata', $query->createNamedParameter($calendarData, IQueryBuilder::PARAM_LOB))
1133
+                ->set('lastmodified', $query->createNamedParameter(time()))
1134
+                ->set('etag', $query->createNamedParameter($extraData['etag']))
1135
+                ->set('size', $query->createNamedParameter($extraData['size']))
1136
+                ->set('componenttype', $query->createNamedParameter($extraData['componentType']))
1137
+                ->set('firstoccurence', $query->createNamedParameter($extraData['firstOccurence']))
1138
+                ->set('lastoccurence', $query->createNamedParameter($extraData['lastOccurence']))
1139
+                ->set('classification', $query->createNamedParameter($extraData['classification']))
1140
+                ->set('uid', $query->createNamedParameter($extraData['uid']))
1141
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
1142
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
1143
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)))
1144
+            ->execute();
1145
+
1146
+        $this->updateProperties($calendarId, $objectUri, $calendarData, $calendarType);
1147
+
1148
+        $data = $this->getCalendarObject($calendarId, $objectUri);
1149
+        if (is_array($data)) {
1150
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1151
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject', new GenericEvent(
1152
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCalendarObject',
1153
+                    [
1154
+                        'calendarId' => $calendarId,
1155
+                        'calendarData' => $this->getCalendarById($calendarId),
1156
+                        'shares' => $this->getShares($calendarId),
1157
+                        'objectData' => $data,
1158
+                    ]
1159
+                ));
1160
+            } else {
1161
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent(
1162
+                    '\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject',
1163
+                    [
1164
+                        'subscriptionId' => $calendarId,
1165
+                        'calendarData' => $this->getCalendarById($calendarId),
1166
+                        'shares' => $this->getShares($calendarId),
1167
+                        'objectData' => $data,
1168
+                    ]
1169
+                ));
1170
+            }
1171
+        }
1172
+        $this->addChange($calendarId, $objectUri, 2, $calendarType);
1173
+
1174
+        return '"' . $extraData['etag'] . '"';
1175
+    }
1176
+
1177
+    /**
1178
+     * @param int $calendarObjectId
1179
+     * @param int $classification
1180
+     */
1181
+    public function setClassification($calendarObjectId, $classification) {
1182
+        if (!in_array($classification, [
1183
+            self::CLASSIFICATION_PUBLIC, self::CLASSIFICATION_PRIVATE, self::CLASSIFICATION_CONFIDENTIAL
1184
+        ])) {
1185
+            throw new \InvalidArgumentException();
1186
+        }
1187
+        $query = $this->db->getQueryBuilder();
1188
+        $query->update('calendarobjects')
1189
+            ->set('classification', $query->createNamedParameter($classification))
1190
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarObjectId)))
1191
+            ->execute();
1192
+    }
1193
+
1194
+    /**
1195
+     * Deletes an existing calendar object.
1196
+     *
1197
+     * The object uri is only the basename, or filename and not a full path.
1198
+     *
1199
+     * @param mixed $calendarId
1200
+     * @param string $objectUri
1201
+     * @param int $calendarType
1202
+     * @return void
1203
+     */
1204
+    function deleteCalendarObject($calendarId, $objectUri, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1205
+        $data = $this->getCalendarObject($calendarId, $objectUri, $calendarType);
1206
+        if (is_array($data)) {
1207
+            if ($calendarType === self::CALENDAR_TYPE_CALENDAR) {
1208
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject', new GenericEvent(
1209
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCalendarObject',
1210
+                    [
1211
+                        'calendarId' => $calendarId,
1212
+                        'calendarData' => $this->getCalendarById($calendarId),
1213
+                        'shares' => $this->getShares($calendarId),
1214
+                        'objectData' => $data,
1215
+                    ]
1216
+                ));
1217
+            } else {
1218
+                $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent(
1219
+                    '\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject',
1220
+                    [
1221
+                        'subscriptionId' => $calendarId,
1222
+                        'calendarData' => $this->getCalendarById($calendarId),
1223
+                        'shares' => $this->getShares($calendarId),
1224
+                        'objectData' => $data,
1225
+                    ]
1226
+                ));
1227
+            }
1228
+        }
1229
+
1230
+        $stmt = $this->db->prepare('DELETE FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `uri` = ? AND `calendartype` = ?');
1231
+        $stmt->execute([$calendarId, $objectUri, $calendarType]);
1232
+
1233
+        $this->purgeProperties($calendarId, $data['id'], $calendarType);
1234
+
1235
+        $this->addChange($calendarId, $objectUri, 3, $calendarType);
1236
+    }
1237
+
1238
+    /**
1239
+     * Performs a calendar-query on the contents of this calendar.
1240
+     *
1241
+     * The calendar-query is defined in RFC4791 : CalDAV. Using the
1242
+     * calendar-query it is possible for a client to request a specific set of
1243
+     * object, based on contents of iCalendar properties, date-ranges and
1244
+     * iCalendar component types (VTODO, VEVENT).
1245
+     *
1246
+     * This method should just return a list of (relative) urls that match this
1247
+     * query.
1248
+     *
1249
+     * The list of filters are specified as an array. The exact array is
1250
+     * documented by Sabre\CalDAV\CalendarQueryParser.
1251
+     *
1252
+     * Note that it is extremely likely that getCalendarObject for every path
1253
+     * returned from this method will be called almost immediately after. You
1254
+     * may want to anticipate this to speed up these requests.
1255
+     *
1256
+     * This method provides a default implementation, which parses *all* the
1257
+     * iCalendar objects in the specified calendar.
1258
+     *
1259
+     * This default may well be good enough for personal use, and calendars
1260
+     * that aren't very large. But if you anticipate high usage, big calendars
1261
+     * or high loads, you are strongly advised to optimize certain paths.
1262
+     *
1263
+     * The best way to do so is override this method and to optimize
1264
+     * specifically for 'common filters'.
1265
+     *
1266
+     * Requests that are extremely common are:
1267
+     *   * requests for just VEVENTS
1268
+     *   * requests for just VTODO
1269
+     *   * requests with a time-range-filter on either VEVENT or VTODO.
1270
+     *
1271
+     * ..and combinations of these requests. It may not be worth it to try to
1272
+     * handle every possible situation and just rely on the (relatively
1273
+     * easy to use) CalendarQueryValidator to handle the rest.
1274
+     *
1275
+     * Note that especially time-range-filters may be difficult to parse. A
1276
+     * time-range filter specified on a VEVENT must for instance also handle
1277
+     * recurrence rules correctly.
1278
+     * A good example of how to interprete all these filters can also simply
1279
+     * be found in Sabre\CalDAV\CalendarQueryFilter. This class is as correct
1280
+     * as possible, so it gives you a good idea on what type of stuff you need
1281
+     * to think of.
1282
+     *
1283
+     * @param mixed $id
1284
+     * @param array $filters
1285
+     * @param int $calendarType
1286
+     * @return array
1287
+     */
1288
+    public function calendarQuery($id, array $filters, $calendarType=self::CALENDAR_TYPE_CALENDAR):array {
1289
+        $componentType = null;
1290
+        $requirePostFilter = true;
1291
+        $timeRange = null;
1292
+
1293
+        // if no filters were specified, we don't need to filter after a query
1294
+        if (!$filters['prop-filters'] && !$filters['comp-filters']) {
1295
+            $requirePostFilter = false;
1296
+        }
1297
+
1298
+        // Figuring out if there's a component filter
1299
+        if (count($filters['comp-filters']) > 0 && !$filters['comp-filters'][0]['is-not-defined']) {
1300
+            $componentType = $filters['comp-filters'][0]['name'];
1301
+
1302
+            // Checking if we need post-filters
1303
+            if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['time-range'] && !$filters['comp-filters'][0]['prop-filters']) {
1304
+                $requirePostFilter = false;
1305
+            }
1306
+            // There was a time-range filter
1307
+            if ($componentType === 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) {
1308
+                $timeRange = $filters['comp-filters'][0]['time-range'];
1309
+
1310
+                // If start time OR the end time is not specified, we can do a
1311
+                // 100% accurate mysql query.
1312
+                if (!$filters['prop-filters'] && !$filters['comp-filters'][0]['comp-filters'] && !$filters['comp-filters'][0]['prop-filters'] && (!$timeRange['start'] || !$timeRange['end'])) {
1313
+                    $requirePostFilter = false;
1314
+                }
1315
+            }
1316
+
1317
+        }
1318
+        $columns = ['uri'];
1319
+        if ($requirePostFilter) {
1320
+            $columns = ['uri', 'calendardata'];
1321
+        }
1322
+        $query = $this->db->getQueryBuilder();
1323
+        $query->select($columns)
1324
+            ->from('calendarobjects')
1325
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($id)))
1326
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
1327
+
1328
+        if ($componentType) {
1329
+            $query->andWhere($query->expr()->eq('componenttype', $query->createNamedParameter($componentType)));
1330
+        }
1331
+
1332
+        if ($timeRange && $timeRange['start']) {
1333
+            $query->andWhere($query->expr()->gt('lastoccurence', $query->createNamedParameter($timeRange['start']->getTimeStamp())));
1334
+        }
1335
+        if ($timeRange && $timeRange['end']) {
1336
+            $query->andWhere($query->expr()->lt('firstoccurence', $query->createNamedParameter($timeRange['end']->getTimeStamp())));
1337
+        }
1338
+
1339
+        $stmt = $query->execute();
1340
+
1341
+        $result = [];
1342
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1343
+            if ($requirePostFilter) {
1344
+                // validateFilterForObject will parse the calendar data
1345
+                // catch parsing errors
1346
+                try {
1347
+                    $matches = $this->validateFilterForObject($row, $filters);
1348
+                } catch(ParseException $ex) {
1349
+                    $this->logger->logException($ex, [
1350
+                        'app' => 'dav',
1351
+                        'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1352
+                    ]);
1353
+                    continue;
1354
+                } catch (InvalidDataException $ex) {
1355
+                    $this->logger->logException($ex, [
1356
+                        'app' => 'dav',
1357
+                        'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$id.' uri:'.$row['uri']
1358
+                    ]);
1359
+                    continue;
1360
+                }
1361
+
1362
+                if (!$matches) {
1363
+                    continue;
1364
+                }
1365
+            }
1366
+            $result[] = $row['uri'];
1367
+        }
1368
+
1369
+        return $result;
1370
+    }
1371
+
1372
+    /**
1373
+     * custom Nextcloud search extension for CalDAV
1374
+     *
1375
+     * TODO - this should optionally cover cached calendar objects as well
1376
+     *
1377
+     * @param string $principalUri
1378
+     * @param array $filters
1379
+     * @param integer|null $limit
1380
+     * @param integer|null $offset
1381
+     * @return array
1382
+     */
1383
+    public function calendarSearch($principalUri, array $filters, $limit=null, $offset=null) {
1384
+        $calendars = $this->getCalendarsForUser($principalUri);
1385
+        $ownCalendars = [];
1386
+        $sharedCalendars = [];
1387
+
1388
+        $uriMapper = [];
1389
+
1390
+        foreach($calendars as $calendar) {
1391
+            if ($calendar['{http://owncloud.org/ns}owner-principal'] === $principalUri) {
1392
+                $ownCalendars[] = $calendar['id'];
1393
+            } else {
1394
+                $sharedCalendars[] = $calendar['id'];
1395
+            }
1396
+            $uriMapper[$calendar['id']] = $calendar['uri'];
1397
+        }
1398
+        if (count($ownCalendars) === 0 && count($sharedCalendars) === 0) {
1399
+            return [];
1400
+        }
1401
+
1402
+        $query = $this->db->getQueryBuilder();
1403
+        // Calendar id expressions
1404
+        $calendarExpressions = [];
1405
+        foreach($ownCalendars as $id) {
1406
+            $calendarExpressions[] = $query->expr()->andX(
1407
+                $query->expr()->eq('c.calendarid',
1408
+                    $query->createNamedParameter($id)),
1409
+                $query->expr()->eq('c.calendartype',
1410
+                        $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1411
+        }
1412
+        foreach($sharedCalendars as $id) {
1413
+            $calendarExpressions[] = $query->expr()->andX(
1414
+                $query->expr()->eq('c.calendarid',
1415
+                    $query->createNamedParameter($id)),
1416
+                $query->expr()->eq('c.classification',
1417
+                    $query->createNamedParameter(self::CLASSIFICATION_PUBLIC)),
1418
+                $query->expr()->eq('c.calendartype',
1419
+                    $query->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1420
+        }
1421
+
1422
+        if (count($calendarExpressions) === 1) {
1423
+            $calExpr = $calendarExpressions[0];
1424
+        } else {
1425
+            $calExpr = call_user_func_array([$query->expr(), 'orX'], $calendarExpressions);
1426
+        }
1427
+
1428
+        // Component expressions
1429
+        $compExpressions = [];
1430
+        foreach($filters['comps'] as $comp) {
1431
+            $compExpressions[] = $query->expr()
1432
+                ->eq('c.componenttype', $query->createNamedParameter($comp));
1433
+        }
1434
+
1435
+        if (count($compExpressions) === 1) {
1436
+            $compExpr = $compExpressions[0];
1437
+        } else {
1438
+            $compExpr = call_user_func_array([$query->expr(), 'orX'], $compExpressions);
1439
+        }
1440
+
1441
+        if (!isset($filters['props'])) {
1442
+            $filters['props'] = [];
1443
+        }
1444
+        if (!isset($filters['params'])) {
1445
+            $filters['params'] = [];
1446
+        }
1447
+
1448
+        $propParamExpressions = [];
1449
+        foreach($filters['props'] as $prop) {
1450
+            $propParamExpressions[] = $query->expr()->andX(
1451
+                $query->expr()->eq('i.name', $query->createNamedParameter($prop)),
1452
+                $query->expr()->isNull('i.parameter')
1453
+            );
1454
+        }
1455
+        foreach($filters['params'] as $param) {
1456
+            $propParamExpressions[] = $query->expr()->andX(
1457
+                $query->expr()->eq('i.name', $query->createNamedParameter($param['property'])),
1458
+                $query->expr()->eq('i.parameter', $query->createNamedParameter($param['parameter']))
1459
+            );
1460
+        }
1461
+
1462
+        if (count($propParamExpressions) === 1) {
1463
+            $propParamExpr = $propParamExpressions[0];
1464
+        } else {
1465
+            $propParamExpr = call_user_func_array([$query->expr(), 'orX'], $propParamExpressions);
1466
+        }
1467
+
1468
+        $query->select(['c.calendarid', 'c.uri'])
1469
+            ->from($this->dbObjectPropertiesTable, 'i')
1470
+            ->join('i', 'calendarobjects', 'c', $query->expr()->eq('i.objectid', 'c.id'))
1471
+            ->where($calExpr)
1472
+            ->andWhere($compExpr)
1473
+            ->andWhere($propParamExpr)
1474
+            ->andWhere($query->expr()->iLike('i.value',
1475
+                $query->createNamedParameter('%'.$this->db->escapeLikeParameter($filters['search-term']).'%')));
1476
+
1477
+        if ($offset) {
1478
+            $query->setFirstResult($offset);
1479
+        }
1480
+        if ($limit) {
1481
+            $query->setMaxResults($limit);
1482
+        }
1483
+
1484
+        $stmt = $query->execute();
1485
+
1486
+        $result = [];
1487
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1488
+            $path = $uriMapper[$row['calendarid']] . '/' . $row['uri'];
1489
+            if (!in_array($path, $result)) {
1490
+                $result[] = $path;
1491
+            }
1492
+        }
1493
+
1494
+        return $result;
1495
+    }
1496
+
1497
+    /**
1498
+     * used for Nextcloud's calendar API
1499
+     *
1500
+     * @param array $calendarInfo
1501
+     * @param string $pattern
1502
+     * @param array $searchProperties
1503
+     * @param array $options
1504
+     * @param integer|null $limit
1505
+     * @param integer|null $offset
1506
+     *
1507
+     * @return array
1508
+     */
1509
+    public function search(array $calendarInfo, $pattern, array $searchProperties,
1510
+                            array $options, $limit, $offset) {
1511
+        $outerQuery = $this->db->getQueryBuilder();
1512
+        $innerQuery = $this->db->getQueryBuilder();
1513
+
1514
+        $innerQuery->selectDistinct('op.objectid')
1515
+            ->from($this->dbObjectPropertiesTable, 'op')
1516
+            ->andWhere($innerQuery->expr()->eq('op.calendarid',
1517
+                $outerQuery->createNamedParameter($calendarInfo['id'])))
1518
+            ->andWhere($innerQuery->expr()->eq('op.calendartype',
1519
+                $outerQuery->createNamedParameter(self::CALENDAR_TYPE_CALENDAR)));
1520
+
1521
+        // only return public items for shared calendars for now
1522
+        if ($calendarInfo['principaluri'] !== $calendarInfo['{http://owncloud.org/ns}owner-principal']) {
1523
+            $innerQuery->andWhere($innerQuery->expr()->eq('c.classification',
1524
+                $outerQuery->createNamedParameter(self::CLASSIFICATION_PUBLIC)));
1525
+        }
1526
+
1527
+        $or = $innerQuery->expr()->orX();
1528
+        foreach($searchProperties as $searchProperty) {
1529
+            $or->add($innerQuery->expr()->eq('op.name',
1530
+                $outerQuery->createNamedParameter($searchProperty)));
1531
+        }
1532
+        $innerQuery->andWhere($or);
1533
+
1534
+        if ($pattern !== '') {
1535
+            $innerQuery->andWhere($innerQuery->expr()->iLike('op.value',
1536
+                $outerQuery->createNamedParameter('%' .
1537
+                    $this->db->escapeLikeParameter($pattern) . '%')));
1538
+        }
1539
+
1540
+        $outerQuery->select('c.id', 'c.calendardata', 'c.componenttype', 'c.uid', 'c.uri')
1541
+            ->from('calendarobjects', 'c');
1542
+
1543
+        if (isset($options['timerange'])) {
1544
+            if (isset($options['timerange']['start'])) {
1545
+                $outerQuery->andWhere($outerQuery->expr()->gt('lastoccurence',
1546
+                    $outerQuery->createNamedParameter($options['timerange']['start']->getTimeStamp)));
1547
+
1548
+            }
1549
+            if (isset($options['timerange']['end'])) {
1550
+                $outerQuery->andWhere($outerQuery->expr()->lt('firstoccurence',
1551
+                    $outerQuery->createNamedParameter($options['timerange']['end']->getTimeStamp)));
1552
+            }
1553
+        }
1554
+
1555
+        if (isset($options['types'])) {
1556
+            $or = $outerQuery->expr()->orX();
1557
+            foreach($options['types'] as $type) {
1558
+                $or->add($outerQuery->expr()->eq('componenttype',
1559
+                    $outerQuery->createNamedParameter($type)));
1560
+            }
1561
+            $outerQuery->andWhere($or);
1562
+        }
1563
+
1564
+        $outerQuery->andWhere($outerQuery->expr()->in('c.id',
1565
+            $outerQuery->createFunction($innerQuery->getSQL())));
1566
+
1567
+        if ($offset) {
1568
+            $outerQuery->setFirstResult($offset);
1569
+        }
1570
+        if ($limit) {
1571
+            $outerQuery->setMaxResults($limit);
1572
+        }
1573
+
1574
+        $result = $outerQuery->execute();
1575
+        $calendarObjects = $result->fetchAll();
1576
+
1577
+        return array_map(function($o) {
1578
+            $calendarData = Reader::read($o['calendardata']);
1579
+            $comps = $calendarData->getComponents();
1580
+            $objects = [];
1581
+            $timezones = [];
1582
+            foreach($comps as $comp) {
1583
+                if ($comp instanceof VTimeZone) {
1584
+                    $timezones[] = $comp;
1585
+                } else {
1586
+                    $objects[] = $comp;
1587
+                }
1588
+            }
1589
+
1590
+            return [
1591
+                'id' => $o['id'],
1592
+                'type' => $o['componenttype'],
1593
+                'uid' => $o['uid'],
1594
+                'uri' => $o['uri'],
1595
+                'objects' => array_map(function($c) {
1596
+                    return $this->transformSearchData($c);
1597
+                }, $objects),
1598
+                'timezones' => array_map(function($c) {
1599
+                    return $this->transformSearchData($c);
1600
+                }, $timezones),
1601
+            ];
1602
+        }, $calendarObjects);
1603
+    }
1604
+
1605
+    /**
1606
+     * @param Component $comp
1607
+     * @return array
1608
+     */
1609
+    private function transformSearchData(Component $comp) {
1610
+        $data = [];
1611
+        /** @var Component[] $subComponents */
1612
+        $subComponents = $comp->getComponents();
1613
+        /** @var Property[] $properties */
1614
+        $properties = array_filter($comp->children(), function($c) {
1615
+            return $c instanceof Property;
1616
+        });
1617
+        $validationRules = $comp->getValidationRules();
1618
+
1619
+        foreach($subComponents as $subComponent) {
1620
+            $name = $subComponent->name;
1621
+            if (!isset($data[$name])) {
1622
+                $data[$name] = [];
1623
+            }
1624
+            $data[$name][] = $this->transformSearchData($subComponent);
1625
+        }
1626
+
1627
+        foreach($properties as $property) {
1628
+            $name = $property->name;
1629
+            if (!isset($validationRules[$name])) {
1630
+                $validationRules[$name] = '*';
1631
+            }
1632
+
1633
+            $rule = $validationRules[$property->name];
1634
+            if ($rule === '+' || $rule === '*') { // multiple
1635
+                if (!isset($data[$name])) {
1636
+                    $data[$name] = [];
1637
+                }
1638
+
1639
+                $data[$name][] = $this->transformSearchProperty($property);
1640
+            } else { // once
1641
+                $data[$name] = $this->transformSearchProperty($property);
1642
+            }
1643
+        }
1644
+
1645
+        return $data;
1646
+    }
1647
+
1648
+    /**
1649
+     * @param Property $prop
1650
+     * @return array
1651
+     */
1652
+    private function transformSearchProperty(Property $prop) {
1653
+        // No need to check Date, as it extends DateTime
1654
+        if ($prop instanceof Property\ICalendar\DateTime) {
1655
+            $value = $prop->getDateTime();
1656
+        } else {
1657
+            $value = $prop->getValue();
1658
+        }
1659
+
1660
+        return [
1661
+            $value,
1662
+            $prop->parameters()
1663
+        ];
1664
+    }
1665
+
1666
+    /**
1667
+     * Searches through all of a users calendars and calendar objects to find
1668
+     * an object with a specific UID.
1669
+     *
1670
+     * This method should return the path to this object, relative to the
1671
+     * calendar home, so this path usually only contains two parts:
1672
+     *
1673
+     * calendarpath/objectpath.ics
1674
+     *
1675
+     * If the uid is not found, return null.
1676
+     *
1677
+     * This method should only consider * objects that the principal owns, so
1678
+     * any calendars owned by other principals that also appear in this
1679
+     * collection should be ignored.
1680
+     *
1681
+     * @param string $principalUri
1682
+     * @param string $uid
1683
+     * @return string|null
1684
+     */
1685
+    function getCalendarObjectByUID($principalUri, $uid) {
1686
+
1687
+        $query = $this->db->getQueryBuilder();
1688
+        $query->selectAlias('c.uri', 'calendaruri')->selectAlias('co.uri', 'objecturi')
1689
+            ->from('calendarobjects', 'co')
1690
+            ->leftJoin('co', 'calendars', 'c', $query->expr()->eq('co.calendarid', 'c.id'))
1691
+            ->where($query->expr()->eq('c.principaluri', $query->createNamedParameter($principalUri)))
1692
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)))
1693
+            ->andWhere($query->expr()->eq('co.uid', $query->createNamedParameter($uid)));
1694
+
1695
+        $stmt = $query->execute();
1696
+
1697
+        if ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1698
+            return $row['calendaruri'] . '/' . $row['objecturi'];
1699
+        }
1700
+
1701
+        return null;
1702
+    }
1703
+
1704
+    /**
1705
+     * The getChanges method returns all the changes that have happened, since
1706
+     * the specified syncToken in the specified calendar.
1707
+     *
1708
+     * This function should return an array, such as the following:
1709
+     *
1710
+     * [
1711
+     *   'syncToken' => 'The current synctoken',
1712
+     *   'added'   => [
1713
+     *      'new.txt',
1714
+     *   ],
1715
+     *   'modified'   => [
1716
+     *      'modified.txt',
1717
+     *   ],
1718
+     *   'deleted' => [
1719
+     *      'foo.php.bak',
1720
+     *      'old.txt'
1721
+     *   ]
1722
+     * );
1723
+     *
1724
+     * The returned syncToken property should reflect the *current* syncToken
1725
+     * of the calendar, as reported in the {http://sabredav.org/ns}sync-token
1726
+     * property This is * needed here too, to ensure the operation is atomic.
1727
+     *
1728
+     * If the $syncToken argument is specified as null, this is an initial
1729
+     * sync, and all members should be reported.
1730
+     *
1731
+     * The modified property is an array of nodenames that have changed since
1732
+     * the last token.
1733
+     *
1734
+     * The deleted property is an array with nodenames, that have been deleted
1735
+     * from collection.
1736
+     *
1737
+     * The $syncLevel argument is basically the 'depth' of the report. If it's
1738
+     * 1, you only have to report changes that happened only directly in
1739
+     * immediate descendants. If it's 2, it should also include changes from
1740
+     * the nodes below the child collections. (grandchildren)
1741
+     *
1742
+     * The $limit argument allows a client to specify how many results should
1743
+     * be returned at most. If the limit is not specified, it should be treated
1744
+     * as infinite.
1745
+     *
1746
+     * If the limit (infinite or not) is higher than you're willing to return,
1747
+     * you should throw a Sabre\DAV\Exception\TooMuchMatches() exception.
1748
+     *
1749
+     * If the syncToken is expired (due to data cleanup) or unknown, you must
1750
+     * return null.
1751
+     *
1752
+     * The limit is 'suggestive'. You are free to ignore it.
1753
+     *
1754
+     * @param string $calendarId
1755
+     * @param string $syncToken
1756
+     * @param int $syncLevel
1757
+     * @param int $limit
1758
+     * @param int $calendarType
1759
+     * @return array
1760
+     */
1761
+    function getChangesForCalendar($calendarId, $syncToken, $syncLevel, $limit = null, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
1762
+        // Current synctoken
1763
+        $stmt = $this->db->prepare('SELECT `synctoken` FROM `*PREFIX*calendars` WHERE `id` = ?');
1764
+        $stmt->execute([ $calendarId ]);
1765
+        $currentToken = $stmt->fetchColumn(0);
1766
+
1767
+        if (is_null($currentToken)) {
1768
+            return null;
1769
+        }
1770
+
1771
+        $result = [
1772
+            'syncToken' => $currentToken,
1773
+            'added'     => [],
1774
+            'modified'  => [],
1775
+            'deleted'   => [],
1776
+        ];
1777
+
1778
+        if ($syncToken) {
1779
+
1780
+            $query = "SELECT `uri`, `operation` FROM `*PREFIX*calendarchanges` WHERE `synctoken` >= ? AND `synctoken` < ? AND `calendarid` = ? AND `calendartype` = ? ORDER BY `synctoken`";
1781
+            if ($limit>0) {
1782
+                $query.= " LIMIT " . (int)$limit;
1783
+            }
1784
+
1785
+            // Fetching all changes
1786
+            $stmt = $this->db->prepare($query);
1787
+            $stmt->execute([$syncToken, $currentToken, $calendarId, $calendarType]);
1788
+
1789
+            $changes = [];
1790
+
1791
+            // This loop ensures that any duplicates are overwritten, only the
1792
+            // last change on a node is relevant.
1793
+            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1794
+
1795
+                $changes[$row['uri']] = $row['operation'];
1796
+
1797
+            }
1798
+
1799
+            foreach($changes as $uri => $operation) {
1800
+
1801
+                switch($operation) {
1802
+                    case 1 :
1803
+                        $result['added'][] = $uri;
1804
+                        break;
1805
+                    case 2 :
1806
+                        $result['modified'][] = $uri;
1807
+                        break;
1808
+                    case 3 :
1809
+                        $result['deleted'][] = $uri;
1810
+                        break;
1811
+                }
1812
+
1813
+            }
1814
+        } else {
1815
+            // No synctoken supplied, this is the initial sync.
1816
+            $query = "SELECT `uri` FROM `*PREFIX*calendarobjects` WHERE `calendarid` = ? AND `calendartype` = ?";
1817
+            $stmt = $this->db->prepare($query);
1818
+            $stmt->execute([$calendarId, $calendarType]);
1819
+
1820
+            $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN);
1821
+        }
1822
+        return $result;
1823
+
1824
+    }
1825
+
1826
+    /**
1827
+     * Returns a list of subscriptions for a principal.
1828
+     *
1829
+     * Every subscription is an array with the following keys:
1830
+     *  * id, a unique id that will be used by other functions to modify the
1831
+     *    subscription. This can be the same as the uri or a database key.
1832
+     *  * uri. This is just the 'base uri' or 'filename' of the subscription.
1833
+     *  * principaluri. The owner of the subscription. Almost always the same as
1834
+     *    principalUri passed to this method.
1835
+     *
1836
+     * Furthermore, all the subscription info must be returned too:
1837
+     *
1838
+     * 1. {DAV:}displayname
1839
+     * 2. {http://apple.com/ns/ical/}refreshrate
1840
+     * 3. {http://calendarserver.org/ns/}subscribed-strip-todos (omit if todos
1841
+     *    should not be stripped).
1842
+     * 4. {http://calendarserver.org/ns/}subscribed-strip-alarms (omit if alarms
1843
+     *    should not be stripped).
1844
+     * 5. {http://calendarserver.org/ns/}subscribed-strip-attachments (omit if
1845
+     *    attachments should not be stripped).
1846
+     * 6. {http://calendarserver.org/ns/}source (Must be a
1847
+     *     Sabre\DAV\Property\Href).
1848
+     * 7. {http://apple.com/ns/ical/}calendar-color
1849
+     * 8. {http://apple.com/ns/ical/}calendar-order
1850
+     * 9. {urn:ietf:params:xml:ns:caldav}supported-calendar-component-set
1851
+     *    (should just be an instance of
1852
+     *    Sabre\CalDAV\Property\SupportedCalendarComponentSet, with a bunch of
1853
+     *    default components).
1854
+     *
1855
+     * @param string $principalUri
1856
+     * @return array
1857
+     */
1858
+    function getSubscriptionsForUser($principalUri) {
1859
+        $fields = array_values($this->subscriptionPropertyMap);
1860
+        $fields[] = 'id';
1861
+        $fields[] = 'uri';
1862
+        $fields[] = 'source';
1863
+        $fields[] = 'principaluri';
1864
+        $fields[] = 'lastmodified';
1865
+        $fields[] = 'synctoken';
1866
+
1867
+        $query = $this->db->getQueryBuilder();
1868
+        $query->select($fields)
1869
+            ->from('calendarsubscriptions')
1870
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
1871
+            ->orderBy('calendarorder', 'asc');
1872
+        $stmt =$query->execute();
1873
+
1874
+        $subscriptions = [];
1875
+        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
1876
+
1877
+            $subscription = [
1878
+                'id'           => $row['id'],
1879
+                'uri'          => $row['uri'],
1880
+                'principaluri' => $row['principaluri'],
1881
+                'source'       => $row['source'],
1882
+                'lastmodified' => $row['lastmodified'],
1883
+
1884
+                '{' . Plugin::NS_CALDAV . '}supported-calendar-component-set' => new SupportedCalendarComponentSet(['VTODO', 'VEVENT']),
1885
+                '{http://sabredav.org/ns}sync-token' => $row['synctoken']?$row['synctoken']:'0',
1886
+            ];
1887
+
1888
+            foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1889
+                if (!is_null($row[$dbName])) {
1890
+                    $subscription[$xmlName] = $row[$dbName];
1891
+                }
1892
+            }
1893
+
1894
+            $subscriptions[] = $subscription;
1895
+
1896
+        }
1897
+
1898
+        return $subscriptions;
1899
+    }
1900
+
1901
+    /**
1902
+     * Creates a new subscription for a principal.
1903
+     *
1904
+     * If the creation was a success, an id must be returned that can be used to reference
1905
+     * this subscription in other methods, such as updateSubscription.
1906
+     *
1907
+     * @param string $principalUri
1908
+     * @param string $uri
1909
+     * @param array $properties
1910
+     * @return mixed
1911
+     */
1912
+    function createSubscription($principalUri, $uri, array $properties) {
1913
+
1914
+        if (!isset($properties['{http://calendarserver.org/ns/}source'])) {
1915
+            throw new Forbidden('The {http://calendarserver.org/ns/}source property is required when creating subscriptions');
1916
+        }
1917
+
1918
+        $values = [
1919
+            'principaluri' => $principalUri,
1920
+            'uri'          => $uri,
1921
+            'source'       => $properties['{http://calendarserver.org/ns/}source']->getHref(),
1922
+            'lastmodified' => time(),
1923
+        ];
1924
+
1925
+        $propertiesBoolean = ['striptodos', 'stripalarms', 'stripattachments'];
1926
+
1927
+        foreach($this->subscriptionPropertyMap as $xmlName=>$dbName) {
1928
+            if (array_key_exists($xmlName, $properties)) {
1929
+                    $values[$dbName] = $properties[$xmlName];
1930
+                    if (in_array($dbName, $propertiesBoolean)) {
1931
+                        $values[$dbName] = true;
1932
+                }
1933
+            }
1934
+        }
1935
+
1936
+        $valuesToInsert = array();
1937
+
1938
+        $query = $this->db->getQueryBuilder();
1939
+
1940
+        foreach (array_keys($values) as $name) {
1941
+            $valuesToInsert[$name] = $query->createNamedParameter($values[$name]);
1942
+        }
1943
+
1944
+        $query->insert('calendarsubscriptions')
1945
+            ->values($valuesToInsert)
1946
+            ->execute();
1947
+
1948
+        $subscriptionId = $this->db->lastInsertId('*PREFIX*calendarsubscriptions');
1949
+
1950
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent(
1951
+            '\OCA\DAV\CalDAV\CalDavBackend::createSubscription',
1952
+            [
1953
+                'subscriptionId' => $subscriptionId,
1954
+                'subscriptionData' => $this->getSubscriptionById($subscriptionId),
1955
+            ]));
1956
+
1957
+        return $subscriptionId;
1958
+    }
1959
+
1960
+    /**
1961
+     * Updates a subscription
1962
+     *
1963
+     * The list of mutations is stored in a Sabre\DAV\PropPatch object.
1964
+     * To do the actual updates, you must tell this object which properties
1965
+     * you're going to process with the handle() method.
1966
+     *
1967
+     * Calling the handle method is like telling the PropPatch object "I
1968
+     * promise I can handle updating this property".
1969
+     *
1970
+     * Read the PropPatch documentation for more info and examples.
1971
+     *
1972
+     * @param mixed $subscriptionId
1973
+     * @param PropPatch $propPatch
1974
+     * @return void
1975
+     */
1976
+    function updateSubscription($subscriptionId, PropPatch $propPatch) {
1977
+        $supportedProperties = array_keys($this->subscriptionPropertyMap);
1978
+        $supportedProperties[] = '{http://calendarserver.org/ns/}source';
1979
+
1980
+        /**
1981
+         * @suppress SqlInjectionChecker
1982
+         */
1983
+        $propPatch->handle($supportedProperties, function($mutations) use ($subscriptionId) {
1984
+
1985
+            $newValues = [];
1986
+
1987
+            foreach($mutations as $propertyName=>$propertyValue) {
1988
+                if ($propertyName === '{http://calendarserver.org/ns/}source') {
1989
+                    $newValues['source'] = $propertyValue->getHref();
1990
+                } else {
1991
+                    $fieldName = $this->subscriptionPropertyMap[$propertyName];
1992
+                    $newValues[$fieldName] = $propertyValue;
1993
+                }
1994
+            }
1995
+
1996
+            $query = $this->db->getQueryBuilder();
1997
+            $query->update('calendarsubscriptions')
1998
+                ->set('lastmodified', $query->createNamedParameter(time()));
1999
+            foreach($newValues as $fieldName=>$value) {
2000
+                $query->set($fieldName, $query->createNamedParameter($value));
2001
+            }
2002
+            $query->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2003
+                ->execute();
2004
+
2005
+            $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent(
2006
+                '\OCA\DAV\CalDAV\CalDavBackend::updateSubscription',
2007
+                [
2008
+                    'subscriptionId' => $subscriptionId,
2009
+                    'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2010
+                    'propertyMutations' => $mutations,
2011
+                ]));
2012
+
2013
+            return true;
2014
+
2015
+        });
2016
+    }
2017
+
2018
+    /**
2019
+     * Deletes a subscription.
2020
+     *
2021
+     * @param mixed $subscriptionId
2022
+     * @return void
2023
+     */
2024
+    function deleteSubscription($subscriptionId) {
2025
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent(
2026
+            '\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription',
2027
+            [
2028
+                'subscriptionId' => $subscriptionId,
2029
+                'subscriptionData' => $this->getSubscriptionById($subscriptionId),
2030
+            ]));
2031
+
2032
+        $query = $this->db->getQueryBuilder();
2033
+        $query->delete('calendarsubscriptions')
2034
+            ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId)))
2035
+            ->execute();
2036
+
2037
+        $query = $this->db->getQueryBuilder();
2038
+        $query->delete('calendarobjects')
2039
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2040
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2041
+            ->execute();
2042
+
2043
+        $query->delete('calendarchanges')
2044
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2045
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2046
+            ->execute();
2047
+
2048
+        $query->delete($this->dbObjectPropertiesTable)
2049
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2050
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2051
+            ->execute();
2052
+    }
2053
+
2054
+    /**
2055
+     * Returns a single scheduling object for the inbox collection.
2056
+     *
2057
+     * The returned array should contain the following elements:
2058
+     *   * uri - A unique basename for the object. This will be used to
2059
+     *           construct a full uri.
2060
+     *   * calendardata - The iCalendar object
2061
+     *   * lastmodified - The last modification date. Can be an int for a unix
2062
+     *                    timestamp, or a PHP DateTime object.
2063
+     *   * etag - A unique token that must change if the object changed.
2064
+     *   * size - The size of the object, in bytes.
2065
+     *
2066
+     * @param string $principalUri
2067
+     * @param string $objectUri
2068
+     * @return array
2069
+     */
2070
+    function getSchedulingObject($principalUri, $objectUri) {
2071
+        $query = $this->db->getQueryBuilder();
2072
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2073
+            ->from('schedulingobjects')
2074
+            ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2075
+            ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2076
+            ->execute();
2077
+
2078
+        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
2079
+
2080
+        if(!$row) {
2081
+            return null;
2082
+        }
2083
+
2084
+        return [
2085
+                'uri'          => $row['uri'],
2086
+                'calendardata' => $row['calendardata'],
2087
+                'lastmodified' => $row['lastmodified'],
2088
+                'etag'         => '"' . $row['etag'] . '"',
2089
+                'size'         => (int)$row['size'],
2090
+        ];
2091
+    }
2092
+
2093
+    /**
2094
+     * Returns all scheduling objects for the inbox collection.
2095
+     *
2096
+     * These objects should be returned as an array. Every item in the array
2097
+     * should follow the same structure as returned from getSchedulingObject.
2098
+     *
2099
+     * The main difference is that 'calendardata' is optional.
2100
+     *
2101
+     * @param string $principalUri
2102
+     * @return array
2103
+     */
2104
+    function getSchedulingObjects($principalUri) {
2105
+        $query = $this->db->getQueryBuilder();
2106
+        $stmt = $query->select(['uri', 'calendardata', 'lastmodified', 'etag', 'size'])
2107
+                ->from('schedulingobjects')
2108
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2109
+                ->execute();
2110
+
2111
+        $result = [];
2112
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2113
+            $result[] = [
2114
+                    'calendardata' => $row['calendardata'],
2115
+                    'uri'          => $row['uri'],
2116
+                    'lastmodified' => $row['lastmodified'],
2117
+                    'etag'         => '"' . $row['etag'] . '"',
2118
+                    'size'         => (int)$row['size'],
2119
+            ];
2120
+        }
2121
+
2122
+        return $result;
2123
+    }
2124
+
2125
+    /**
2126
+     * Deletes a scheduling object from the inbox collection.
2127
+     *
2128
+     * @param string $principalUri
2129
+     * @param string $objectUri
2130
+     * @return void
2131
+     */
2132
+    function deleteSchedulingObject($principalUri, $objectUri) {
2133
+        $query = $this->db->getQueryBuilder();
2134
+        $query->delete('schedulingobjects')
2135
+                ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri)))
2136
+                ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($objectUri)))
2137
+                ->execute();
2138
+    }
2139
+
2140
+    /**
2141
+     * Creates a new scheduling object. This should land in a users' inbox.
2142
+     *
2143
+     * @param string $principalUri
2144
+     * @param string $objectUri
2145
+     * @param string $objectData
2146
+     * @return void
2147
+     */
2148
+    function createSchedulingObject($principalUri, $objectUri, $objectData) {
2149
+        $query = $this->db->getQueryBuilder();
2150
+        $query->insert('schedulingobjects')
2151
+            ->values([
2152
+                'principaluri' => $query->createNamedParameter($principalUri),
2153
+                'calendardata' => $query->createNamedParameter($objectData, IQueryBuilder::PARAM_LOB),
2154
+                'uri' => $query->createNamedParameter($objectUri),
2155
+                'lastmodified' => $query->createNamedParameter(time()),
2156
+                'etag' => $query->createNamedParameter(md5($objectData)),
2157
+                'size' => $query->createNamedParameter(strlen($objectData))
2158
+            ])
2159
+            ->execute();
2160
+    }
2161
+
2162
+    /**
2163
+     * Adds a change record to the calendarchanges table.
2164
+     *
2165
+     * @param mixed $calendarId
2166
+     * @param string $objectUri
2167
+     * @param int $operation 1 = add, 2 = modify, 3 = delete.
2168
+     * @param int $calendarType
2169
+     * @return void
2170
+     */
2171
+    protected function addChange($calendarId, $objectUri, $operation, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2172
+        $table = $calendarType === self::CALENDAR_TYPE_CALENDAR ? 'calendars': 'calendarsubscriptions';
2173
+
2174
+        $query = $this->db->getQueryBuilder();
2175
+        $query->select('synctoken')
2176
+            ->from($table)
2177
+            ->where($query->expr()->eq('id', $query->createNamedParameter($calendarId)));
2178
+        $syncToken = (int)$query->execute()->fetchColumn();
2179
+
2180
+        $query = $this->db->getQueryBuilder();
2181
+        $query->insert('calendarchanges')
2182
+            ->values([
2183
+                'uri' => $query->createNamedParameter($objectUri),
2184
+                'synctoken' => $query->createNamedParameter($syncToken),
2185
+                'calendarid' => $query->createNamedParameter($calendarId),
2186
+                'operation' => $query->createNamedParameter($operation),
2187
+                'calendartype' => $query->createNamedParameter($calendarType),
2188
+            ])
2189
+            ->execute();
2190
+
2191
+        $stmt = $this->db->prepare("UPDATE `*PREFIX*$table` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?");
2192
+        $stmt->execute([
2193
+            $calendarId
2194
+        ]);
2195
+
2196
+    }
2197
+
2198
+    /**
2199
+     * Parses some information from calendar objects, used for optimized
2200
+     * calendar-queries.
2201
+     *
2202
+     * Returns an array with the following keys:
2203
+     *   * etag - An md5 checksum of the object without the quotes.
2204
+     *   * size - Size of the object in bytes
2205
+     *   * componentType - VEVENT, VTODO or VJOURNAL
2206
+     *   * firstOccurence
2207
+     *   * lastOccurence
2208
+     *   * uid - value of the UID property
2209
+     *
2210
+     * @param string $calendarData
2211
+     * @return array
2212
+     */
2213
+    public function getDenormalizedData($calendarData) {
2214
+
2215
+        $vObject = Reader::read($calendarData);
2216
+        $componentType = null;
2217
+        $component = null;
2218
+        $firstOccurrence = null;
2219
+        $lastOccurrence = null;
2220
+        $uid = null;
2221
+        $classification = self::CLASSIFICATION_PUBLIC;
2222
+        foreach($vObject->getComponents() as $component) {
2223
+            if ($component->name!=='VTIMEZONE') {
2224
+                $componentType = $component->name;
2225
+                $uid = (string)$component->UID;
2226
+                break;
2227
+            }
2228
+        }
2229
+        if (!$componentType) {
2230
+            throw new \Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
2231
+        }
2232
+        if ($componentType === 'VEVENT' && $component->DTSTART) {
2233
+            $firstOccurrence = $component->DTSTART->getDateTime()->getTimeStamp();
2234
+            // Finding the last occurrence is a bit harder
2235
+            if (!isset($component->RRULE)) {
2236
+                if (isset($component->DTEND)) {
2237
+                    $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp();
2238
+                } elseif (isset($component->DURATION)) {
2239
+                    $endDate = clone $component->DTSTART->getDateTime();
2240
+                    $endDate->add(DateTimeParser::parse($component->DURATION->getValue()));
2241
+                    $lastOccurrence = $endDate->getTimeStamp();
2242
+                } elseif (!$component->DTSTART->hasTime()) {
2243
+                    $endDate = clone $component->DTSTART->getDateTime();
2244
+                    $endDate->modify('+1 day');
2245
+                    $lastOccurrence = $endDate->getTimeStamp();
2246
+                } else {
2247
+                    $lastOccurrence = $firstOccurrence;
2248
+                }
2249
+            } else {
2250
+                $it = new EventIterator($vObject, (string)$component->UID);
2251
+                $maxDate = new \DateTime(self::MAX_DATE);
2252
+                if ($it->isInfinite()) {
2253
+                    $lastOccurrence = $maxDate->getTimestamp();
2254
+                } else {
2255
+                    $end = $it->getDtEnd();
2256
+                    while($it->valid() && $end < $maxDate) {
2257
+                        $end = $it->getDtEnd();
2258
+                        $it->next();
2259
+
2260
+                    }
2261
+                    $lastOccurrence = $end->getTimestamp();
2262
+                }
2263
+
2264
+            }
2265
+        }
2266
+
2267
+        if ($component->CLASS) {
2268
+            $classification = CalDavBackend::CLASSIFICATION_PRIVATE;
2269
+            switch ($component->CLASS->getValue()) {
2270
+                case 'PUBLIC':
2271
+                    $classification = CalDavBackend::CLASSIFICATION_PUBLIC;
2272
+                    break;
2273
+                case 'CONFIDENTIAL':
2274
+                    $classification = CalDavBackend::CLASSIFICATION_CONFIDENTIAL;
2275
+                    break;
2276
+            }
2277
+        }
2278
+        return [
2279
+            'etag' => md5($calendarData),
2280
+            'size' => strlen($calendarData),
2281
+            'componentType' => $componentType,
2282
+            'firstOccurence' => is_null($firstOccurrence) ? null : max(0, $firstOccurrence),
2283
+            'lastOccurence'  => $lastOccurrence,
2284
+            'uid' => $uid,
2285
+            'classification' => $classification
2286
+        ];
2287
+
2288
+    }
2289
+
2290
+    /**
2291
+     * @param $cardData
2292
+     * @return bool|string
2293
+     */
2294
+    private function readBlob($cardData) {
2295
+        if (is_resource($cardData)) {
2296
+            return stream_get_contents($cardData);
2297
+        }
2298
+
2299
+        return $cardData;
2300
+    }
2301
+
2302
+    /**
2303
+     * @param IShareable $shareable
2304
+     * @param array $add
2305
+     * @param array $remove
2306
+     */
2307
+    public function updateShares($shareable, $add, $remove) {
2308
+        $calendarId = $shareable->getResourceId();
2309
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent(
2310
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2311
+            [
2312
+                'calendarId' => $calendarId,
2313
+                'calendarData' => $this->getCalendarById($calendarId),
2314
+                'shares' => $this->getShares($calendarId),
2315
+                'add' => $add,
2316
+                'remove' => $remove,
2317
+            ]));
2318
+        $this->calendarSharingBackend->updateShares($shareable, $add, $remove);
2319
+    }
2320
+
2321
+    /**
2322
+     * @param int $resourceId
2323
+     * @param int $calendarType
2324
+     * @return array
2325
+     */
2326
+    public function getShares($resourceId, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2327
+        return $this->calendarSharingBackend->getShares($resourceId);
2328
+    }
2329
+
2330
+    /**
2331
+     * @param boolean $value
2332
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2333
+     * @return string|null
2334
+     */
2335
+    public function setPublishStatus($value, $calendar) {
2336
+
2337
+        $calendarId = $calendar->getResourceId();
2338
+        $this->dispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent(
2339
+            '\OCA\DAV\CalDAV\CalDavBackend::updateShares',
2340
+            [
2341
+                'calendarId' => $calendarId,
2342
+                'calendarData' => $this->getCalendarById($calendarId),
2343
+                'public' => $value,
2344
+            ]));
2345
+
2346
+        $query = $this->db->getQueryBuilder();
2347
+        if ($value) {
2348
+            $publicUri = $this->random->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
2349
+            $query->insert('dav_shares')
2350
+                ->values([
2351
+                    'principaluri' => $query->createNamedParameter($calendar->getPrincipalURI()),
2352
+                    'type' => $query->createNamedParameter('calendar'),
2353
+                    'access' => $query->createNamedParameter(self::ACCESS_PUBLIC),
2354
+                    'resourceid' => $query->createNamedParameter($calendar->getResourceId()),
2355
+                    'publicuri' => $query->createNamedParameter($publicUri)
2356
+                ]);
2357
+            $query->execute();
2358
+            return $publicUri;
2359
+        }
2360
+        $query->delete('dav_shares')
2361
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2362
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)));
2363
+        $query->execute();
2364
+        return null;
2365
+    }
2366
+
2367
+    /**
2368
+     * @param \OCA\DAV\CalDAV\Calendar $calendar
2369
+     * @return mixed
2370
+     */
2371
+    public function getPublishStatus($calendar) {
2372
+        $query = $this->db->getQueryBuilder();
2373
+        $result = $query->select('publicuri')
2374
+            ->from('dav_shares')
2375
+            ->where($query->expr()->eq('resourceid', $query->createNamedParameter($calendar->getResourceId())))
2376
+            ->andWhere($query->expr()->eq('access', $query->createNamedParameter(self::ACCESS_PUBLIC)))
2377
+            ->execute();
2378
+
2379
+        $row = $result->fetch();
2380
+        $result->closeCursor();
2381
+        return $row ? reset($row) : false;
2382
+    }
2383
+
2384
+    /**
2385
+     * @param int $resourceId
2386
+     * @param array $acl
2387
+     * @return array
2388
+     */
2389
+    public function applyShareAcl($resourceId, $acl) {
2390
+        return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl);
2391
+    }
2392
+
2393
+
2394
+
2395
+    /**
2396
+     * update properties table
2397
+     *
2398
+     * @param int $calendarId
2399
+     * @param string $objectUri
2400
+     * @param string $calendarData
2401
+     * @param int $calendarType
2402
+     */
2403
+    public function updateProperties($calendarId, $objectUri, $calendarData, $calendarType=self::CALENDAR_TYPE_CALENDAR) {
2404
+        $objectId = $this->getCalendarObjectId($calendarId, $objectUri, $calendarType);
2405
+
2406
+        try {
2407
+            $vCalendar = $this->readCalendarData($calendarData);
2408
+        } catch (\Exception $ex) {
2409
+            return;
2410
+        }
2411
+
2412
+        $this->purgeProperties($calendarId, $objectId);
2413
+
2414
+        $query = $this->db->getQueryBuilder();
2415
+        $query->insert($this->dbObjectPropertiesTable)
2416
+            ->values(
2417
+                [
2418
+                    'calendarid' => $query->createNamedParameter($calendarId),
2419
+                    'calendartype' => $query->createNamedParameter($calendarType),
2420
+                    'objectid' => $query->createNamedParameter($objectId),
2421
+                    'name' => $query->createParameter('name'),
2422
+                    'parameter' => $query->createParameter('parameter'),
2423
+                    'value' => $query->createParameter('value'),
2424
+                ]
2425
+            );
2426
+
2427
+        $indexComponents = ['VEVENT', 'VJOURNAL', 'VTODO'];
2428
+        foreach ($vCalendar->getComponents() as $component) {
2429
+            if (!in_array($component->name, $indexComponents)) {
2430
+                continue;
2431
+            }
2432
+
2433
+            foreach ($component->children() as $property) {
2434
+                if (in_array($property->name, self::$indexProperties)) {
2435
+                    $value = $property->getValue();
2436
+                    // is this a shitty db?
2437
+                    if (!$this->db->supports4ByteText()) {
2438
+                        $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2439
+                    }
2440
+                    $value = mb_substr($value, 0, 254);
2441
+
2442
+                    $query->setParameter('name', $property->name);
2443
+                    $query->setParameter('parameter', null);
2444
+                    $query->setParameter('value', $value);
2445
+                    $query->execute();
2446
+                }
2447
+
2448
+                if (array_key_exists($property->name, self::$indexParameters)) {
2449
+                    $parameters = $property->parameters();
2450
+                    $indexedParametersForProperty = self::$indexParameters[$property->name];
2451
+
2452
+                    foreach ($parameters as $key => $value) {
2453
+                        if (in_array($key, $indexedParametersForProperty)) {
2454
+                            // is this a shitty db?
2455
+                            if ($this->db->supports4ByteText()) {
2456
+                                $value = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $value);
2457
+                            }
2458
+                            $value = mb_substr($value, 0, 254);
2459
+
2460
+                            $query->setParameter('name', $property->name);
2461
+                            $query->setParameter('parameter', substr($key, 0, 254));
2462
+                            $query->setParameter('value', substr($value, 0, 254));
2463
+                            $query->execute();
2464
+                        }
2465
+                    }
2466
+                }
2467
+            }
2468
+        }
2469
+    }
2470
+
2471
+    /**
2472
+     * deletes all birthday calendars
2473
+     */
2474
+    public function deleteAllBirthdayCalendars() {
2475
+        $query = $this->db->getQueryBuilder();
2476
+        $result = $query->select(['id'])->from('calendars')
2477
+            ->where($query->expr()->eq('uri', $query->createNamedParameter(BirthdayService::BIRTHDAY_CALENDAR_URI)))
2478
+            ->execute();
2479
+
2480
+        $ids = $result->fetchAll();
2481
+        foreach($ids as $id) {
2482
+            $this->deleteCalendar($id['id']);
2483
+        }
2484
+    }
2485
+
2486
+    /**
2487
+     * @param $subscriptionId
2488
+     */
2489
+    public function purgeAllCachedEventsForSubscription($subscriptionId) {
2490
+        $query = $this->db->getQueryBuilder();
2491
+        $query->select('uri')
2492
+            ->from('calendarobjects')
2493
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2494
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)));
2495
+        $stmt = $query->execute();
2496
+
2497
+        $uris = [];
2498
+        foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
2499
+            $uris[] = $row['uri'];
2500
+        }
2501
+        $stmt->closeCursor();
2502
+
2503
+        $query = $this->db->getQueryBuilder();
2504
+        $query->delete('calendarobjects')
2505
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2506
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2507
+            ->execute();
2508
+
2509
+        $query->delete('calendarchanges')
2510
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2511
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2512
+            ->execute();
2513
+
2514
+        $query->delete($this->dbObjectPropertiesTable)
2515
+            ->where($query->expr()->eq('calendarid', $query->createNamedParameter($subscriptionId)))
2516
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter(self::CALENDAR_TYPE_SUBSCRIPTION)))
2517
+            ->execute();
2518
+
2519
+        foreach($uris as $uri) {
2520
+            $this->addChange($subscriptionId, $uri, 3, self::CALENDAR_TYPE_SUBSCRIPTION);
2521
+        }
2522
+    }
2523
+
2524
+    /**
2525
+     * read VCalendar data into a VCalendar object
2526
+     *
2527
+     * @param string $objectData
2528
+     * @return VCalendar
2529
+     */
2530
+    protected function readCalendarData($objectData) {
2531
+        return Reader::read($objectData);
2532
+    }
2533
+
2534
+    /**
2535
+     * delete all properties from a given calendar object
2536
+     *
2537
+     * @param int $calendarId
2538
+     * @param int $objectId
2539
+     */
2540
+    protected function purgeProperties($calendarId, $objectId) {
2541
+        $query = $this->db->getQueryBuilder();
2542
+        $query->delete($this->dbObjectPropertiesTable)
2543
+            ->where($query->expr()->eq('objectid', $query->createNamedParameter($objectId)))
2544
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)));
2545
+        $query->execute();
2546
+    }
2547
+
2548
+    /**
2549
+     * get ID from a given calendar object
2550
+     *
2551
+     * @param int $calendarId
2552
+     * @param string $uri
2553
+     * @param int $calendarType
2554
+     * @return int
2555
+     */
2556
+    protected function getCalendarObjectId($calendarId, $uri, $calendarType):int {
2557
+        $query = $this->db->getQueryBuilder();
2558
+        $query->select('id')
2559
+            ->from('calendarobjects')
2560
+            ->where($query->expr()->eq('uri', $query->createNamedParameter($uri)))
2561
+            ->andWhere($query->expr()->eq('calendarid', $query->createNamedParameter($calendarId)))
2562
+            ->andWhere($query->expr()->eq('calendartype', $query->createNamedParameter($calendarType)));
2563
+
2564
+        $result = $query->execute();
2565
+        $objectIds = $result->fetch();
2566
+        $result->closeCursor();
2567
+
2568
+        if (!isset($objectIds['id'])) {
2569
+            throw new \InvalidArgumentException('Calendarobject does not exists: ' . $uri);
2570
+        }
2571
+
2572
+        return (int)$objectIds['id'];
2573
+    }
2574
+
2575
+    /**
2576
+     * return legacy endpoint principal name to new principal name
2577
+     *
2578
+     * @param $principalUri
2579
+     * @param $toV2
2580
+     * @return string
2581
+     */
2582
+    private function convertPrincipal($principalUri, $toV2) {
2583
+        if ($this->principalBackend->getPrincipalPrefix() === 'principals') {
2584
+            list(, $name) = Uri\split($principalUri);
2585
+            if ($toV2 === true) {
2586
+                return "principals/users/$name";
2587
+            }
2588
+            return "principals/$name";
2589
+        }
2590
+        return $principalUri;
2591
+    }
2592
+
2593
+    /**
2594
+     * adds information about an owner to the calendar data
2595
+     *
2596
+     * @param $calendarInfo
2597
+     */
2598
+    private function addOwnerPrincipal(&$calendarInfo) {
2599
+        $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal';
2600
+        $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname';
2601
+        if (isset($calendarInfo[$ownerPrincipalKey])) {
2602
+            $uri = $calendarInfo[$ownerPrincipalKey];
2603
+        } else {
2604
+            $uri = $calendarInfo['principaluri'];
2605
+        }
2606
+
2607
+        $principalInformation = $this->principalBackend->getPrincipalByPath($uri);
2608
+        if (isset($principalInformation['{DAV:}displayname'])) {
2609
+            $calendarInfo[$displaynameKey] = $principalInformation['{DAV:}displayname'];
2610
+        }
2611
+    }
2612 2612
 }
Please login to merge, or discard this patch.
core/Command/Db/ConvertType.php 1 patch
Indentation   +405 added lines, -405 removed lines patch added patch discarded remove patch
@@ -51,409 +51,409 @@
 block discarded – undo
51 51
 use Symfony\Component\Console\Question\Question;
52 52
 
53 53
 class ConvertType extends Command implements CompletionAwareInterface {
54
-	/**
55
-	 * @var \OCP\IConfig
56
-	 */
57
-	protected $config;
58
-
59
-	/**
60
-	 * @var \OC\DB\ConnectionFactory
61
-	 */
62
-	protected $connectionFactory;
63
-
64
-	/** @var array */
65
-	protected $columnTypes;
66
-
67
-	/**
68
-	 * @param \OCP\IConfig $config
69
-	 * @param \OC\DB\ConnectionFactory $connectionFactory
70
-	 */
71
-	public function __construct(IConfig $config, ConnectionFactory $connectionFactory) {
72
-		$this->config = $config;
73
-		$this->connectionFactory = $connectionFactory;
74
-		parent::__construct();
75
-	}
76
-
77
-	protected function configure() {
78
-		$this
79
-			->setName('db:convert-type')
80
-			->setDescription('Convert the Nextcloud database to the newly configured one')
81
-			->addArgument(
82
-				'type',
83
-				InputArgument::REQUIRED,
84
-				'the type of the database to convert to'
85
-			)
86
-			->addArgument(
87
-				'username',
88
-				InputArgument::REQUIRED,
89
-				'the username of the database to convert to'
90
-			)
91
-			->addArgument(
92
-				'hostname',
93
-				InputArgument::REQUIRED,
94
-				'the hostname of the database to convert to'
95
-			)
96
-			->addArgument(
97
-				'database',
98
-				InputArgument::REQUIRED,
99
-				'the name of the database to convert to'
100
-			)
101
-			->addOption(
102
-				'port',
103
-				null,
104
-				InputOption::VALUE_REQUIRED,
105
-				'the port of the database to convert to'
106
-			)
107
-			->addOption(
108
-				'password',
109
-				null,
110
-				InputOption::VALUE_REQUIRED,
111
-				'the password of the database to convert to. Will be asked when not specified. Can also be passed via stdin.'
112
-			)
113
-			->addOption(
114
-				'clear-schema',
115
-				null,
116
-				InputOption::VALUE_NONE,
117
-				'remove all tables from the destination database'
118
-			)
119
-			->addOption(
120
-				'all-apps',
121
-				null,
122
-				InputOption::VALUE_NONE,
123
-				'whether to create schema for all apps instead of only installed apps'
124
-			)
125
-			->addOption(
126
-				'chunk-size',
127
-				null,
128
-				InputOption::VALUE_REQUIRED,
129
-				'the maximum number of database rows to handle in a single query, bigger tables will be handled in chunks of this size. Lower this if the process runs out of memory during conversion.',
130
-				1000
131
-			)
132
-		;
133
-	}
134
-
135
-	protected function validateInput(InputInterface $input, OutputInterface $output) {
136
-		$type = $this->connectionFactory->normalizeType($input->getArgument('type'));
137
-		if ($type === 'sqlite3') {
138
-			throw new \InvalidArgumentException(
139
-				'Converting to SQLite (sqlite3) is currently not supported.'
140
-			);
141
-		}
142
-		if ($type === $this->config->getSystemValue('dbtype', '')) {
143
-			throw new \InvalidArgumentException(sprintf(
144
-				'Can not convert from %1$s to %1$s.',
145
-				$type
146
-			));
147
-		}
148
-		if ($type === 'oci' && $input->getOption('clear-schema')) {
149
-			// Doctrine unconditionally tries (at least in version 2.3)
150
-			// to drop sequence triggers when dropping a table, even though
151
-			// such triggers may not exist. This results in errors like
152
-			// "ORA-04080: trigger 'OC_STORAGES_AI_PK' does not exist".
153
-			throw new \InvalidArgumentException(
154
-				'The --clear-schema option is not supported when converting to Oracle (oci).'
155
-			);
156
-		}
157
-	}
158
-
159
-	protected function readPassword(InputInterface $input, OutputInterface $output) {
160
-		// Explicitly specified password
161
-		if ($input->getOption('password')) {
162
-			return;
163
-		}
164
-
165
-		// Read from stdin. stream_set_blocking is used to prevent blocking
166
-		// when nothing is passed via stdin.
167
-		stream_set_blocking(STDIN, 0);
168
-		$password = file_get_contents('php://stdin');
169
-		stream_set_blocking(STDIN, 1);
170
-		if (trim($password) !== '') {
171
-			$input->setOption('password', $password);
172
-			return;
173
-		}
174
-
175
-		// Read password by interacting
176
-		if ($input->isInteractive()) {
177
-			/** @var QuestionHelper $helper */
178
-			$helper = $this->getHelper('question');
179
-			$question = new Question('What is the database password?');
180
-			$question->setHidden(true);
181
-			$question->setHiddenFallback(false);
182
-			$password = $helper->ask($input, $output, $question);
183
-			$input->setOption('password', $password);
184
-			return;
185
-		}
186
-	}
187
-
188
-	protected function execute(InputInterface $input, OutputInterface $output) {
189
-		$this->validateInput($input, $output);
190
-		$this->readPassword($input, $output);
191
-
192
-		$fromDB = \OC::$server->getDatabaseConnection();
193
-		$toDB = $this->getToDBConnection($input, $output);
194
-
195
-		if ($input->getOption('clear-schema')) {
196
-			$this->clearSchema($toDB, $input, $output);
197
-		}
198
-
199
-		$this->createSchema($fromDB, $toDB, $input, $output);
200
-
201
-		$toTables = $this->getTables($toDB);
202
-		$fromTables = $this->getTables($fromDB);
203
-
204
-		// warn/fail if there are more tables in 'from' database
205
-		$extraFromTables = array_diff($fromTables, $toTables);
206
-		if (!empty($extraFromTables)) {
207
-			$output->writeln('<comment>The following tables will not be converted:</comment>');
208
-			$output->writeln($extraFromTables);
209
-			if (!$input->getOption('all-apps')) {
210
-				$output->writeln('<comment>Please note that tables belonging to available but currently not installed apps</comment>');
211
-				$output->writeln('<comment>can be included by specifying the --all-apps option.</comment>');
212
-			}
213
-
214
-			/** @var QuestionHelper $helper */
215
-			$helper = $this->getHelper('question');
216
-			$question = new ConfirmationQuestion('Continue with the conversion (y/n)? [n] ', false);
217
-
218
-			if (!$helper->ask($input, $output, $question)) {
219
-				return;
220
-			}
221
-		}
222
-		$intersectingTables = array_intersect($toTables, $fromTables);
223
-		$this->convertDB($fromDB, $toDB, $intersectingTables, $input, $output);
224
-	}
225
-
226
-	protected function createSchema(Connection $fromDB, Connection $toDB, InputInterface $input, OutputInterface $output) {
227
-		$output->writeln('<info>Creating schema in new database</info>');
228
-
229
-		$fromMS = new MigrationService('core', $fromDB);
230
-		$currentMigration = $fromMS->getMigration('current');
231
-		if ($currentMigration !== '0') {
232
-			$toMS = new MigrationService('core', $toDB);
233
-			$toMS->migrate($currentMigration);
234
-		}
235
-
236
-		$schemaManager = new \OC\DB\MDB2SchemaManager($toDB);
237
-		$apps = $input->getOption('all-apps') ? \OC_App::getAllApps() : \OC_App::getEnabledApps();
238
-		foreach($apps as $app) {
239
-			if (file_exists(\OC_App::getAppPath($app).'/appinfo/database.xml')) {
240
-				$schemaManager->createDbFromStructure(\OC_App::getAppPath($app).'/appinfo/database.xml');
241
-			} else {
242
-				// Make sure autoloading works...
243
-				\OC_App::loadApp($app);
244
-				$fromMS = new MigrationService($app, $fromDB);
245
-				$currentMigration = $fromMS->getMigration('current');
246
-				if ($currentMigration !== '0') {
247
-					$toMS = new MigrationService($app, $toDB);
248
-					$toMS->migrate($currentMigration, true);
249
-				}
250
-			}
251
-		}
252
-	}
253
-
254
-	protected function getToDBConnection(InputInterface $input, OutputInterface $output) {
255
-		$type = $input->getArgument('type');
256
-		$connectionParams = $this->connectionFactory->createConnectionParams();
257
-		$connectionParams = array_merge($connectionParams, [
258
-			'host' => $input->getArgument('hostname'),
259
-			'user' => $input->getArgument('username'),
260
-			'password' => $input->getOption('password'),
261
-			'dbname' => $input->getArgument('database'),
262
-		]);
263
-		if ($input->getOption('port')) {
264
-			$connectionParams['port'] = $input->getOption('port');
265
-		}
266
-		return $this->connectionFactory->getConnection($type, $connectionParams);
267
-	}
268
-
269
-	protected function clearSchema(Connection $db, InputInterface $input, OutputInterface $output) {
270
-		$toTables = $this->getTables($db);
271
-		if (!empty($toTables)) {
272
-			$output->writeln('<info>Clearing schema in new database</info>');
273
-		}
274
-		foreach($toTables as $table) {
275
-			$db->getSchemaManager()->dropTable($table);
276
-		}
277
-	}
278
-
279
-	protected function getTables(Connection $db) {
280
-		$filterExpression = '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
281
-		$db->getConfiguration()->
282
-			setFilterSchemaAssetsExpression($filterExpression);
283
-		return $db->getSchemaManager()->listTableNames();
284
-	}
285
-
286
-	/**
287
-	 * @param Connection $fromDB
288
-	 * @param Connection $toDB
289
-	 * @param Table $table
290
-	 * @param InputInterface $input
291
-	 * @param OutputInterface $output
292
-	 * @suppress SqlInjectionChecker
293
-	 */
294
-	protected function copyTable(Connection $fromDB, Connection $toDB, Table $table, InputInterface $input, OutputInterface $output) {
295
-		if ($table->getName() === $toDB->getPrefix() . 'migrations') {
296
-			$output->writeln('<comment>Skipping migrations table because it was already filled by running the migrations</comment>');
297
-			return;
298
-		}
299
-
300
-		$chunkSize = $input->getOption('chunk-size');
301
-
302
-		$query = $fromDB->getQueryBuilder();
303
-		$query->automaticTablePrefix(false);
304
-		$query->select($query->func()->count('*', 'num_entries'))
305
-			->from($table->getName());
306
-		$result = $query->execute();
307
-		$count = $result->fetchColumn();
308
-		$result->closeCursor();
309
-
310
-		$numChunks = ceil($count/$chunkSize);
311
-		if ($numChunks > 1) {
312
-			$output->writeln('chunked query, ' . $numChunks . ' chunks');
313
-		}
314
-
315
-		$progress = new ProgressBar($output, $count);
316
-		$progress->start();
317
-		$redraw = $count > $chunkSize ? 100 : ($count > 100 ? 5 : 1);
318
-		$progress->setRedrawFrequency($redraw);
319
-
320
-		$query = $fromDB->getQueryBuilder();
321
-		$query->automaticTablePrefix(false);
322
-		$query->select('*')
323
-			->from($table->getName())
324
-			->setMaxResults($chunkSize);
325
-
326
-		try {
327
-			$orderColumns = $table->getPrimaryKeyColumns();
328
-		} catch (DBALException $e) {
329
-			$orderColumns = [];
330
-			foreach ($table->getColumns() as $column) {
331
-				$orderColumns[] = $column->getName();
332
-			}
333
-		}
334
-
335
-		foreach ($orderColumns as $column) {
336
-			$query->addOrderBy($column);
337
-		}
338
-
339
-		$insertQuery = $toDB->getQueryBuilder();
340
-		$insertQuery->automaticTablePrefix(false);
341
-		$insertQuery->insert($table->getName());
342
-		$parametersCreated = false;
343
-
344
-		for ($chunk = 0; $chunk < $numChunks; $chunk++) {
345
-			$query->setFirstResult($chunk * $chunkSize);
346
-
347
-			$result = $query->execute();
348
-
349
-			while ($row = $result->fetch()) {
350
-				$progress->advance();
351
-				if (!$parametersCreated) {
352
-					foreach ($row as $key => $value) {
353
-						$insertQuery->setValue($key, $insertQuery->createParameter($key));
354
-					}
355
-					$parametersCreated = true;
356
-				}
357
-
358
-				foreach ($row as $key => $value) {
359
-					$type = $this->getColumnType($table, $key);
360
-					if ($type !== false) {
361
-						$insertQuery->setParameter($key, $value, $type);
362
-					} else {
363
-						$insertQuery->setParameter($key, $value);
364
-					}
365
-				}
366
-				$insertQuery->execute();
367
-			}
368
-			$result->closeCursor();
369
-		}
370
-		$progress->finish();
371
-	}
372
-
373
-	protected function getColumnType(Table $table, $columnName) {
374
-		$tableName = $table->getName();
375
-		if (isset($this->columnTypes[$tableName][$columnName])) {
376
-			return $this->columnTypes[$tableName][$columnName];
377
-		}
378
-
379
-		$type = $table->getColumn($columnName)->getType()->getName();
380
-
381
-		switch ($type) {
382
-			case Type::BLOB:
383
-			case Type::TEXT:
384
-				$this->columnTypes[$tableName][$columnName] = IQueryBuilder::PARAM_LOB;
385
-				break;
386
-			default:
387
-				$this->columnTypes[$tableName][$columnName] = false;
388
-		}
389
-
390
-		return $this->columnTypes[$tableName][$columnName];
391
-	}
392
-
393
-	protected function convertDB(Connection $fromDB, Connection $toDB, array $tables, InputInterface $input, OutputInterface $output) {
394
-		$this->config->setSystemValue('maintenance', true);
395
-		$schema = $fromDB->createSchema();
396
-
397
-		try {
398
-			// copy table rows
399
-			foreach($tables as $table) {
400
-				$output->writeln($table);
401
-				$this->copyTable($fromDB, $toDB, $schema->getTable($table), $input, $output);
402
-			}
403
-			if ($input->getArgument('type') === 'pgsql') {
404
-				$tools = new \OC\DB\PgSqlTools($this->config);
405
-				$tools->resynchronizeDatabaseSequences($toDB);
406
-			}
407
-			// save new database config
408
-			$this->saveDBInfo($input);
409
-		} catch(\Exception $e) {
410
-			$this->config->setSystemValue('maintenance', false);
411
-			throw $e;
412
-		}
413
-		$this->config->setSystemValue('maintenance', false);
414
-	}
415
-
416
-	protected function saveDBInfo(InputInterface $input) {
417
-		$type = $input->getArgument('type');
418
-		$username = $input->getArgument('username');
419
-		$dbHost = $input->getArgument('hostname');
420
-		$dbName = $input->getArgument('database');
421
-		$password = $input->getOption('password');
422
-		if ($input->getOption('port')) {
423
-			$dbHost .= ':'.$input->getOption('port');
424
-		}
425
-
426
-		$this->config->setSystemValues([
427
-			'dbtype'		=> $type,
428
-			'dbname'		=> $dbName,
429
-			'dbhost'		=> $dbHost,
430
-			'dbuser'		=> $username,
431
-			'dbpassword'	=> $password,
432
-		]);
433
-	}
434
-
435
-	/**
436
-	 * Return possible values for the named option
437
-	 *
438
-	 * @param string $optionName
439
-	 * @param CompletionContext $context
440
-	 * @return string[]
441
-	 */
442
-	public function completeOptionValues($optionName, CompletionContext $context) {
443
-		return [];
444
-	}
445
-
446
-	/**
447
-	 * Return possible values for the named argument
448
-	 *
449
-	 * @param string $argumentName
450
-	 * @param CompletionContext $context
451
-	 * @return string[]
452
-	 */
453
-	public function completeArgumentValues($argumentName, CompletionContext $context) {
454
-		if ($argumentName === 'type') {
455
-			return ['mysql', 'oci', 'pgsql'];
456
-		}
457
-		return [];
458
-	}
54
+    /**
55
+     * @var \OCP\IConfig
56
+     */
57
+    protected $config;
58
+
59
+    /**
60
+     * @var \OC\DB\ConnectionFactory
61
+     */
62
+    protected $connectionFactory;
63
+
64
+    /** @var array */
65
+    protected $columnTypes;
66
+
67
+    /**
68
+     * @param \OCP\IConfig $config
69
+     * @param \OC\DB\ConnectionFactory $connectionFactory
70
+     */
71
+    public function __construct(IConfig $config, ConnectionFactory $connectionFactory) {
72
+        $this->config = $config;
73
+        $this->connectionFactory = $connectionFactory;
74
+        parent::__construct();
75
+    }
76
+
77
+    protected function configure() {
78
+        $this
79
+            ->setName('db:convert-type')
80
+            ->setDescription('Convert the Nextcloud database to the newly configured one')
81
+            ->addArgument(
82
+                'type',
83
+                InputArgument::REQUIRED,
84
+                'the type of the database to convert to'
85
+            )
86
+            ->addArgument(
87
+                'username',
88
+                InputArgument::REQUIRED,
89
+                'the username of the database to convert to'
90
+            )
91
+            ->addArgument(
92
+                'hostname',
93
+                InputArgument::REQUIRED,
94
+                'the hostname of the database to convert to'
95
+            )
96
+            ->addArgument(
97
+                'database',
98
+                InputArgument::REQUIRED,
99
+                'the name of the database to convert to'
100
+            )
101
+            ->addOption(
102
+                'port',
103
+                null,
104
+                InputOption::VALUE_REQUIRED,
105
+                'the port of the database to convert to'
106
+            )
107
+            ->addOption(
108
+                'password',
109
+                null,
110
+                InputOption::VALUE_REQUIRED,
111
+                'the password of the database to convert to. Will be asked when not specified. Can also be passed via stdin.'
112
+            )
113
+            ->addOption(
114
+                'clear-schema',
115
+                null,
116
+                InputOption::VALUE_NONE,
117
+                'remove all tables from the destination database'
118
+            )
119
+            ->addOption(
120
+                'all-apps',
121
+                null,
122
+                InputOption::VALUE_NONE,
123
+                'whether to create schema for all apps instead of only installed apps'
124
+            )
125
+            ->addOption(
126
+                'chunk-size',
127
+                null,
128
+                InputOption::VALUE_REQUIRED,
129
+                'the maximum number of database rows to handle in a single query, bigger tables will be handled in chunks of this size. Lower this if the process runs out of memory during conversion.',
130
+                1000
131
+            )
132
+        ;
133
+    }
134
+
135
+    protected function validateInput(InputInterface $input, OutputInterface $output) {
136
+        $type = $this->connectionFactory->normalizeType($input->getArgument('type'));
137
+        if ($type === 'sqlite3') {
138
+            throw new \InvalidArgumentException(
139
+                'Converting to SQLite (sqlite3) is currently not supported.'
140
+            );
141
+        }
142
+        if ($type === $this->config->getSystemValue('dbtype', '')) {
143
+            throw new \InvalidArgumentException(sprintf(
144
+                'Can not convert from %1$s to %1$s.',
145
+                $type
146
+            ));
147
+        }
148
+        if ($type === 'oci' && $input->getOption('clear-schema')) {
149
+            // Doctrine unconditionally tries (at least in version 2.3)
150
+            // to drop sequence triggers when dropping a table, even though
151
+            // such triggers may not exist. This results in errors like
152
+            // "ORA-04080: trigger 'OC_STORAGES_AI_PK' does not exist".
153
+            throw new \InvalidArgumentException(
154
+                'The --clear-schema option is not supported when converting to Oracle (oci).'
155
+            );
156
+        }
157
+    }
158
+
159
+    protected function readPassword(InputInterface $input, OutputInterface $output) {
160
+        // Explicitly specified password
161
+        if ($input->getOption('password')) {
162
+            return;
163
+        }
164
+
165
+        // Read from stdin. stream_set_blocking is used to prevent blocking
166
+        // when nothing is passed via stdin.
167
+        stream_set_blocking(STDIN, 0);
168
+        $password = file_get_contents('php://stdin');
169
+        stream_set_blocking(STDIN, 1);
170
+        if (trim($password) !== '') {
171
+            $input->setOption('password', $password);
172
+            return;
173
+        }
174
+
175
+        // Read password by interacting
176
+        if ($input->isInteractive()) {
177
+            /** @var QuestionHelper $helper */
178
+            $helper = $this->getHelper('question');
179
+            $question = new Question('What is the database password?');
180
+            $question->setHidden(true);
181
+            $question->setHiddenFallback(false);
182
+            $password = $helper->ask($input, $output, $question);
183
+            $input->setOption('password', $password);
184
+            return;
185
+        }
186
+    }
187
+
188
+    protected function execute(InputInterface $input, OutputInterface $output) {
189
+        $this->validateInput($input, $output);
190
+        $this->readPassword($input, $output);
191
+
192
+        $fromDB = \OC::$server->getDatabaseConnection();
193
+        $toDB = $this->getToDBConnection($input, $output);
194
+
195
+        if ($input->getOption('clear-schema')) {
196
+            $this->clearSchema($toDB, $input, $output);
197
+        }
198
+
199
+        $this->createSchema($fromDB, $toDB, $input, $output);
200
+
201
+        $toTables = $this->getTables($toDB);
202
+        $fromTables = $this->getTables($fromDB);
203
+
204
+        // warn/fail if there are more tables in 'from' database
205
+        $extraFromTables = array_diff($fromTables, $toTables);
206
+        if (!empty($extraFromTables)) {
207
+            $output->writeln('<comment>The following tables will not be converted:</comment>');
208
+            $output->writeln($extraFromTables);
209
+            if (!$input->getOption('all-apps')) {
210
+                $output->writeln('<comment>Please note that tables belonging to available but currently not installed apps</comment>');
211
+                $output->writeln('<comment>can be included by specifying the --all-apps option.</comment>');
212
+            }
213
+
214
+            /** @var QuestionHelper $helper */
215
+            $helper = $this->getHelper('question');
216
+            $question = new ConfirmationQuestion('Continue with the conversion (y/n)? [n] ', false);
217
+
218
+            if (!$helper->ask($input, $output, $question)) {
219
+                return;
220
+            }
221
+        }
222
+        $intersectingTables = array_intersect($toTables, $fromTables);
223
+        $this->convertDB($fromDB, $toDB, $intersectingTables, $input, $output);
224
+    }
225
+
226
+    protected function createSchema(Connection $fromDB, Connection $toDB, InputInterface $input, OutputInterface $output) {
227
+        $output->writeln('<info>Creating schema in new database</info>');
228
+
229
+        $fromMS = new MigrationService('core', $fromDB);
230
+        $currentMigration = $fromMS->getMigration('current');
231
+        if ($currentMigration !== '0') {
232
+            $toMS = new MigrationService('core', $toDB);
233
+            $toMS->migrate($currentMigration);
234
+        }
235
+
236
+        $schemaManager = new \OC\DB\MDB2SchemaManager($toDB);
237
+        $apps = $input->getOption('all-apps') ? \OC_App::getAllApps() : \OC_App::getEnabledApps();
238
+        foreach($apps as $app) {
239
+            if (file_exists(\OC_App::getAppPath($app).'/appinfo/database.xml')) {
240
+                $schemaManager->createDbFromStructure(\OC_App::getAppPath($app).'/appinfo/database.xml');
241
+            } else {
242
+                // Make sure autoloading works...
243
+                \OC_App::loadApp($app);
244
+                $fromMS = new MigrationService($app, $fromDB);
245
+                $currentMigration = $fromMS->getMigration('current');
246
+                if ($currentMigration !== '0') {
247
+                    $toMS = new MigrationService($app, $toDB);
248
+                    $toMS->migrate($currentMigration, true);
249
+                }
250
+            }
251
+        }
252
+    }
253
+
254
+    protected function getToDBConnection(InputInterface $input, OutputInterface $output) {
255
+        $type = $input->getArgument('type');
256
+        $connectionParams = $this->connectionFactory->createConnectionParams();
257
+        $connectionParams = array_merge($connectionParams, [
258
+            'host' => $input->getArgument('hostname'),
259
+            'user' => $input->getArgument('username'),
260
+            'password' => $input->getOption('password'),
261
+            'dbname' => $input->getArgument('database'),
262
+        ]);
263
+        if ($input->getOption('port')) {
264
+            $connectionParams['port'] = $input->getOption('port');
265
+        }
266
+        return $this->connectionFactory->getConnection($type, $connectionParams);
267
+    }
268
+
269
+    protected function clearSchema(Connection $db, InputInterface $input, OutputInterface $output) {
270
+        $toTables = $this->getTables($db);
271
+        if (!empty($toTables)) {
272
+            $output->writeln('<info>Clearing schema in new database</info>');
273
+        }
274
+        foreach($toTables as $table) {
275
+            $db->getSchemaManager()->dropTable($table);
276
+        }
277
+    }
278
+
279
+    protected function getTables(Connection $db) {
280
+        $filterExpression = '/^' . preg_quote($this->config->getSystemValue('dbtableprefix', 'oc_')) . '/';
281
+        $db->getConfiguration()->
282
+            setFilterSchemaAssetsExpression($filterExpression);
283
+        return $db->getSchemaManager()->listTableNames();
284
+    }
285
+
286
+    /**
287
+     * @param Connection $fromDB
288
+     * @param Connection $toDB
289
+     * @param Table $table
290
+     * @param InputInterface $input
291
+     * @param OutputInterface $output
292
+     * @suppress SqlInjectionChecker
293
+     */
294
+    protected function copyTable(Connection $fromDB, Connection $toDB, Table $table, InputInterface $input, OutputInterface $output) {
295
+        if ($table->getName() === $toDB->getPrefix() . 'migrations') {
296
+            $output->writeln('<comment>Skipping migrations table because it was already filled by running the migrations</comment>');
297
+            return;
298
+        }
299
+
300
+        $chunkSize = $input->getOption('chunk-size');
301
+
302
+        $query = $fromDB->getQueryBuilder();
303
+        $query->automaticTablePrefix(false);
304
+        $query->select($query->func()->count('*', 'num_entries'))
305
+            ->from($table->getName());
306
+        $result = $query->execute();
307
+        $count = $result->fetchColumn();
308
+        $result->closeCursor();
309
+
310
+        $numChunks = ceil($count/$chunkSize);
311
+        if ($numChunks > 1) {
312
+            $output->writeln('chunked query, ' . $numChunks . ' chunks');
313
+        }
314
+
315
+        $progress = new ProgressBar($output, $count);
316
+        $progress->start();
317
+        $redraw = $count > $chunkSize ? 100 : ($count > 100 ? 5 : 1);
318
+        $progress->setRedrawFrequency($redraw);
319
+
320
+        $query = $fromDB->getQueryBuilder();
321
+        $query->automaticTablePrefix(false);
322
+        $query->select('*')
323
+            ->from($table->getName())
324
+            ->setMaxResults($chunkSize);
325
+
326
+        try {
327
+            $orderColumns = $table->getPrimaryKeyColumns();
328
+        } catch (DBALException $e) {
329
+            $orderColumns = [];
330
+            foreach ($table->getColumns() as $column) {
331
+                $orderColumns[] = $column->getName();
332
+            }
333
+        }
334
+
335
+        foreach ($orderColumns as $column) {
336
+            $query->addOrderBy($column);
337
+        }
338
+
339
+        $insertQuery = $toDB->getQueryBuilder();
340
+        $insertQuery->automaticTablePrefix(false);
341
+        $insertQuery->insert($table->getName());
342
+        $parametersCreated = false;
343
+
344
+        for ($chunk = 0; $chunk < $numChunks; $chunk++) {
345
+            $query->setFirstResult($chunk * $chunkSize);
346
+
347
+            $result = $query->execute();
348
+
349
+            while ($row = $result->fetch()) {
350
+                $progress->advance();
351
+                if (!$parametersCreated) {
352
+                    foreach ($row as $key => $value) {
353
+                        $insertQuery->setValue($key, $insertQuery->createParameter($key));
354
+                    }
355
+                    $parametersCreated = true;
356
+                }
357
+
358
+                foreach ($row as $key => $value) {
359
+                    $type = $this->getColumnType($table, $key);
360
+                    if ($type !== false) {
361
+                        $insertQuery->setParameter($key, $value, $type);
362
+                    } else {
363
+                        $insertQuery->setParameter($key, $value);
364
+                    }
365
+                }
366
+                $insertQuery->execute();
367
+            }
368
+            $result->closeCursor();
369
+        }
370
+        $progress->finish();
371
+    }
372
+
373
+    protected function getColumnType(Table $table, $columnName) {
374
+        $tableName = $table->getName();
375
+        if (isset($this->columnTypes[$tableName][$columnName])) {
376
+            return $this->columnTypes[$tableName][$columnName];
377
+        }
378
+
379
+        $type = $table->getColumn($columnName)->getType()->getName();
380
+
381
+        switch ($type) {
382
+            case Type::BLOB:
383
+            case Type::TEXT:
384
+                $this->columnTypes[$tableName][$columnName] = IQueryBuilder::PARAM_LOB;
385
+                break;
386
+            default:
387
+                $this->columnTypes[$tableName][$columnName] = false;
388
+        }
389
+
390
+        return $this->columnTypes[$tableName][$columnName];
391
+    }
392
+
393
+    protected function convertDB(Connection $fromDB, Connection $toDB, array $tables, InputInterface $input, OutputInterface $output) {
394
+        $this->config->setSystemValue('maintenance', true);
395
+        $schema = $fromDB->createSchema();
396
+
397
+        try {
398
+            // copy table rows
399
+            foreach($tables as $table) {
400
+                $output->writeln($table);
401
+                $this->copyTable($fromDB, $toDB, $schema->getTable($table), $input, $output);
402
+            }
403
+            if ($input->getArgument('type') === 'pgsql') {
404
+                $tools = new \OC\DB\PgSqlTools($this->config);
405
+                $tools->resynchronizeDatabaseSequences($toDB);
406
+            }
407
+            // save new database config
408
+            $this->saveDBInfo($input);
409
+        } catch(\Exception $e) {
410
+            $this->config->setSystemValue('maintenance', false);
411
+            throw $e;
412
+        }
413
+        $this->config->setSystemValue('maintenance', false);
414
+    }
415
+
416
+    protected function saveDBInfo(InputInterface $input) {
417
+        $type = $input->getArgument('type');
418
+        $username = $input->getArgument('username');
419
+        $dbHost = $input->getArgument('hostname');
420
+        $dbName = $input->getArgument('database');
421
+        $password = $input->getOption('password');
422
+        if ($input->getOption('port')) {
423
+            $dbHost .= ':'.$input->getOption('port');
424
+        }
425
+
426
+        $this->config->setSystemValues([
427
+            'dbtype'		=> $type,
428
+            'dbname'		=> $dbName,
429
+            'dbhost'		=> $dbHost,
430
+            'dbuser'		=> $username,
431
+            'dbpassword'	=> $password,
432
+        ]);
433
+    }
434
+
435
+    /**
436
+     * Return possible values for the named option
437
+     *
438
+     * @param string $optionName
439
+     * @param CompletionContext $context
440
+     * @return string[]
441
+     */
442
+    public function completeOptionValues($optionName, CompletionContext $context) {
443
+        return [];
444
+    }
445
+
446
+    /**
447
+     * Return possible values for the named argument
448
+     *
449
+     * @param string $argumentName
450
+     * @param CompletionContext $context
451
+     * @return string[]
452
+     */
453
+    public function completeArgumentValues($argumentName, CompletionContext $context) {
454
+        if ($argumentName === 'type') {
455
+            return ['mysql', 'oci', 'pgsql'];
456
+        }
457
+        return [];
458
+    }
459 459
 }
Please login to merge, or discard this patch.