Passed
Push — master ( b0fbcc...642f07 )
by Joas
14:16 queued 13s
created
lib/private/Comments/Manager.php 1 patch
Indentation   +1582 added lines, -1582 removed lines patch added patch discarded remove patch
@@ -47,1586 +47,1586 @@
 block discarded – undo
47 47
 
48 48
 class Manager implements ICommentsManager {
49 49
 
50
-	/** @var  IDBConnection */
51
-	protected $dbConn;
52
-
53
-	/** @var  LoggerInterface */
54
-	protected $logger;
55
-
56
-	/** @var IConfig */
57
-	protected $config;
58
-
59
-	/** @var ITimeFactory */
60
-	protected $timeFactory;
61
-
62
-	/** @var IInitialStateService */
63
-	protected $initialStateService;
64
-
65
-	/** @var IComment[] */
66
-	protected $commentsCache = [];
67
-
68
-	/** @var  \Closure[] */
69
-	protected $eventHandlerClosures = [];
70
-
71
-	/** @var  ICommentsEventHandler[] */
72
-	protected $eventHandlers = [];
73
-
74
-	/** @var \Closure[] */
75
-	protected $displayNameResolvers = [];
76
-
77
-	public function __construct(IDBConnection $dbConn,
78
-								LoggerInterface $logger,
79
-								IConfig $config,
80
-								ITimeFactory $timeFactory,
81
-								IInitialStateService $initialStateService) {
82
-		$this->dbConn = $dbConn;
83
-		$this->logger = $logger;
84
-		$this->config = $config;
85
-		$this->timeFactory = $timeFactory;
86
-		$this->initialStateService = $initialStateService;
87
-	}
88
-
89
-	/**
90
-	 * converts data base data into PHP native, proper types as defined by
91
-	 * IComment interface.
92
-	 *
93
-	 * @param array $data
94
-	 * @return array
95
-	 */
96
-	protected function normalizeDatabaseData(array $data) {
97
-		$data['id'] = (string)$data['id'];
98
-		$data['parent_id'] = (string)$data['parent_id'];
99
-		$data['topmost_parent_id'] = (string)$data['topmost_parent_id'];
100
-		$data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
101
-		if (!is_null($data['latest_child_timestamp'])) {
102
-			$data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
103
-		}
104
-		$data['children_count'] = (int)$data['children_count'];
105
-		$data['reference_id'] = $data['reference_id'] ?? null;
106
-		if ($this->supportReactions()) {
107
-			$list = json_decode($data['reactions'], true);
108
-			// Ordering does not work on the database with group concat and Oracle,
109
-			// So we simply sort on the output.
110
-			if (is_array($list)) {
111
-				uasort($list, static function ($a, $b) {
112
-					if ($a === $b) {
113
-						return 0;
114
-					}
115
-					return ($a > $b) ? -1 : 1;
116
-				});
117
-			}
118
-			$data['reactions'] = $list;
119
-		}
120
-		return $data;
121
-	}
122
-
123
-
124
-	/**
125
-	 * @param array $data
126
-	 * @return IComment
127
-	 */
128
-	public function getCommentFromData(array $data): IComment {
129
-		return new Comment($this->normalizeDatabaseData($data));
130
-	}
131
-
132
-	/**
133
-	 * prepares a comment for an insert or update operation after making sure
134
-	 * all necessary fields have a value assigned.
135
-	 *
136
-	 * @param IComment $comment
137
-	 * @return IComment returns the same updated IComment instance as provided
138
-	 *                  by parameter for convenience
139
-	 * @throws \UnexpectedValueException
140
-	 */
141
-	protected function prepareCommentForDatabaseWrite(IComment $comment) {
142
-		if (!$comment->getActorType()
143
-			|| $comment->getActorId() === ''
144
-			|| !$comment->getObjectType()
145
-			|| $comment->getObjectId() === ''
146
-			|| !$comment->getVerb()
147
-		) {
148
-			throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
149
-		}
150
-
151
-		if ($comment->getVerb() === 'reaction' && mb_strlen($comment->getMessage()) > 2) {
152
-			throw new \UnexpectedValueException('Reactions cannot be longer than 2 chars (emoji with skin tone have two chars)');
153
-		}
154
-
155
-		if ($comment->getId() === '') {
156
-			$comment->setChildrenCount(0);
157
-			$comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
158
-			$comment->setLatestChildDateTime(null);
159
-		}
160
-
161
-		if (is_null($comment->getCreationDateTime())) {
162
-			$comment->setCreationDateTime(new \DateTime());
163
-		}
164
-
165
-		if ($comment->getParentId() !== '0') {
166
-			$comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
167
-		} else {
168
-			$comment->setTopmostParentId('0');
169
-		}
170
-
171
-		$this->cache($comment);
172
-
173
-		return $comment;
174
-	}
175
-
176
-	/**
177
-	 * returns the topmost parent id of a given comment identified by ID
178
-	 *
179
-	 * @param string $id
180
-	 * @return string
181
-	 * @throws NotFoundException
182
-	 */
183
-	protected function determineTopmostParentId($id) {
184
-		$comment = $this->get($id);
185
-		if ($comment->getParentId() === '0') {
186
-			return $comment->getId();
187
-		}
188
-
189
-		return $this->determineTopmostParentId($comment->getParentId());
190
-	}
191
-
192
-	/**
193
-	 * updates child information of a comment
194
-	 *
195
-	 * @param string $id
196
-	 * @param \DateTime $cDateTime the date time of the most recent child
197
-	 * @throws NotFoundException
198
-	 */
199
-	protected function updateChildrenInformation($id, \DateTime $cDateTime) {
200
-		$qb = $this->dbConn->getQueryBuilder();
201
-		$query = $qb->select($qb->func()->count('id'))
202
-			->from('comments')
203
-			->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
204
-			->setParameter('id', $id);
205
-
206
-		$resultStatement = $query->execute();
207
-		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
208
-		$resultStatement->closeCursor();
209
-		$children = (int)$data[0];
210
-
211
-		$comment = $this->get($id);
212
-		$comment->setChildrenCount($children);
213
-		$comment->setLatestChildDateTime($cDateTime);
214
-		$this->save($comment);
215
-	}
216
-
217
-	/**
218
-	 * Tests whether actor or object type and id parameters are acceptable.
219
-	 * Throws exception if not.
220
-	 *
221
-	 * @param string $role
222
-	 * @param string $type
223
-	 * @param string $id
224
-	 * @throws \InvalidArgumentException
225
-	 */
226
-	protected function checkRoleParameters($role, $type, $id) {
227
-		if (
228
-			!is_string($type) || empty($type)
229
-			|| !is_string($id) || empty($id)
230
-		) {
231
-			throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
232
-		}
233
-	}
234
-
235
-	/**
236
-	 * run-time caches a comment
237
-	 *
238
-	 * @param IComment $comment
239
-	 */
240
-	protected function cache(IComment $comment) {
241
-		$id = $comment->getId();
242
-		if (empty($id)) {
243
-			return;
244
-		}
245
-		$this->commentsCache[(string)$id] = $comment;
246
-	}
247
-
248
-	/**
249
-	 * removes an entry from the comments run time cache
250
-	 *
251
-	 * @param mixed $id the comment's id
252
-	 */
253
-	protected function uncache($id) {
254
-		$id = (string)$id;
255
-		if (isset($this->commentsCache[$id])) {
256
-			unset($this->commentsCache[$id]);
257
-		}
258
-	}
259
-
260
-	/**
261
-	 * returns a comment instance
262
-	 *
263
-	 * @param string $id the ID of the comment
264
-	 * @return IComment
265
-	 * @throws NotFoundException
266
-	 * @throws \InvalidArgumentException
267
-	 * @since 9.0.0
268
-	 */
269
-	public function get($id) {
270
-		if ((int)$id === 0) {
271
-			throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
272
-		}
273
-
274
-		if (isset($this->commentsCache[$id])) {
275
-			return $this->commentsCache[$id];
276
-		}
277
-
278
-		$qb = $this->dbConn->getQueryBuilder();
279
-		$resultStatement = $qb->select('*')
280
-			->from('comments')
281
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
282
-			->setParameter('id', $id, IQueryBuilder::PARAM_INT)
283
-			->execute();
284
-
285
-		$data = $resultStatement->fetch();
286
-		$resultStatement->closeCursor();
287
-		if (!$data) {
288
-			throw new NotFoundException();
289
-		}
290
-
291
-
292
-		$comment = $this->getCommentFromData($data);
293
-		$this->cache($comment);
294
-		return $comment;
295
-	}
296
-
297
-	/**
298
-	 * returns the comment specified by the id and all it's child comments.
299
-	 * At this point of time, we do only support one level depth.
300
-	 *
301
-	 * @param string $id
302
-	 * @param int $limit max number of entries to return, 0 returns all
303
-	 * @param int $offset the start entry
304
-	 * @return array
305
-	 * @since 9.0.0
306
-	 *
307
-	 * The return array looks like this
308
-	 * [
309
-	 *   'comment' => IComment, // root comment
310
-	 *   'replies' =>
311
-	 *   [
312
-	 *     0 =>
313
-	 *     [
314
-	 *       'comment' => IComment,
315
-	 *       'replies' => []
316
-	 *     ]
317
-	 *     1 =>
318
-	 *     [
319
-	 *       'comment' => IComment,
320
-	 *       'replies'=> []
321
-	 *     ],
322
-	 *     …
323
-	 *   ]
324
-	 * ]
325
-	 */
326
-	public function getTree($id, $limit = 0, $offset = 0) {
327
-		$tree = [];
328
-		$tree['comment'] = $this->get($id);
329
-		$tree['replies'] = [];
330
-
331
-		$qb = $this->dbConn->getQueryBuilder();
332
-		$query = $qb->select('*')
333
-			->from('comments')
334
-			->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
335
-			->orderBy('creation_timestamp', 'DESC')
336
-			->setParameter('id', $id);
337
-
338
-		if ($limit > 0) {
339
-			$query->setMaxResults($limit);
340
-		}
341
-		if ($offset > 0) {
342
-			$query->setFirstResult($offset);
343
-		}
344
-
345
-		$resultStatement = $query->execute();
346
-		while ($data = $resultStatement->fetch()) {
347
-			$comment = $this->getCommentFromData($data);
348
-			$this->cache($comment);
349
-			$tree['replies'][] = [
350
-				'comment' => $comment,
351
-				'replies' => []
352
-			];
353
-		}
354
-		$resultStatement->closeCursor();
355
-
356
-		return $tree;
357
-	}
358
-
359
-	/**
360
-	 * returns comments for a specific object (e.g. a file).
361
-	 *
362
-	 * The sort order is always newest to oldest.
363
-	 *
364
-	 * @param string $objectType the object type, e.g. 'files'
365
-	 * @param string $objectId the id of the object
366
-	 * @param int $limit optional, number of maximum comments to be returned. if
367
-	 * not specified, all comments are returned.
368
-	 * @param int $offset optional, starting point
369
-	 * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
370
-	 * that may be returned
371
-	 * @return IComment[]
372
-	 * @since 9.0.0
373
-	 */
374
-	public function getForObject(
375
-		$objectType,
376
-		$objectId,
377
-		$limit = 0,
378
-		$offset = 0,
379
-		\DateTime $notOlderThan = null
380
-	) {
381
-		$comments = [];
382
-
383
-		$qb = $this->dbConn->getQueryBuilder();
384
-		$query = $qb->select('*')
385
-			->from('comments')
386
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
387
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
388
-			->orderBy('creation_timestamp', 'DESC')
389
-			->setParameter('type', $objectType)
390
-			->setParameter('id', $objectId);
391
-
392
-		if ($limit > 0) {
393
-			$query->setMaxResults($limit);
394
-		}
395
-		if ($offset > 0) {
396
-			$query->setFirstResult($offset);
397
-		}
398
-		if (!is_null($notOlderThan)) {
399
-			$query
400
-				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
401
-				->setParameter('notOlderThan', $notOlderThan, 'datetime');
402
-		}
403
-
404
-		$resultStatement = $query->execute();
405
-		while ($data = $resultStatement->fetch()) {
406
-			$comment = $this->getCommentFromData($data);
407
-			$this->cache($comment);
408
-			$comments[] = $comment;
409
-		}
410
-		$resultStatement->closeCursor();
411
-
412
-		return $comments;
413
-	}
414
-
415
-	/**
416
-	 * @param string $objectType the object type, e.g. 'files'
417
-	 * @param string $objectId the id of the object
418
-	 * @param int $lastKnownCommentId the last known comment (will be used as offset)
419
-	 * @param string $sortDirection direction of the comments (`asc` or `desc`)
420
-	 * @param int $limit optional, number of maximum comments to be returned. if
421
-	 * set to 0, all comments are returned.
422
-	 * @param bool $includeLastKnown
423
-	 * @return IComment[]
424
-	 * @return array
425
-	 */
426
-	public function getForObjectSince(
427
-		string $objectType,
428
-		string $objectId,
429
-		int $lastKnownCommentId,
430
-		string $sortDirection = 'asc',
431
-		int $limit = 30,
432
-		bool $includeLastKnown = false
433
-	): array {
434
-		return $this->getCommentsWithVerbForObjectSinceComment(
435
-			$objectType,
436
-			$objectId,
437
-			[],
438
-			$lastKnownCommentId,
439
-			$sortDirection,
440
-			$limit,
441
-			$includeLastKnown
442
-		);
443
-	}
444
-
445
-	/**
446
-	 * @param string $objectType the object type, e.g. 'files'
447
-	 * @param string $objectId the id of the object
448
-	 * @param string[] $verbs List of verbs to filter by
449
-	 * @param int $lastKnownCommentId the last known comment (will be used as offset)
450
-	 * @param string $sortDirection direction of the comments (`asc` or `desc`)
451
-	 * @param int $limit optional, number of maximum comments to be returned. if
452
-	 * set to 0, all comments are returned.
453
-	 * @param bool $includeLastKnown
454
-	 * @return IComment[]
455
-	 */
456
-	public function getCommentsWithVerbForObjectSinceComment(
457
-		string $objectType,
458
-		string $objectId,
459
-		array $verbs,
460
-		int $lastKnownCommentId,
461
-		string $sortDirection = 'asc',
462
-		int $limit = 30,
463
-		bool $includeLastKnown = false
464
-	): array {
465
-		$comments = [];
466
-
467
-		$query = $this->dbConn->getQueryBuilder();
468
-		$query->select('*')
469
-			->from('comments')
470
-			->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
471
-			->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
472
-			->orderBy('creation_timestamp', $sortDirection === 'desc' ? 'DESC' : 'ASC')
473
-			->addOrderBy('id', $sortDirection === 'desc' ? 'DESC' : 'ASC');
474
-
475
-		if ($limit > 0) {
476
-			$query->setMaxResults($limit);
477
-		}
478
-
479
-		if (!empty($verbs)) {
480
-			$query->andWhere($query->expr()->in('verb', $query->createNamedParameter($verbs, IQueryBuilder::PARAM_STR_ARRAY)));
481
-		}
482
-
483
-		$lastKnownComment = $lastKnownCommentId > 0 ? $this->getLastKnownComment(
484
-			$objectType,
485
-			$objectId,
486
-			$lastKnownCommentId
487
-		) : null;
488
-		if ($lastKnownComment instanceof IComment) {
489
-			$lastKnownCommentDateTime = $lastKnownComment->getCreationDateTime();
490
-			if ($sortDirection === 'desc') {
491
-				if ($includeLastKnown) {
492
-					$idComparison = $query->expr()->lte('id', $query->createNamedParameter($lastKnownCommentId));
493
-				} else {
494
-					$idComparison = $query->expr()->lt('id', $query->createNamedParameter($lastKnownCommentId));
495
-				}
496
-				$query->andWhere(
497
-					$query->expr()->orX(
498
-						$query->expr()->lt(
499
-							'creation_timestamp',
500
-							$query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
501
-							IQueryBuilder::PARAM_DATE
502
-						),
503
-						$query->expr()->andX(
504
-							$query->expr()->eq(
505
-								'creation_timestamp',
506
-								$query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
507
-								IQueryBuilder::PARAM_DATE
508
-							),
509
-							$idComparison
510
-						)
511
-					)
512
-				);
513
-			} else {
514
-				if ($includeLastKnown) {
515
-					$idComparison = $query->expr()->gte('id', $query->createNamedParameter($lastKnownCommentId));
516
-				} else {
517
-					$idComparison = $query->expr()->gt('id', $query->createNamedParameter($lastKnownCommentId));
518
-				}
519
-				$query->andWhere(
520
-					$query->expr()->orX(
521
-						$query->expr()->gt(
522
-							'creation_timestamp',
523
-							$query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
524
-							IQueryBuilder::PARAM_DATE
525
-						),
526
-						$query->expr()->andX(
527
-							$query->expr()->eq(
528
-								'creation_timestamp',
529
-								$query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
530
-								IQueryBuilder::PARAM_DATE
531
-							),
532
-							$idComparison
533
-						)
534
-					)
535
-				);
536
-			}
537
-		}
538
-
539
-		$resultStatement = $query->execute();
540
-		while ($data = $resultStatement->fetch()) {
541
-			$comment = $this->getCommentFromData($data);
542
-			$this->cache($comment);
543
-			$comments[] = $comment;
544
-		}
545
-		$resultStatement->closeCursor();
546
-
547
-		return $comments;
548
-	}
549
-
550
-	/**
551
-	 * @param string $objectType the object type, e.g. 'files'
552
-	 * @param string $objectId the id of the object
553
-	 * @param int $id the comment to look for
554
-	 * @return Comment|null
555
-	 */
556
-	protected function getLastKnownComment(string $objectType,
557
-										   string $objectId,
558
-										   int $id) {
559
-		$query = $this->dbConn->getQueryBuilder();
560
-		$query->select('*')
561
-			->from('comments')
562
-			->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
563
-			->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
564
-			->andWhere($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
565
-
566
-		$result = $query->execute();
567
-		$row = $result->fetch();
568
-		$result->closeCursor();
569
-
570
-		if ($row) {
571
-			$comment = $this->getCommentFromData($row);
572
-			$this->cache($comment);
573
-			return $comment;
574
-		}
575
-
576
-		return null;
577
-	}
578
-
579
-	/**
580
-	 * Search for comments with a given content
581
-	 *
582
-	 * @param string $search content to search for
583
-	 * @param string $objectType Limit the search by object type
584
-	 * @param string $objectId Limit the search by object id
585
-	 * @param string $verb Limit the verb of the comment
586
-	 * @param int $offset
587
-	 * @param int $limit
588
-	 * @return IComment[]
589
-	 */
590
-	public function search(string $search, string $objectType, string $objectId, string $verb, int $offset, int $limit = 50): array {
591
-		$objectIds = [];
592
-		if ($objectId) {
593
-			$objectIds[] = $objectIds;
594
-		}
595
-		return $this->searchForObjects($search, $objectType, $objectIds, $verb, $offset, $limit);
596
-	}
597
-
598
-	/**
599
-	 * Search for comments on one or more objects with a given content
600
-	 *
601
-	 * @param string $search content to search for
602
-	 * @param string $objectType Limit the search by object type
603
-	 * @param array $objectIds Limit the search by object ids
604
-	 * @param string $verb Limit the verb of the comment
605
-	 * @param int $offset
606
-	 * @param int $limit
607
-	 * @return IComment[]
608
-	 */
609
-	public function searchForObjects(string $search, string $objectType, array $objectIds, string $verb, int $offset, int $limit = 50): array {
610
-		$query = $this->dbConn->getQueryBuilder();
611
-
612
-		$query->select('*')
613
-			->from('comments')
614
-			->orderBy('creation_timestamp', 'DESC')
615
-			->addOrderBy('id', 'DESC')
616
-			->setMaxResults($limit);
617
-
618
-		if ($search !== '') {
619
-			$query->where($query->expr()->iLike('message', $query->createNamedParameter(
620
-				'%' . $this->dbConn->escapeLikeParameter($search). '%'
621
-			)));
622
-		}
623
-
624
-		if ($objectType !== '') {
625
-			$query->andWhere($query->expr()->eq('object_type', $query->createNamedParameter($objectType)));
626
-		}
627
-		if (!empty($objectIds)) {
628
-			$query->andWhere($query->expr()->in('object_id', $query->createNamedParameter($objectIds, IQueryBuilder::PARAM_STR_ARRAY)));
629
-		}
630
-		if ($verb !== '') {
631
-			$query->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)));
632
-		}
633
-		if ($offset !== 0) {
634
-			$query->setFirstResult($offset);
635
-		}
636
-
637
-		$comments = [];
638
-		$result = $query->execute();
639
-		while ($data = $result->fetch()) {
640
-			$comment = $this->getCommentFromData($data);
641
-			$this->cache($comment);
642
-			$comments[] = $comment;
643
-		}
644
-		$result->closeCursor();
645
-
646
-		return $comments;
647
-	}
648
-
649
-	/**
650
-	 * @param $objectType string the object type, e.g. 'files'
651
-	 * @param $objectId string the id of the object
652
-	 * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
653
-	 * that may be returned
654
-	 * @param string $verb Limit the verb of the comment - Added in 14.0.0
655
-	 * @return Int
656
-	 * @since 9.0.0
657
-	 */
658
-	public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null, $verb = '') {
659
-		$qb = $this->dbConn->getQueryBuilder();
660
-		$query = $qb->select($qb->func()->count('id'))
661
-			->from('comments')
662
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
663
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
664
-			->setParameter('type', $objectType)
665
-			->setParameter('id', $objectId);
666
-
667
-		if (!is_null($notOlderThan)) {
668
-			$query
669
-				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
670
-				->setParameter('notOlderThan', $notOlderThan, 'datetime');
671
-		}
672
-
673
-		if ($verb !== '') {
674
-			$query->andWhere($qb->expr()->eq('verb', $qb->createNamedParameter($verb)));
675
-		}
676
-
677
-		$resultStatement = $query->execute();
678
-		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
679
-		$resultStatement->closeCursor();
680
-		return (int)$data[0];
681
-	}
682
-
683
-	/**
684
-	 * @param string $objectType the object type, e.g. 'files'
685
-	 * @param string[] $objectIds the id of the object
686
-	 * @param IUser $user
687
-	 * @param string $verb Limit the verb of the comment - Added in 14.0.0
688
-	 * @return array Map with object id => # of unread comments
689
-	 * @psalm-return array<string, int>
690
-	 * @since 21.0.0
691
-	 */
692
-	public function getNumberOfUnreadCommentsForObjects(string $objectType, array $objectIds, IUser $user, $verb = ''): array {
693
-		$unreadComments = [];
694
-		$query = $this->dbConn->getQueryBuilder();
695
-		$query->select('c.object_id', $query->func()->count('c.id', 'num_comments'))
696
-			->from('comments', 'c')
697
-			->leftJoin('c', 'comments_read_markers', 'm', $query->expr()->andX(
698
-				$query->expr()->eq('m.user_id', $query->createNamedParameter($user->getUID())),
699
-				$query->expr()->eq('c.object_type', 'm.object_type'),
700
-				$query->expr()->eq('c.object_id', 'm.object_id')
701
-			))
702
-			->where($query->expr()->eq('c.object_type', $query->createNamedParameter($objectType)))
703
-			->andWhere($query->expr()->in('c.object_id', $query->createParameter('ids')))
704
-			->andWhere($query->expr()->orX(
705
-				$query->expr()->gt('c.creation_timestamp', 'm.marker_datetime'),
706
-				$query->expr()->isNull('m.marker_datetime')
707
-			))
708
-			->groupBy('c.object_id');
709
-
710
-		if ($verb !== '') {
711
-			$query->andWhere($query->expr()->eq('c.verb', $query->createNamedParameter($verb)));
712
-		}
713
-
714
-		$unreadComments = array_fill_keys($objectIds, 0);
715
-		foreach (array_chunk($objectIds, 1000) as $chunk) {
716
-			$query->setParameter('ids', $chunk, IQueryBuilder::PARAM_STR_ARRAY);
717
-
718
-			$result = $query->executeQuery();
719
-			while ($row = $result->fetch()) {
720
-				$unreadComments[$row['object_id']] = (int) $row['num_comments'];
721
-			}
722
-			$result->closeCursor();
723
-		}
724
-
725
-		return $unreadComments;
726
-	}
727
-
728
-	/**
729
-	 * @param string $objectType
730
-	 * @param string $objectId
731
-	 * @param int $lastRead
732
-	 * @param string $verb
733
-	 * @return int
734
-	 * @since 21.0.0
735
-	 */
736
-	public function getNumberOfCommentsForObjectSinceComment(string $objectType, string $objectId, int $lastRead, string $verb = ''): int {
737
-		if ($verb !== '') {
738
-			return $this->getNumberOfCommentsWithVerbsForObjectSinceComment($objectType, $objectId, $lastRead, [$verb]);
739
-		}
740
-
741
-		return $this->getNumberOfCommentsWithVerbsForObjectSinceComment($objectType, $objectId, $lastRead, []);
742
-	}
743
-
744
-	/**
745
-	 * @param string $objectType
746
-	 * @param string $objectId
747
-	 * @param int $lastRead
748
-	 * @param string[] $verbs
749
-	 * @return int
750
-	 * @since 24.0.0
751
-	 */
752
-	public function getNumberOfCommentsWithVerbsForObjectSinceComment(string $objectType, string $objectId, int $lastRead, array $verbs): int {
753
-		$query = $this->dbConn->getQueryBuilder();
754
-		$query->select($query->func()->count('id', 'num_messages'))
755
-			->from('comments')
756
-			->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
757
-			->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
758
-			->andWhere($query->expr()->gt('id', $query->createNamedParameter($lastRead)));
759
-
760
-		if (!empty($verbs)) {
761
-			$query->andWhere($query->expr()->in('verb', $query->createNamedParameter($verbs, IQueryBuilder::PARAM_STR_ARRAY)));
762
-		}
763
-
764
-		$result = $query->executeQuery();
765
-		$data = $result->fetch();
766
-		$result->closeCursor();
767
-
768
-		return (int) ($data['num_messages'] ?? 0);
769
-	}
770
-
771
-	/**
772
-	 * @param string $objectType
773
-	 * @param string $objectId
774
-	 * @param \DateTime $beforeDate
775
-	 * @param string $verb
776
-	 * @return int
777
-	 * @since 21.0.0
778
-	 */
779
-	public function getLastCommentBeforeDate(string $objectType, string $objectId, \DateTime $beforeDate, string $verb = ''): int {
780
-		$query = $this->dbConn->getQueryBuilder();
781
-		$query->select('id')
782
-			->from('comments')
783
-			->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
784
-			->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
785
-			->andWhere($query->expr()->lt('creation_timestamp', $query->createNamedParameter($beforeDate, IQueryBuilder::PARAM_DATE)))
786
-			->orderBy('creation_timestamp', 'desc');
787
-
788
-		if ($verb !== '') {
789
-			$query->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)));
790
-		}
791
-
792
-		$result = $query->execute();
793
-		$data = $result->fetch();
794
-		$result->closeCursor();
795
-
796
-		return (int) ($data['id'] ?? 0);
797
-	}
798
-
799
-	/**
800
-	 * @param string $objectType
801
-	 * @param string $objectId
802
-	 * @param string $verb
803
-	 * @param string $actorType
804
-	 * @param string[] $actors
805
-	 * @return \DateTime[] Map of "string actor" => "\DateTime most recent comment date"
806
-	 * @psalm-return array<string, \DateTime>
807
-	 * @since 21.0.0
808
-	 */
809
-	public function getLastCommentDateByActor(
810
-		string $objectType,
811
-		string $objectId,
812
-		string $verb,
813
-		string $actorType,
814
-		array $actors
815
-	): array {
816
-		$lastComments = [];
817
-
818
-		$query = $this->dbConn->getQueryBuilder();
819
-		$query->select('actor_id')
820
-			->selectAlias($query->createFunction('MAX(' . $query->getColumnName('creation_timestamp') . ')'), 'last_comment')
821
-			->from('comments')
822
-			->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
823
-			->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
824
-			->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)))
825
-			->andWhere($query->expr()->eq('actor_type', $query->createNamedParameter($actorType)))
826
-			->andWhere($query->expr()->in('actor_id', $query->createNamedParameter($actors, IQueryBuilder::PARAM_STR_ARRAY)))
827
-			->groupBy('actor_id');
828
-
829
-		$result = $query->execute();
830
-		while ($row = $result->fetch()) {
831
-			$lastComments[$row['actor_id']] = $this->timeFactory->getDateTime($row['last_comment']);
832
-		}
833
-		$result->closeCursor();
834
-
835
-		return $lastComments;
836
-	}
837
-
838
-	/**
839
-	 * Get the number of unread comments for all files in a folder
840
-	 *
841
-	 * @param int $folderId
842
-	 * @param IUser $user
843
-	 * @return array [$fileId => $unreadCount]
844
-	 */
845
-	public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
846
-		$qb = $this->dbConn->getQueryBuilder();
847
-
848
-		$query = $qb->select('f.fileid')
849
-			->addSelect($qb->func()->count('c.id', 'num_ids'))
850
-			->from('filecache', 'f')
851
-			->leftJoin('f', 'comments', 'c', $qb->expr()->andX(
852
-				$qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT)),
853
-				$qb->expr()->eq('c.object_type', $qb->createNamedParameter('files'))
854
-			))
855
-			->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX(
856
-				$qb->expr()->eq('c.object_id', 'm.object_id'),
857
-				$qb->expr()->eq('m.object_type', $qb->createNamedParameter('files'))
858
-			))
859
-			->where(
860
-				$qb->expr()->andX(
861
-					$qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId)),
862
-					$qb->expr()->orX(
863
-						$qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
864
-						$qb->expr()->isNull('c.object_type')
865
-					),
866
-					$qb->expr()->orX(
867
-						$qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')),
868
-						$qb->expr()->isNull('m.object_type')
869
-					),
870
-					$qb->expr()->orX(
871
-						$qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID())),
872
-						$qb->expr()->isNull('m.user_id')
873
-					),
874
-					$qb->expr()->orX(
875
-						$qb->expr()->gt('c.creation_timestamp', 'm.marker_datetime'),
876
-						$qb->expr()->isNull('m.marker_datetime')
877
-					)
878
-				)
879
-			)->groupBy('f.fileid');
880
-
881
-		$resultStatement = $query->execute();
882
-
883
-		$results = [];
884
-		while ($row = $resultStatement->fetch()) {
885
-			$results[$row['fileid']] = (int) $row['num_ids'];
886
-		}
887
-		$resultStatement->closeCursor();
888
-		return $results;
889
-	}
890
-
891
-	/**
892
-	 * creates a new comment and returns it. At this point of time, it is not
893
-	 * saved in the used data storage. Use save() after setting other fields
894
-	 * of the comment (e.g. message or verb).
895
-	 *
896
-	 * @param string $actorType the actor type (e.g. 'users')
897
-	 * @param string $actorId a user id
898
-	 * @param string $objectType the object type the comment is attached to
899
-	 * @param string $objectId the object id the comment is attached to
900
-	 * @return IComment
901
-	 * @since 9.0.0
902
-	 */
903
-	public function create($actorType, $actorId, $objectType, $objectId) {
904
-		$comment = new Comment();
905
-		$comment
906
-			->setActor($actorType, $actorId)
907
-			->setObject($objectType, $objectId);
908
-		return $comment;
909
-	}
910
-
911
-	/**
912
-	 * permanently deletes the comment specified by the ID
913
-	 *
914
-	 * When the comment has child comments, their parent ID will be changed to
915
-	 * the parent ID of the item that is to be deleted.
916
-	 *
917
-	 * @param string $id
918
-	 * @return bool
919
-	 * @throws \InvalidArgumentException
920
-	 * @since 9.0.0
921
-	 */
922
-	public function delete($id) {
923
-		if (!is_string($id)) {
924
-			throw new \InvalidArgumentException('Parameter must be string');
925
-		}
926
-
927
-		try {
928
-			$comment = $this->get($id);
929
-		} catch (\Exception $e) {
930
-			// Ignore exceptions, we just don't fire a hook then
931
-			$comment = null;
932
-		}
933
-
934
-		$qb = $this->dbConn->getQueryBuilder();
935
-		$query = $qb->delete('comments')
936
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
937
-			->setParameter('id', $id);
938
-
939
-		try {
940
-			$affectedRows = $query->execute();
941
-			$this->uncache($id);
942
-		} catch (DriverException $e) {
943
-			$this->logger->error($e->getMessage(), [
944
-				'exception' => $e,
945
-				'app' => 'core_comments',
946
-			]);
947
-			return false;
948
-		}
949
-
950
-		if ($affectedRows > 0 && $comment instanceof IComment) {
951
-			if ($comment->getVerb() === 'reaction_deleted') {
952
-				$this->deleteReaction($comment);
953
-			}
954
-			$this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
955
-		}
956
-
957
-		return ($affectedRows > 0);
958
-	}
959
-
960
-	private function deleteReaction(IComment $reaction): void {
961
-		$qb = $this->dbConn->getQueryBuilder();
962
-		$qb->delete('reactions')
963
-			->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($reaction->getParentId())))
964
-			->andWhere($qb->expr()->eq('message_id', $qb->createNamedParameter($reaction->getId())))
965
-			->executeStatement();
966
-		$this->sumReactions($reaction->getParentId());
967
-	}
968
-
969
-	/**
970
-	 * Get comment related with user reaction
971
-	 *
972
-	 * Throws PreConditionNotMetException when the system haven't the minimum requirements to
973
-	 * use reactions
974
-	 *
975
-	 * @param int $parentId
976
-	 * @param string $actorType
977
-	 * @param string $actorId
978
-	 * @param string $reaction
979
-	 * @return IComment
980
-	 * @throws NotFoundException
981
-	 * @throws PreConditionNotMetException
982
-	 * @since 24.0.0
983
-	 */
984
-	public function getReactionComment(int $parentId, string $actorType, string $actorId, string $reaction): IComment {
985
-		$this->throwIfNotSupportReactions();
986
-		$qb = $this->dbConn->getQueryBuilder();
987
-		$messageId = $qb
988
-			->select('message_id')
989
-			->from('reactions')
990
-			->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($parentId)))
991
-			->andWhere($qb->expr()->eq('actor_type', $qb->createNamedParameter($actorType)))
992
-			->andWhere($qb->expr()->eq('actor_id', $qb->createNamedParameter($actorId)))
993
-			->andWhere($qb->expr()->eq('reaction', $qb->createNamedParameter($reaction)))
994
-			->executeQuery()
995
-			->fetchOne();
996
-		if (!$messageId) {
997
-			throw new NotFoundException('Comment related with reaction not found');
998
-		}
999
-		return $this->get($messageId);
1000
-	}
1001
-
1002
-	/**
1003
-	 * Retrieve all reactions of a message
1004
-	 *
1005
-	 * Throws PreConditionNotMetException when the system haven't the minimum requirements to
1006
-	 * use reactions
1007
-	 *
1008
-	 * @param int $parentId
1009
-	 * @return IComment[]
1010
-	 * @throws PreConditionNotMetException
1011
-	 * @since 24.0.0
1012
-	 */
1013
-	public function retrieveAllReactions(int $parentId): array {
1014
-		$this->throwIfNotSupportReactions();
1015
-		$qb = $this->dbConn->getQueryBuilder();
1016
-		$result = $qb
1017
-			->select('message_id')
1018
-			->from('reactions')
1019
-			->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($parentId)))
1020
-			->executeQuery();
1021
-
1022
-		$commentIds = [];
1023
-		while ($data = $result->fetch()) {
1024
-			$commentIds[] = $data['message_id'];
1025
-		}
1026
-
1027
-		return $this->getCommentsById($commentIds);
1028
-	}
1029
-
1030
-	/**
1031
-	 * Retrieve all reactions with specific reaction of a message
1032
-	 *
1033
-	 * Throws PreConditionNotMetException when the system haven't the minimum requirements to
1034
-	 * use reactions
1035
-	 *
1036
-	 * @param int $parentId
1037
-	 * @param string $reaction
1038
-	 * @return IComment[]
1039
-	 * @throws PreConditionNotMetException
1040
-	 * @since 24.0.0
1041
-	 */
1042
-	public function retrieveAllReactionsWithSpecificReaction(int $parentId, string $reaction): array {
1043
-		$this->throwIfNotSupportReactions();
1044
-		$qb = $this->dbConn->getQueryBuilder();
1045
-		$result = $qb
1046
-			->select('message_id')
1047
-			->from('reactions')
1048
-			->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($parentId)))
1049
-			->andWhere($qb->expr()->eq('reaction', $qb->createNamedParameter($reaction)))
1050
-			->executeQuery();
1051
-
1052
-		$commentIds = [];
1053
-		while ($data = $result->fetch()) {
1054
-			$commentIds[] = $data['message_id'];
1055
-		}
1056
-		$comments = [];
1057
-		if ($commentIds) {
1058
-			$comments = $this->getCommentsById($commentIds);
1059
-		}
1060
-
1061
-		return $comments;
1062
-	}
1063
-
1064
-	/**
1065
-	 * Support reactions
1066
-	 *
1067
-	 * @return bool
1068
-	 * @since 24.0.0
1069
-	 */
1070
-	public function supportReactions(): bool {
1071
-		return $this->dbConn->supports4ByteText();
1072
-	}
1073
-
1074
-	/**
1075
-	 * @throws PreConditionNotMetException
1076
-	 * @since 24.0.0
1077
-	 */
1078
-	private function throwIfNotSupportReactions() {
1079
-		if (!$this->supportReactions()) {
1080
-			throw new PreConditionNotMetException('The database does not support reactions');
1081
-		}
1082
-	}
1083
-
1084
-	/**
1085
-	 * Get all comments on list
1086
-	 *
1087
-	 * @param int[] $commentIds
1088
-	 * @return IComment[]
1089
-	 * @since 24.0.0
1090
-	 */
1091
-	private function getCommentsById(array $commentIds): array {
1092
-		if (!$commentIds) {
1093
-			return [];
1094
-		}
1095
-		$query = $this->dbConn->getQueryBuilder();
1096
-
1097
-		$query->select('*')
1098
-			->from('comments')
1099
-			->where($query->expr()->in('id', $query->createNamedParameter($commentIds, IQueryBuilder::PARAM_STR_ARRAY)))
1100
-			->orderBy('creation_timestamp', 'DESC')
1101
-			->addOrderBy('id', 'DESC');
1102
-
1103
-		$comments = [];
1104
-		$result = $query->executeQuery();
1105
-		while ($data = $result->fetch()) {
1106
-			$comment = $this->getCommentFromData($data);
1107
-			$this->cache($comment);
1108
-			$comments[] = $comment;
1109
-		}
1110
-		$result->closeCursor();
1111
-		return $comments;
1112
-	}
1113
-
1114
-	/**
1115
-	 * saves the comment permanently
1116
-	 *
1117
-	 * if the supplied comment has an empty ID, a new entry comment will be
1118
-	 * saved and the instance updated with the new ID.
1119
-	 *
1120
-	 * Otherwise, an existing comment will be updated.
1121
-	 *
1122
-	 * Throws NotFoundException when a comment that is to be updated does not
1123
-	 * exist anymore at this point of time.
1124
-	 *
1125
-	 * Throws PreConditionNotMetException when the system haven't the minimum requirements to
1126
-	 * use reactions
1127
-	 *
1128
-	 * @param IComment $comment
1129
-	 * @return bool
1130
-	 * @throws NotFoundException
1131
-	 * @throws PreConditionNotMetException
1132
-	 * @since 9.0.0
1133
-	 */
1134
-	public function save(IComment $comment) {
1135
-		if ($comment->getVerb() === 'reaction') {
1136
-			$this->throwIfNotSupportReactions();
1137
-		}
1138
-
1139
-		if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
1140
-			$result = $this->insert($comment);
1141
-		} else {
1142
-			$result = $this->update($comment);
1143
-		}
1144
-
1145
-		if ($result && !!$comment->getParentId()) {
1146
-			$this->updateChildrenInformation(
1147
-				$comment->getParentId(),
1148
-				$comment->getCreationDateTime()
1149
-			);
1150
-			$this->cache($comment);
1151
-		}
1152
-
1153
-		return $result;
1154
-	}
1155
-
1156
-	/**
1157
-	 * inserts the provided comment in the database
1158
-	 *
1159
-	 * @param IComment $comment
1160
-	 * @return bool
1161
-	 */
1162
-	protected function insert(IComment $comment): bool {
1163
-		try {
1164
-			$result = $this->insertQuery($comment, true);
1165
-		} catch (InvalidFieldNameException $e) {
1166
-			// The reference id field was only added in Nextcloud 19.
1167
-			// In order to not cause too long waiting times on the update,
1168
-			// it was decided to only add it lazy, as it is also not a critical
1169
-			// feature, but only helps to have a better experience while commenting.
1170
-			// So in case the reference_id field is missing,
1171
-			// we simply save the comment without that field.
1172
-			$result = $this->insertQuery($comment, false);
1173
-		}
1174
-
1175
-		return $result;
1176
-	}
1177
-
1178
-	protected function insertQuery(IComment $comment, bool $tryWritingReferenceId): bool {
1179
-		$qb = $this->dbConn->getQueryBuilder();
1180
-
1181
-		$values = [
1182
-			'parent_id' => $qb->createNamedParameter($comment->getParentId()),
1183
-			'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
1184
-			'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
1185
-			'actor_type' => $qb->createNamedParameter($comment->getActorType()),
1186
-			'actor_id' => $qb->createNamedParameter($comment->getActorId()),
1187
-			'message' => $qb->createNamedParameter($comment->getMessage()),
1188
-			'verb' => $qb->createNamedParameter($comment->getVerb()),
1189
-			'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
1190
-			'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
1191
-			'object_type' => $qb->createNamedParameter($comment->getObjectType()),
1192
-			'object_id' => $qb->createNamedParameter($comment->getObjectId()),
1193
-		];
1194
-
1195
-		if ($tryWritingReferenceId) {
1196
-			$values['reference_id'] = $qb->createNamedParameter($comment->getReferenceId());
1197
-		}
1198
-
1199
-		$affectedRows = $qb->insert('comments')
1200
-			->values($values)
1201
-			->execute();
1202
-
1203
-		if ($affectedRows > 0) {
1204
-			$comment->setId((string)$qb->getLastInsertId());
1205
-			if ($comment->getVerb() === 'reaction') {
1206
-				$this->addReaction($comment);
1207
-			}
1208
-			$this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
1209
-		}
1210
-
1211
-		return $affectedRows > 0;
1212
-	}
1213
-
1214
-	private function addReaction(IComment $reaction): void {
1215
-		// Prevent violate constraint
1216
-		$qb = $this->dbConn->getQueryBuilder();
1217
-		$qb->select($qb->func()->count('*'))
1218
-			->from('reactions')
1219
-			->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($reaction->getParentId())))
1220
-			->andWhere($qb->expr()->eq('actor_type', $qb->createNamedParameter($reaction->getActorType())))
1221
-			->andWhere($qb->expr()->eq('actor_id', $qb->createNamedParameter($reaction->getActorId())))
1222
-			->andWhere($qb->expr()->eq('reaction', $qb->createNamedParameter($reaction->getMessage())));
1223
-		$result = $qb->executeQuery();
1224
-		$exists = (int) $result->fetchOne();
1225
-		if (!$exists) {
1226
-			$qb = $this->dbConn->getQueryBuilder();
1227
-			try {
1228
-				$qb->insert('reactions')
1229
-					->values([
1230
-						'parent_id' => $qb->createNamedParameter($reaction->getParentId()),
1231
-						'message_id' => $qb->createNamedParameter($reaction->getId()),
1232
-						'actor_type' => $qb->createNamedParameter($reaction->getActorType()),
1233
-						'actor_id' => $qb->createNamedParameter($reaction->getActorId()),
1234
-						'reaction' => $qb->createNamedParameter($reaction->getMessage()),
1235
-					])
1236
-					->executeStatement();
1237
-			} catch (\Exception $e) {
1238
-				$this->logger->error($e->getMessage(), [
1239
-					'exception' => $e,
1240
-					'app' => 'core_comments',
1241
-				]);
1242
-			}
1243
-		}
1244
-		$this->sumReactions($reaction->getParentId());
1245
-	}
1246
-
1247
-	private function sumReactions(string $parentId): void {
1248
-		$qb = $this->dbConn->getQueryBuilder();
1249
-
1250
-		$totalQuery = $this->dbConn->getQueryBuilder();
1251
-		$totalQuery
1252
-			->selectAlias(
1253
-				$totalQuery->func()->concat(
1254
-					$totalQuery->expr()->literal('"'),
1255
-					'reaction',
1256
-					$totalQuery->expr()->literal('":'),
1257
-					$totalQuery->func()->count('id')
1258
-				),
1259
-				'colonseparatedvalue'
1260
-			)
1261
-			->selectAlias($totalQuery->func()->count('id'), 'total')
1262
-			->from('reactions', 'r')
1263
-			->where($totalQuery->expr()->eq('r.parent_id', $qb->createNamedParameter($parentId)))
1264
-			->groupBy('r.reaction')
1265
-			->orderBy('total', 'DESC')
1266
-			->setMaxResults(20);
1267
-
1268
-		$jsonQuery = $this->dbConn->getQueryBuilder();
1269
-		$jsonQuery
1270
-			->selectAlias(
1271
-				$jsonQuery->func()->concat(
1272
-					$jsonQuery->expr()->literal('{'),
1273
-					$jsonQuery->func()->groupConcat('colonseparatedvalue'),
1274
-					$jsonQuery->expr()->literal('}')
1275
-				),
1276
-				'json'
1277
-			)
1278
-			->from($jsonQuery->createFunction('(' . $totalQuery->getSQL() . ')'), 'json');
1279
-
1280
-		$qb
1281
-			->update('comments')
1282
-			->set('reactions', $jsonQuery->createFunction('(' . $jsonQuery->getSQL() . ')'))
1283
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($parentId)))
1284
-			->executeStatement();
1285
-	}
1286
-
1287
-	/**
1288
-	 * updates a Comment data row
1289
-	 *
1290
-	 * @param IComment $comment
1291
-	 * @return bool
1292
-	 * @throws NotFoundException
1293
-	 */
1294
-	protected function update(IComment $comment) {
1295
-		// for properly working preUpdate Events we need the old comments as is
1296
-		// in the DB and overcome caching. Also avoid that outdated information stays.
1297
-		$this->uncache($comment->getId());
1298
-		$this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
1299
-		$this->uncache($comment->getId());
1300
-
1301
-		try {
1302
-			$result = $this->updateQuery($comment, true);
1303
-		} catch (InvalidFieldNameException $e) {
1304
-			// See function insert() for explanation
1305
-			$result = $this->updateQuery($comment, false);
1306
-		}
1307
-
1308
-		if ($comment->getVerb() === 'reaction_deleted') {
1309
-			$this->deleteReaction($comment);
1310
-		}
1311
-
1312
-		$this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
1313
-
1314
-		return $result;
1315
-	}
1316
-
1317
-	protected function updateQuery(IComment $comment, bool $tryWritingReferenceId): bool {
1318
-		$qb = $this->dbConn->getQueryBuilder();
1319
-		$qb
1320
-			->update('comments')
1321
-			->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
1322
-			->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
1323
-			->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
1324
-			->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
1325
-			->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
1326
-			->set('message', $qb->createNamedParameter($comment->getMessage()))
1327
-			->set('verb', $qb->createNamedParameter($comment->getVerb()))
1328
-			->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
1329
-			->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
1330
-			->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
1331
-			->set('object_id', $qb->createNamedParameter($comment->getObjectId()));
1332
-
1333
-		if ($tryWritingReferenceId) {
1334
-			$qb->set('reference_id', $qb->createNamedParameter($comment->getReferenceId()));
1335
-		}
1336
-
1337
-		$affectedRows = $qb->where($qb->expr()->eq('id', $qb->createNamedParameter($comment->getId())))
1338
-			->execute();
1339
-
1340
-		if ($affectedRows === 0) {
1341
-			throw new NotFoundException('Comment to update does ceased to exist');
1342
-		}
1343
-
1344
-		return $affectedRows > 0;
1345
-	}
1346
-
1347
-	/**
1348
-	 * removes references to specific actor (e.g. on user delete) of a comment.
1349
-	 * The comment itself must not get lost/deleted.
1350
-	 *
1351
-	 * @param string $actorType the actor type (e.g. 'users')
1352
-	 * @param string $actorId a user id
1353
-	 * @return boolean
1354
-	 * @since 9.0.0
1355
-	 */
1356
-	public function deleteReferencesOfActor($actorType, $actorId) {
1357
-		$this->checkRoleParameters('Actor', $actorType, $actorId);
1358
-
1359
-		$qb = $this->dbConn->getQueryBuilder();
1360
-		$affectedRows = $qb
1361
-			->update('comments')
1362
-			->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
1363
-			->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
1364
-			->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
1365
-			->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
1366
-			->setParameter('type', $actorType)
1367
-			->setParameter('id', $actorId)
1368
-			->execute();
1369
-
1370
-		$this->commentsCache = [];
1371
-
1372
-		return is_int($affectedRows);
1373
-	}
1374
-
1375
-	/**
1376
-	 * deletes all comments made of a specific object (e.g. on file delete)
1377
-	 *
1378
-	 * @param string $objectType the object type (e.g. 'files')
1379
-	 * @param string $objectId e.g. the file id
1380
-	 * @return boolean
1381
-	 * @since 9.0.0
1382
-	 */
1383
-	public function deleteCommentsAtObject($objectType, $objectId) {
1384
-		$this->checkRoleParameters('Object', $objectType, $objectId);
1385
-
1386
-		$qb = $this->dbConn->getQueryBuilder();
1387
-		$affectedRows = $qb
1388
-			->delete('comments')
1389
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
1390
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
1391
-			->setParameter('type', $objectType)
1392
-			->setParameter('id', $objectId)
1393
-			->execute();
1394
-
1395
-		$this->commentsCache = [];
1396
-
1397
-		return is_int($affectedRows);
1398
-	}
1399
-
1400
-	/**
1401
-	 * deletes the read markers for the specified user
1402
-	 *
1403
-	 * @param \OCP\IUser $user
1404
-	 * @return bool
1405
-	 * @since 9.0.0
1406
-	 */
1407
-	public function deleteReadMarksFromUser(IUser $user) {
1408
-		$qb = $this->dbConn->getQueryBuilder();
1409
-		$query = $qb->delete('comments_read_markers')
1410
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
1411
-			->setParameter('user_id', $user->getUID());
1412
-
1413
-		try {
1414
-			$affectedRows = $query->execute();
1415
-		} catch (DriverException $e) {
1416
-			$this->logger->error($e->getMessage(), [
1417
-				'exception' => $e,
1418
-				'app' => 'core_comments',
1419
-			]);
1420
-			return false;
1421
-		}
1422
-		return ($affectedRows > 0);
1423
-	}
1424
-
1425
-	/**
1426
-	 * sets the read marker for a given file to the specified date for the
1427
-	 * provided user
1428
-	 *
1429
-	 * @param string $objectType
1430
-	 * @param string $objectId
1431
-	 * @param \DateTime $dateTime
1432
-	 * @param IUser $user
1433
-	 * @since 9.0.0
1434
-	 */
1435
-	public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
1436
-		$this->checkRoleParameters('Object', $objectType, $objectId);
1437
-
1438
-		$qb = $this->dbConn->getQueryBuilder();
1439
-		$values = [
1440
-			'user_id' => $qb->createNamedParameter($user->getUID()),
1441
-			'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
1442
-			'object_type' => $qb->createNamedParameter($objectType),
1443
-			'object_id' => $qb->createNamedParameter($objectId),
1444
-		];
1445
-
1446
-		// Strategy: try to update, if this does not return affected rows, do an insert.
1447
-		$affectedRows = $qb
1448
-			->update('comments_read_markers')
1449
-			->set('user_id', $values['user_id'])
1450
-			->set('marker_datetime', $values['marker_datetime'])
1451
-			->set('object_type', $values['object_type'])
1452
-			->set('object_id', $values['object_id'])
1453
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
1454
-			->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
1455
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
1456
-			->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
1457
-			->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
1458
-			->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
1459
-			->execute();
1460
-
1461
-		if ($affectedRows > 0) {
1462
-			return;
1463
-		}
1464
-
1465
-		$qb->insert('comments_read_markers')
1466
-			->values($values)
1467
-			->execute();
1468
-	}
1469
-
1470
-	/**
1471
-	 * returns the read marker for a given file to the specified date for the
1472
-	 * provided user. It returns null, when the marker is not present, i.e.
1473
-	 * no comments were marked as read.
1474
-	 *
1475
-	 * @param string $objectType
1476
-	 * @param string $objectId
1477
-	 * @param IUser $user
1478
-	 * @return \DateTime|null
1479
-	 * @since 9.0.0
1480
-	 */
1481
-	public function getReadMark($objectType, $objectId, IUser $user) {
1482
-		$qb = $this->dbConn->getQueryBuilder();
1483
-		$resultStatement = $qb->select('marker_datetime')
1484
-			->from('comments_read_markers')
1485
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
1486
-			->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
1487
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
1488
-			->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
1489
-			->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
1490
-			->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
1491
-			->execute();
1492
-
1493
-		$data = $resultStatement->fetch();
1494
-		$resultStatement->closeCursor();
1495
-		if (!$data || is_null($data['marker_datetime'])) {
1496
-			return null;
1497
-		}
1498
-
1499
-		return new \DateTime($data['marker_datetime']);
1500
-	}
1501
-
1502
-	/**
1503
-	 * deletes the read markers on the specified object
1504
-	 *
1505
-	 * @param string $objectType
1506
-	 * @param string $objectId
1507
-	 * @return bool
1508
-	 * @since 9.0.0
1509
-	 */
1510
-	public function deleteReadMarksOnObject($objectType, $objectId) {
1511
-		$this->checkRoleParameters('Object', $objectType, $objectId);
1512
-
1513
-		$qb = $this->dbConn->getQueryBuilder();
1514
-		$query = $qb->delete('comments_read_markers')
1515
-			->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
1516
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
1517
-			->setParameter('object_type', $objectType)
1518
-			->setParameter('object_id', $objectId);
1519
-
1520
-		try {
1521
-			$affectedRows = $query->execute();
1522
-		} catch (DriverException $e) {
1523
-			$this->logger->error($e->getMessage(), [
1524
-				'exception' => $e,
1525
-				'app' => 'core_comments',
1526
-			]);
1527
-			return false;
1528
-		}
1529
-		return ($affectedRows > 0);
1530
-	}
1531
-
1532
-	/**
1533
-	 * registers an Entity to the manager, so event notifications can be send
1534
-	 * to consumers of the comments infrastructure
1535
-	 *
1536
-	 * @param \Closure $closure
1537
-	 */
1538
-	public function registerEventHandler(\Closure $closure) {
1539
-		$this->eventHandlerClosures[] = $closure;
1540
-		$this->eventHandlers = [];
1541
-	}
1542
-
1543
-	/**
1544
-	 * registers a method that resolves an ID to a display name for a given type
1545
-	 *
1546
-	 * @param string $type
1547
-	 * @param \Closure $closure
1548
-	 * @throws \OutOfBoundsException
1549
-	 * @since 11.0.0
1550
-	 *
1551
-	 * Only one resolver shall be registered per type. Otherwise a
1552
-	 * \OutOfBoundsException has to thrown.
1553
-	 */
1554
-	public function registerDisplayNameResolver($type, \Closure $closure) {
1555
-		if (!is_string($type)) {
1556
-			throw new \InvalidArgumentException('String expected.');
1557
-		}
1558
-		if (isset($this->displayNameResolvers[$type])) {
1559
-			throw new \OutOfBoundsException('Displayname resolver for this type already registered');
1560
-		}
1561
-		$this->displayNameResolvers[$type] = $closure;
1562
-	}
1563
-
1564
-	/**
1565
-	 * resolves a given ID of a given Type to a display name.
1566
-	 *
1567
-	 * @param string $type
1568
-	 * @param string $id
1569
-	 * @return string
1570
-	 * @throws \OutOfBoundsException
1571
-	 * @since 11.0.0
1572
-	 *
1573
-	 * If a provided type was not registered, an \OutOfBoundsException shall
1574
-	 * be thrown. It is upon the resolver discretion what to return of the
1575
-	 * provided ID is unknown. It must be ensured that a string is returned.
1576
-	 */
1577
-	public function resolveDisplayName($type, $id) {
1578
-		if (!is_string($type)) {
1579
-			throw new \InvalidArgumentException('String expected.');
1580
-		}
1581
-		if (!isset($this->displayNameResolvers[$type])) {
1582
-			throw new \OutOfBoundsException('No Displayname resolver for this type registered');
1583
-		}
1584
-		return (string)$this->displayNameResolvers[$type]($id);
1585
-	}
1586
-
1587
-	/**
1588
-	 * returns valid, registered entities
1589
-	 *
1590
-	 * @return \OCP\Comments\ICommentsEventHandler[]
1591
-	 */
1592
-	private function getEventHandlers() {
1593
-		if (!empty($this->eventHandlers)) {
1594
-			return $this->eventHandlers;
1595
-		}
1596
-
1597
-		$this->eventHandlers = [];
1598
-		foreach ($this->eventHandlerClosures as $name => $closure) {
1599
-			$entity = $closure();
1600
-			if (!($entity instanceof ICommentsEventHandler)) {
1601
-				throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
1602
-			}
1603
-			$this->eventHandlers[$name] = $entity;
1604
-		}
1605
-
1606
-		return $this->eventHandlers;
1607
-	}
1608
-
1609
-	/**
1610
-	 * sends notifications to the registered entities
1611
-	 *
1612
-	 * @param $eventType
1613
-	 * @param IComment $comment
1614
-	 */
1615
-	private function sendEvent($eventType, IComment $comment) {
1616
-		$entities = $this->getEventHandlers();
1617
-		$event = new CommentsEvent($eventType, $comment);
1618
-		foreach ($entities as $entity) {
1619
-			$entity->handle($event);
1620
-		}
1621
-	}
1622
-
1623
-	/**
1624
-	 * Load the Comments app into the page
1625
-	 *
1626
-	 * @since 21.0.0
1627
-	 */
1628
-	public function load(): void {
1629
-		$this->initialStateService->provideInitialState('comments', 'max-message-length', IComment::MAX_MESSAGE_LENGTH);
1630
-		Util::addScript('comments', 'comments-app');
1631
-	}
50
+    /** @var  IDBConnection */
51
+    protected $dbConn;
52
+
53
+    /** @var  LoggerInterface */
54
+    protected $logger;
55
+
56
+    /** @var IConfig */
57
+    protected $config;
58
+
59
+    /** @var ITimeFactory */
60
+    protected $timeFactory;
61
+
62
+    /** @var IInitialStateService */
63
+    protected $initialStateService;
64
+
65
+    /** @var IComment[] */
66
+    protected $commentsCache = [];
67
+
68
+    /** @var  \Closure[] */
69
+    protected $eventHandlerClosures = [];
70
+
71
+    /** @var  ICommentsEventHandler[] */
72
+    protected $eventHandlers = [];
73
+
74
+    /** @var \Closure[] */
75
+    protected $displayNameResolvers = [];
76
+
77
+    public function __construct(IDBConnection $dbConn,
78
+                                LoggerInterface $logger,
79
+                                IConfig $config,
80
+                                ITimeFactory $timeFactory,
81
+                                IInitialStateService $initialStateService) {
82
+        $this->dbConn = $dbConn;
83
+        $this->logger = $logger;
84
+        $this->config = $config;
85
+        $this->timeFactory = $timeFactory;
86
+        $this->initialStateService = $initialStateService;
87
+    }
88
+
89
+    /**
90
+     * converts data base data into PHP native, proper types as defined by
91
+     * IComment interface.
92
+     *
93
+     * @param array $data
94
+     * @return array
95
+     */
96
+    protected function normalizeDatabaseData(array $data) {
97
+        $data['id'] = (string)$data['id'];
98
+        $data['parent_id'] = (string)$data['parent_id'];
99
+        $data['topmost_parent_id'] = (string)$data['topmost_parent_id'];
100
+        $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
101
+        if (!is_null($data['latest_child_timestamp'])) {
102
+            $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
103
+        }
104
+        $data['children_count'] = (int)$data['children_count'];
105
+        $data['reference_id'] = $data['reference_id'] ?? null;
106
+        if ($this->supportReactions()) {
107
+            $list = json_decode($data['reactions'], true);
108
+            // Ordering does not work on the database with group concat and Oracle,
109
+            // So we simply sort on the output.
110
+            if (is_array($list)) {
111
+                uasort($list, static function ($a, $b) {
112
+                    if ($a === $b) {
113
+                        return 0;
114
+                    }
115
+                    return ($a > $b) ? -1 : 1;
116
+                });
117
+            }
118
+            $data['reactions'] = $list;
119
+        }
120
+        return $data;
121
+    }
122
+
123
+
124
+    /**
125
+     * @param array $data
126
+     * @return IComment
127
+     */
128
+    public function getCommentFromData(array $data): IComment {
129
+        return new Comment($this->normalizeDatabaseData($data));
130
+    }
131
+
132
+    /**
133
+     * prepares a comment for an insert or update operation after making sure
134
+     * all necessary fields have a value assigned.
135
+     *
136
+     * @param IComment $comment
137
+     * @return IComment returns the same updated IComment instance as provided
138
+     *                  by parameter for convenience
139
+     * @throws \UnexpectedValueException
140
+     */
141
+    protected function prepareCommentForDatabaseWrite(IComment $comment) {
142
+        if (!$comment->getActorType()
143
+            || $comment->getActorId() === ''
144
+            || !$comment->getObjectType()
145
+            || $comment->getObjectId() === ''
146
+            || !$comment->getVerb()
147
+        ) {
148
+            throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
149
+        }
150
+
151
+        if ($comment->getVerb() === 'reaction' && mb_strlen($comment->getMessage()) > 2) {
152
+            throw new \UnexpectedValueException('Reactions cannot be longer than 2 chars (emoji with skin tone have two chars)');
153
+        }
154
+
155
+        if ($comment->getId() === '') {
156
+            $comment->setChildrenCount(0);
157
+            $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
158
+            $comment->setLatestChildDateTime(null);
159
+        }
160
+
161
+        if (is_null($comment->getCreationDateTime())) {
162
+            $comment->setCreationDateTime(new \DateTime());
163
+        }
164
+
165
+        if ($comment->getParentId() !== '0') {
166
+            $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
167
+        } else {
168
+            $comment->setTopmostParentId('0');
169
+        }
170
+
171
+        $this->cache($comment);
172
+
173
+        return $comment;
174
+    }
175
+
176
+    /**
177
+     * returns the topmost parent id of a given comment identified by ID
178
+     *
179
+     * @param string $id
180
+     * @return string
181
+     * @throws NotFoundException
182
+     */
183
+    protected function determineTopmostParentId($id) {
184
+        $comment = $this->get($id);
185
+        if ($comment->getParentId() === '0') {
186
+            return $comment->getId();
187
+        }
188
+
189
+        return $this->determineTopmostParentId($comment->getParentId());
190
+    }
191
+
192
+    /**
193
+     * updates child information of a comment
194
+     *
195
+     * @param string $id
196
+     * @param \DateTime $cDateTime the date time of the most recent child
197
+     * @throws NotFoundException
198
+     */
199
+    protected function updateChildrenInformation($id, \DateTime $cDateTime) {
200
+        $qb = $this->dbConn->getQueryBuilder();
201
+        $query = $qb->select($qb->func()->count('id'))
202
+            ->from('comments')
203
+            ->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
204
+            ->setParameter('id', $id);
205
+
206
+        $resultStatement = $query->execute();
207
+        $data = $resultStatement->fetch(\PDO::FETCH_NUM);
208
+        $resultStatement->closeCursor();
209
+        $children = (int)$data[0];
210
+
211
+        $comment = $this->get($id);
212
+        $comment->setChildrenCount($children);
213
+        $comment->setLatestChildDateTime($cDateTime);
214
+        $this->save($comment);
215
+    }
216
+
217
+    /**
218
+     * Tests whether actor or object type and id parameters are acceptable.
219
+     * Throws exception if not.
220
+     *
221
+     * @param string $role
222
+     * @param string $type
223
+     * @param string $id
224
+     * @throws \InvalidArgumentException
225
+     */
226
+    protected function checkRoleParameters($role, $type, $id) {
227
+        if (
228
+            !is_string($type) || empty($type)
229
+            || !is_string($id) || empty($id)
230
+        ) {
231
+            throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
232
+        }
233
+    }
234
+
235
+    /**
236
+     * run-time caches a comment
237
+     *
238
+     * @param IComment $comment
239
+     */
240
+    protected function cache(IComment $comment) {
241
+        $id = $comment->getId();
242
+        if (empty($id)) {
243
+            return;
244
+        }
245
+        $this->commentsCache[(string)$id] = $comment;
246
+    }
247
+
248
+    /**
249
+     * removes an entry from the comments run time cache
250
+     *
251
+     * @param mixed $id the comment's id
252
+     */
253
+    protected function uncache($id) {
254
+        $id = (string)$id;
255
+        if (isset($this->commentsCache[$id])) {
256
+            unset($this->commentsCache[$id]);
257
+        }
258
+    }
259
+
260
+    /**
261
+     * returns a comment instance
262
+     *
263
+     * @param string $id the ID of the comment
264
+     * @return IComment
265
+     * @throws NotFoundException
266
+     * @throws \InvalidArgumentException
267
+     * @since 9.0.0
268
+     */
269
+    public function get($id) {
270
+        if ((int)$id === 0) {
271
+            throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
272
+        }
273
+
274
+        if (isset($this->commentsCache[$id])) {
275
+            return $this->commentsCache[$id];
276
+        }
277
+
278
+        $qb = $this->dbConn->getQueryBuilder();
279
+        $resultStatement = $qb->select('*')
280
+            ->from('comments')
281
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
282
+            ->setParameter('id', $id, IQueryBuilder::PARAM_INT)
283
+            ->execute();
284
+
285
+        $data = $resultStatement->fetch();
286
+        $resultStatement->closeCursor();
287
+        if (!$data) {
288
+            throw new NotFoundException();
289
+        }
290
+
291
+
292
+        $comment = $this->getCommentFromData($data);
293
+        $this->cache($comment);
294
+        return $comment;
295
+    }
296
+
297
+    /**
298
+     * returns the comment specified by the id and all it's child comments.
299
+     * At this point of time, we do only support one level depth.
300
+     *
301
+     * @param string $id
302
+     * @param int $limit max number of entries to return, 0 returns all
303
+     * @param int $offset the start entry
304
+     * @return array
305
+     * @since 9.0.0
306
+     *
307
+     * The return array looks like this
308
+     * [
309
+     *   'comment' => IComment, // root comment
310
+     *   'replies' =>
311
+     *   [
312
+     *     0 =>
313
+     *     [
314
+     *       'comment' => IComment,
315
+     *       'replies' => []
316
+     *     ]
317
+     *     1 =>
318
+     *     [
319
+     *       'comment' => IComment,
320
+     *       'replies'=> []
321
+     *     ],
322
+     *     …
323
+     *   ]
324
+     * ]
325
+     */
326
+    public function getTree($id, $limit = 0, $offset = 0) {
327
+        $tree = [];
328
+        $tree['comment'] = $this->get($id);
329
+        $tree['replies'] = [];
330
+
331
+        $qb = $this->dbConn->getQueryBuilder();
332
+        $query = $qb->select('*')
333
+            ->from('comments')
334
+            ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
335
+            ->orderBy('creation_timestamp', 'DESC')
336
+            ->setParameter('id', $id);
337
+
338
+        if ($limit > 0) {
339
+            $query->setMaxResults($limit);
340
+        }
341
+        if ($offset > 0) {
342
+            $query->setFirstResult($offset);
343
+        }
344
+
345
+        $resultStatement = $query->execute();
346
+        while ($data = $resultStatement->fetch()) {
347
+            $comment = $this->getCommentFromData($data);
348
+            $this->cache($comment);
349
+            $tree['replies'][] = [
350
+                'comment' => $comment,
351
+                'replies' => []
352
+            ];
353
+        }
354
+        $resultStatement->closeCursor();
355
+
356
+        return $tree;
357
+    }
358
+
359
+    /**
360
+     * returns comments for a specific object (e.g. a file).
361
+     *
362
+     * The sort order is always newest to oldest.
363
+     *
364
+     * @param string $objectType the object type, e.g. 'files'
365
+     * @param string $objectId the id of the object
366
+     * @param int $limit optional, number of maximum comments to be returned. if
367
+     * not specified, all comments are returned.
368
+     * @param int $offset optional, starting point
369
+     * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
370
+     * that may be returned
371
+     * @return IComment[]
372
+     * @since 9.0.0
373
+     */
374
+    public function getForObject(
375
+        $objectType,
376
+        $objectId,
377
+        $limit = 0,
378
+        $offset = 0,
379
+        \DateTime $notOlderThan = null
380
+    ) {
381
+        $comments = [];
382
+
383
+        $qb = $this->dbConn->getQueryBuilder();
384
+        $query = $qb->select('*')
385
+            ->from('comments')
386
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
387
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
388
+            ->orderBy('creation_timestamp', 'DESC')
389
+            ->setParameter('type', $objectType)
390
+            ->setParameter('id', $objectId);
391
+
392
+        if ($limit > 0) {
393
+            $query->setMaxResults($limit);
394
+        }
395
+        if ($offset > 0) {
396
+            $query->setFirstResult($offset);
397
+        }
398
+        if (!is_null($notOlderThan)) {
399
+            $query
400
+                ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
401
+                ->setParameter('notOlderThan', $notOlderThan, 'datetime');
402
+        }
403
+
404
+        $resultStatement = $query->execute();
405
+        while ($data = $resultStatement->fetch()) {
406
+            $comment = $this->getCommentFromData($data);
407
+            $this->cache($comment);
408
+            $comments[] = $comment;
409
+        }
410
+        $resultStatement->closeCursor();
411
+
412
+        return $comments;
413
+    }
414
+
415
+    /**
416
+     * @param string $objectType the object type, e.g. 'files'
417
+     * @param string $objectId the id of the object
418
+     * @param int $lastKnownCommentId the last known comment (will be used as offset)
419
+     * @param string $sortDirection direction of the comments (`asc` or `desc`)
420
+     * @param int $limit optional, number of maximum comments to be returned. if
421
+     * set to 0, all comments are returned.
422
+     * @param bool $includeLastKnown
423
+     * @return IComment[]
424
+     * @return array
425
+     */
426
+    public function getForObjectSince(
427
+        string $objectType,
428
+        string $objectId,
429
+        int $lastKnownCommentId,
430
+        string $sortDirection = 'asc',
431
+        int $limit = 30,
432
+        bool $includeLastKnown = false
433
+    ): array {
434
+        return $this->getCommentsWithVerbForObjectSinceComment(
435
+            $objectType,
436
+            $objectId,
437
+            [],
438
+            $lastKnownCommentId,
439
+            $sortDirection,
440
+            $limit,
441
+            $includeLastKnown
442
+        );
443
+    }
444
+
445
+    /**
446
+     * @param string $objectType the object type, e.g. 'files'
447
+     * @param string $objectId the id of the object
448
+     * @param string[] $verbs List of verbs to filter by
449
+     * @param int $lastKnownCommentId the last known comment (will be used as offset)
450
+     * @param string $sortDirection direction of the comments (`asc` or `desc`)
451
+     * @param int $limit optional, number of maximum comments to be returned. if
452
+     * set to 0, all comments are returned.
453
+     * @param bool $includeLastKnown
454
+     * @return IComment[]
455
+     */
456
+    public function getCommentsWithVerbForObjectSinceComment(
457
+        string $objectType,
458
+        string $objectId,
459
+        array $verbs,
460
+        int $lastKnownCommentId,
461
+        string $sortDirection = 'asc',
462
+        int $limit = 30,
463
+        bool $includeLastKnown = false
464
+    ): array {
465
+        $comments = [];
466
+
467
+        $query = $this->dbConn->getQueryBuilder();
468
+        $query->select('*')
469
+            ->from('comments')
470
+            ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
471
+            ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
472
+            ->orderBy('creation_timestamp', $sortDirection === 'desc' ? 'DESC' : 'ASC')
473
+            ->addOrderBy('id', $sortDirection === 'desc' ? 'DESC' : 'ASC');
474
+
475
+        if ($limit > 0) {
476
+            $query->setMaxResults($limit);
477
+        }
478
+
479
+        if (!empty($verbs)) {
480
+            $query->andWhere($query->expr()->in('verb', $query->createNamedParameter($verbs, IQueryBuilder::PARAM_STR_ARRAY)));
481
+        }
482
+
483
+        $lastKnownComment = $lastKnownCommentId > 0 ? $this->getLastKnownComment(
484
+            $objectType,
485
+            $objectId,
486
+            $lastKnownCommentId
487
+        ) : null;
488
+        if ($lastKnownComment instanceof IComment) {
489
+            $lastKnownCommentDateTime = $lastKnownComment->getCreationDateTime();
490
+            if ($sortDirection === 'desc') {
491
+                if ($includeLastKnown) {
492
+                    $idComparison = $query->expr()->lte('id', $query->createNamedParameter($lastKnownCommentId));
493
+                } else {
494
+                    $idComparison = $query->expr()->lt('id', $query->createNamedParameter($lastKnownCommentId));
495
+                }
496
+                $query->andWhere(
497
+                    $query->expr()->orX(
498
+                        $query->expr()->lt(
499
+                            'creation_timestamp',
500
+                            $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
501
+                            IQueryBuilder::PARAM_DATE
502
+                        ),
503
+                        $query->expr()->andX(
504
+                            $query->expr()->eq(
505
+                                'creation_timestamp',
506
+                                $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
507
+                                IQueryBuilder::PARAM_DATE
508
+                            ),
509
+                            $idComparison
510
+                        )
511
+                    )
512
+                );
513
+            } else {
514
+                if ($includeLastKnown) {
515
+                    $idComparison = $query->expr()->gte('id', $query->createNamedParameter($lastKnownCommentId));
516
+                } else {
517
+                    $idComparison = $query->expr()->gt('id', $query->createNamedParameter($lastKnownCommentId));
518
+                }
519
+                $query->andWhere(
520
+                    $query->expr()->orX(
521
+                        $query->expr()->gt(
522
+                            'creation_timestamp',
523
+                            $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
524
+                            IQueryBuilder::PARAM_DATE
525
+                        ),
526
+                        $query->expr()->andX(
527
+                            $query->expr()->eq(
528
+                                'creation_timestamp',
529
+                                $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
530
+                                IQueryBuilder::PARAM_DATE
531
+                            ),
532
+                            $idComparison
533
+                        )
534
+                    )
535
+                );
536
+            }
537
+        }
538
+
539
+        $resultStatement = $query->execute();
540
+        while ($data = $resultStatement->fetch()) {
541
+            $comment = $this->getCommentFromData($data);
542
+            $this->cache($comment);
543
+            $comments[] = $comment;
544
+        }
545
+        $resultStatement->closeCursor();
546
+
547
+        return $comments;
548
+    }
549
+
550
+    /**
551
+     * @param string $objectType the object type, e.g. 'files'
552
+     * @param string $objectId the id of the object
553
+     * @param int $id the comment to look for
554
+     * @return Comment|null
555
+     */
556
+    protected function getLastKnownComment(string $objectType,
557
+                                            string $objectId,
558
+                                            int $id) {
559
+        $query = $this->dbConn->getQueryBuilder();
560
+        $query->select('*')
561
+            ->from('comments')
562
+            ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
563
+            ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
564
+            ->andWhere($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
565
+
566
+        $result = $query->execute();
567
+        $row = $result->fetch();
568
+        $result->closeCursor();
569
+
570
+        if ($row) {
571
+            $comment = $this->getCommentFromData($row);
572
+            $this->cache($comment);
573
+            return $comment;
574
+        }
575
+
576
+        return null;
577
+    }
578
+
579
+    /**
580
+     * Search for comments with a given content
581
+     *
582
+     * @param string $search content to search for
583
+     * @param string $objectType Limit the search by object type
584
+     * @param string $objectId Limit the search by object id
585
+     * @param string $verb Limit the verb of the comment
586
+     * @param int $offset
587
+     * @param int $limit
588
+     * @return IComment[]
589
+     */
590
+    public function search(string $search, string $objectType, string $objectId, string $verb, int $offset, int $limit = 50): array {
591
+        $objectIds = [];
592
+        if ($objectId) {
593
+            $objectIds[] = $objectIds;
594
+        }
595
+        return $this->searchForObjects($search, $objectType, $objectIds, $verb, $offset, $limit);
596
+    }
597
+
598
+    /**
599
+     * Search for comments on one or more objects with a given content
600
+     *
601
+     * @param string $search content to search for
602
+     * @param string $objectType Limit the search by object type
603
+     * @param array $objectIds Limit the search by object ids
604
+     * @param string $verb Limit the verb of the comment
605
+     * @param int $offset
606
+     * @param int $limit
607
+     * @return IComment[]
608
+     */
609
+    public function searchForObjects(string $search, string $objectType, array $objectIds, string $verb, int $offset, int $limit = 50): array {
610
+        $query = $this->dbConn->getQueryBuilder();
611
+
612
+        $query->select('*')
613
+            ->from('comments')
614
+            ->orderBy('creation_timestamp', 'DESC')
615
+            ->addOrderBy('id', 'DESC')
616
+            ->setMaxResults($limit);
617
+
618
+        if ($search !== '') {
619
+            $query->where($query->expr()->iLike('message', $query->createNamedParameter(
620
+                '%' . $this->dbConn->escapeLikeParameter($search). '%'
621
+            )));
622
+        }
623
+
624
+        if ($objectType !== '') {
625
+            $query->andWhere($query->expr()->eq('object_type', $query->createNamedParameter($objectType)));
626
+        }
627
+        if (!empty($objectIds)) {
628
+            $query->andWhere($query->expr()->in('object_id', $query->createNamedParameter($objectIds, IQueryBuilder::PARAM_STR_ARRAY)));
629
+        }
630
+        if ($verb !== '') {
631
+            $query->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)));
632
+        }
633
+        if ($offset !== 0) {
634
+            $query->setFirstResult($offset);
635
+        }
636
+
637
+        $comments = [];
638
+        $result = $query->execute();
639
+        while ($data = $result->fetch()) {
640
+            $comment = $this->getCommentFromData($data);
641
+            $this->cache($comment);
642
+            $comments[] = $comment;
643
+        }
644
+        $result->closeCursor();
645
+
646
+        return $comments;
647
+    }
648
+
649
+    /**
650
+     * @param $objectType string the object type, e.g. 'files'
651
+     * @param $objectId string the id of the object
652
+     * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
653
+     * that may be returned
654
+     * @param string $verb Limit the verb of the comment - Added in 14.0.0
655
+     * @return Int
656
+     * @since 9.0.0
657
+     */
658
+    public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null, $verb = '') {
659
+        $qb = $this->dbConn->getQueryBuilder();
660
+        $query = $qb->select($qb->func()->count('id'))
661
+            ->from('comments')
662
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
663
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
664
+            ->setParameter('type', $objectType)
665
+            ->setParameter('id', $objectId);
666
+
667
+        if (!is_null($notOlderThan)) {
668
+            $query
669
+                ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
670
+                ->setParameter('notOlderThan', $notOlderThan, 'datetime');
671
+        }
672
+
673
+        if ($verb !== '') {
674
+            $query->andWhere($qb->expr()->eq('verb', $qb->createNamedParameter($verb)));
675
+        }
676
+
677
+        $resultStatement = $query->execute();
678
+        $data = $resultStatement->fetch(\PDO::FETCH_NUM);
679
+        $resultStatement->closeCursor();
680
+        return (int)$data[0];
681
+    }
682
+
683
+    /**
684
+     * @param string $objectType the object type, e.g. 'files'
685
+     * @param string[] $objectIds the id of the object
686
+     * @param IUser $user
687
+     * @param string $verb Limit the verb of the comment - Added in 14.0.0
688
+     * @return array Map with object id => # of unread comments
689
+     * @psalm-return array<string, int>
690
+     * @since 21.0.0
691
+     */
692
+    public function getNumberOfUnreadCommentsForObjects(string $objectType, array $objectIds, IUser $user, $verb = ''): array {
693
+        $unreadComments = [];
694
+        $query = $this->dbConn->getQueryBuilder();
695
+        $query->select('c.object_id', $query->func()->count('c.id', 'num_comments'))
696
+            ->from('comments', 'c')
697
+            ->leftJoin('c', 'comments_read_markers', 'm', $query->expr()->andX(
698
+                $query->expr()->eq('m.user_id', $query->createNamedParameter($user->getUID())),
699
+                $query->expr()->eq('c.object_type', 'm.object_type'),
700
+                $query->expr()->eq('c.object_id', 'm.object_id')
701
+            ))
702
+            ->where($query->expr()->eq('c.object_type', $query->createNamedParameter($objectType)))
703
+            ->andWhere($query->expr()->in('c.object_id', $query->createParameter('ids')))
704
+            ->andWhere($query->expr()->orX(
705
+                $query->expr()->gt('c.creation_timestamp', 'm.marker_datetime'),
706
+                $query->expr()->isNull('m.marker_datetime')
707
+            ))
708
+            ->groupBy('c.object_id');
709
+
710
+        if ($verb !== '') {
711
+            $query->andWhere($query->expr()->eq('c.verb', $query->createNamedParameter($verb)));
712
+        }
713
+
714
+        $unreadComments = array_fill_keys($objectIds, 0);
715
+        foreach (array_chunk($objectIds, 1000) as $chunk) {
716
+            $query->setParameter('ids', $chunk, IQueryBuilder::PARAM_STR_ARRAY);
717
+
718
+            $result = $query->executeQuery();
719
+            while ($row = $result->fetch()) {
720
+                $unreadComments[$row['object_id']] = (int) $row['num_comments'];
721
+            }
722
+            $result->closeCursor();
723
+        }
724
+
725
+        return $unreadComments;
726
+    }
727
+
728
+    /**
729
+     * @param string $objectType
730
+     * @param string $objectId
731
+     * @param int $lastRead
732
+     * @param string $verb
733
+     * @return int
734
+     * @since 21.0.0
735
+     */
736
+    public function getNumberOfCommentsForObjectSinceComment(string $objectType, string $objectId, int $lastRead, string $verb = ''): int {
737
+        if ($verb !== '') {
738
+            return $this->getNumberOfCommentsWithVerbsForObjectSinceComment($objectType, $objectId, $lastRead, [$verb]);
739
+        }
740
+
741
+        return $this->getNumberOfCommentsWithVerbsForObjectSinceComment($objectType, $objectId, $lastRead, []);
742
+    }
743
+
744
+    /**
745
+     * @param string $objectType
746
+     * @param string $objectId
747
+     * @param int $lastRead
748
+     * @param string[] $verbs
749
+     * @return int
750
+     * @since 24.0.0
751
+     */
752
+    public function getNumberOfCommentsWithVerbsForObjectSinceComment(string $objectType, string $objectId, int $lastRead, array $verbs): int {
753
+        $query = $this->dbConn->getQueryBuilder();
754
+        $query->select($query->func()->count('id', 'num_messages'))
755
+            ->from('comments')
756
+            ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
757
+            ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
758
+            ->andWhere($query->expr()->gt('id', $query->createNamedParameter($lastRead)));
759
+
760
+        if (!empty($verbs)) {
761
+            $query->andWhere($query->expr()->in('verb', $query->createNamedParameter($verbs, IQueryBuilder::PARAM_STR_ARRAY)));
762
+        }
763
+
764
+        $result = $query->executeQuery();
765
+        $data = $result->fetch();
766
+        $result->closeCursor();
767
+
768
+        return (int) ($data['num_messages'] ?? 0);
769
+    }
770
+
771
+    /**
772
+     * @param string $objectType
773
+     * @param string $objectId
774
+     * @param \DateTime $beforeDate
775
+     * @param string $verb
776
+     * @return int
777
+     * @since 21.0.0
778
+     */
779
+    public function getLastCommentBeforeDate(string $objectType, string $objectId, \DateTime $beforeDate, string $verb = ''): int {
780
+        $query = $this->dbConn->getQueryBuilder();
781
+        $query->select('id')
782
+            ->from('comments')
783
+            ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
784
+            ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
785
+            ->andWhere($query->expr()->lt('creation_timestamp', $query->createNamedParameter($beforeDate, IQueryBuilder::PARAM_DATE)))
786
+            ->orderBy('creation_timestamp', 'desc');
787
+
788
+        if ($verb !== '') {
789
+            $query->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)));
790
+        }
791
+
792
+        $result = $query->execute();
793
+        $data = $result->fetch();
794
+        $result->closeCursor();
795
+
796
+        return (int) ($data['id'] ?? 0);
797
+    }
798
+
799
+    /**
800
+     * @param string $objectType
801
+     * @param string $objectId
802
+     * @param string $verb
803
+     * @param string $actorType
804
+     * @param string[] $actors
805
+     * @return \DateTime[] Map of "string actor" => "\DateTime most recent comment date"
806
+     * @psalm-return array<string, \DateTime>
807
+     * @since 21.0.0
808
+     */
809
+    public function getLastCommentDateByActor(
810
+        string $objectType,
811
+        string $objectId,
812
+        string $verb,
813
+        string $actorType,
814
+        array $actors
815
+    ): array {
816
+        $lastComments = [];
817
+
818
+        $query = $this->dbConn->getQueryBuilder();
819
+        $query->select('actor_id')
820
+            ->selectAlias($query->createFunction('MAX(' . $query->getColumnName('creation_timestamp') . ')'), 'last_comment')
821
+            ->from('comments')
822
+            ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
823
+            ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
824
+            ->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)))
825
+            ->andWhere($query->expr()->eq('actor_type', $query->createNamedParameter($actorType)))
826
+            ->andWhere($query->expr()->in('actor_id', $query->createNamedParameter($actors, IQueryBuilder::PARAM_STR_ARRAY)))
827
+            ->groupBy('actor_id');
828
+
829
+        $result = $query->execute();
830
+        while ($row = $result->fetch()) {
831
+            $lastComments[$row['actor_id']] = $this->timeFactory->getDateTime($row['last_comment']);
832
+        }
833
+        $result->closeCursor();
834
+
835
+        return $lastComments;
836
+    }
837
+
838
+    /**
839
+     * Get the number of unread comments for all files in a folder
840
+     *
841
+     * @param int $folderId
842
+     * @param IUser $user
843
+     * @return array [$fileId => $unreadCount]
844
+     */
845
+    public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
846
+        $qb = $this->dbConn->getQueryBuilder();
847
+
848
+        $query = $qb->select('f.fileid')
849
+            ->addSelect($qb->func()->count('c.id', 'num_ids'))
850
+            ->from('filecache', 'f')
851
+            ->leftJoin('f', 'comments', 'c', $qb->expr()->andX(
852
+                $qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT)),
853
+                $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files'))
854
+            ))
855
+            ->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX(
856
+                $qb->expr()->eq('c.object_id', 'm.object_id'),
857
+                $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files'))
858
+            ))
859
+            ->where(
860
+                $qb->expr()->andX(
861
+                    $qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId)),
862
+                    $qb->expr()->orX(
863
+                        $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
864
+                        $qb->expr()->isNull('c.object_type')
865
+                    ),
866
+                    $qb->expr()->orX(
867
+                        $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')),
868
+                        $qb->expr()->isNull('m.object_type')
869
+                    ),
870
+                    $qb->expr()->orX(
871
+                        $qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID())),
872
+                        $qb->expr()->isNull('m.user_id')
873
+                    ),
874
+                    $qb->expr()->orX(
875
+                        $qb->expr()->gt('c.creation_timestamp', 'm.marker_datetime'),
876
+                        $qb->expr()->isNull('m.marker_datetime')
877
+                    )
878
+                )
879
+            )->groupBy('f.fileid');
880
+
881
+        $resultStatement = $query->execute();
882
+
883
+        $results = [];
884
+        while ($row = $resultStatement->fetch()) {
885
+            $results[$row['fileid']] = (int) $row['num_ids'];
886
+        }
887
+        $resultStatement->closeCursor();
888
+        return $results;
889
+    }
890
+
891
+    /**
892
+     * creates a new comment and returns it. At this point of time, it is not
893
+     * saved in the used data storage. Use save() after setting other fields
894
+     * of the comment (e.g. message or verb).
895
+     *
896
+     * @param string $actorType the actor type (e.g. 'users')
897
+     * @param string $actorId a user id
898
+     * @param string $objectType the object type the comment is attached to
899
+     * @param string $objectId the object id the comment is attached to
900
+     * @return IComment
901
+     * @since 9.0.0
902
+     */
903
+    public function create($actorType, $actorId, $objectType, $objectId) {
904
+        $comment = new Comment();
905
+        $comment
906
+            ->setActor($actorType, $actorId)
907
+            ->setObject($objectType, $objectId);
908
+        return $comment;
909
+    }
910
+
911
+    /**
912
+     * permanently deletes the comment specified by the ID
913
+     *
914
+     * When the comment has child comments, their parent ID will be changed to
915
+     * the parent ID of the item that is to be deleted.
916
+     *
917
+     * @param string $id
918
+     * @return bool
919
+     * @throws \InvalidArgumentException
920
+     * @since 9.0.0
921
+     */
922
+    public function delete($id) {
923
+        if (!is_string($id)) {
924
+            throw new \InvalidArgumentException('Parameter must be string');
925
+        }
926
+
927
+        try {
928
+            $comment = $this->get($id);
929
+        } catch (\Exception $e) {
930
+            // Ignore exceptions, we just don't fire a hook then
931
+            $comment = null;
932
+        }
933
+
934
+        $qb = $this->dbConn->getQueryBuilder();
935
+        $query = $qb->delete('comments')
936
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
937
+            ->setParameter('id', $id);
938
+
939
+        try {
940
+            $affectedRows = $query->execute();
941
+            $this->uncache($id);
942
+        } catch (DriverException $e) {
943
+            $this->logger->error($e->getMessage(), [
944
+                'exception' => $e,
945
+                'app' => 'core_comments',
946
+            ]);
947
+            return false;
948
+        }
949
+
950
+        if ($affectedRows > 0 && $comment instanceof IComment) {
951
+            if ($comment->getVerb() === 'reaction_deleted') {
952
+                $this->deleteReaction($comment);
953
+            }
954
+            $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
955
+        }
956
+
957
+        return ($affectedRows > 0);
958
+    }
959
+
960
+    private function deleteReaction(IComment $reaction): void {
961
+        $qb = $this->dbConn->getQueryBuilder();
962
+        $qb->delete('reactions')
963
+            ->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($reaction->getParentId())))
964
+            ->andWhere($qb->expr()->eq('message_id', $qb->createNamedParameter($reaction->getId())))
965
+            ->executeStatement();
966
+        $this->sumReactions($reaction->getParentId());
967
+    }
968
+
969
+    /**
970
+     * Get comment related with user reaction
971
+     *
972
+     * Throws PreConditionNotMetException when the system haven't the minimum requirements to
973
+     * use reactions
974
+     *
975
+     * @param int $parentId
976
+     * @param string $actorType
977
+     * @param string $actorId
978
+     * @param string $reaction
979
+     * @return IComment
980
+     * @throws NotFoundException
981
+     * @throws PreConditionNotMetException
982
+     * @since 24.0.0
983
+     */
984
+    public function getReactionComment(int $parentId, string $actorType, string $actorId, string $reaction): IComment {
985
+        $this->throwIfNotSupportReactions();
986
+        $qb = $this->dbConn->getQueryBuilder();
987
+        $messageId = $qb
988
+            ->select('message_id')
989
+            ->from('reactions')
990
+            ->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($parentId)))
991
+            ->andWhere($qb->expr()->eq('actor_type', $qb->createNamedParameter($actorType)))
992
+            ->andWhere($qb->expr()->eq('actor_id', $qb->createNamedParameter($actorId)))
993
+            ->andWhere($qb->expr()->eq('reaction', $qb->createNamedParameter($reaction)))
994
+            ->executeQuery()
995
+            ->fetchOne();
996
+        if (!$messageId) {
997
+            throw new NotFoundException('Comment related with reaction not found');
998
+        }
999
+        return $this->get($messageId);
1000
+    }
1001
+
1002
+    /**
1003
+     * Retrieve all reactions of a message
1004
+     *
1005
+     * Throws PreConditionNotMetException when the system haven't the minimum requirements to
1006
+     * use reactions
1007
+     *
1008
+     * @param int $parentId
1009
+     * @return IComment[]
1010
+     * @throws PreConditionNotMetException
1011
+     * @since 24.0.0
1012
+     */
1013
+    public function retrieveAllReactions(int $parentId): array {
1014
+        $this->throwIfNotSupportReactions();
1015
+        $qb = $this->dbConn->getQueryBuilder();
1016
+        $result = $qb
1017
+            ->select('message_id')
1018
+            ->from('reactions')
1019
+            ->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($parentId)))
1020
+            ->executeQuery();
1021
+
1022
+        $commentIds = [];
1023
+        while ($data = $result->fetch()) {
1024
+            $commentIds[] = $data['message_id'];
1025
+        }
1026
+
1027
+        return $this->getCommentsById($commentIds);
1028
+    }
1029
+
1030
+    /**
1031
+     * Retrieve all reactions with specific reaction of a message
1032
+     *
1033
+     * Throws PreConditionNotMetException when the system haven't the minimum requirements to
1034
+     * use reactions
1035
+     *
1036
+     * @param int $parentId
1037
+     * @param string $reaction
1038
+     * @return IComment[]
1039
+     * @throws PreConditionNotMetException
1040
+     * @since 24.0.0
1041
+     */
1042
+    public function retrieveAllReactionsWithSpecificReaction(int $parentId, string $reaction): array {
1043
+        $this->throwIfNotSupportReactions();
1044
+        $qb = $this->dbConn->getQueryBuilder();
1045
+        $result = $qb
1046
+            ->select('message_id')
1047
+            ->from('reactions')
1048
+            ->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($parentId)))
1049
+            ->andWhere($qb->expr()->eq('reaction', $qb->createNamedParameter($reaction)))
1050
+            ->executeQuery();
1051
+
1052
+        $commentIds = [];
1053
+        while ($data = $result->fetch()) {
1054
+            $commentIds[] = $data['message_id'];
1055
+        }
1056
+        $comments = [];
1057
+        if ($commentIds) {
1058
+            $comments = $this->getCommentsById($commentIds);
1059
+        }
1060
+
1061
+        return $comments;
1062
+    }
1063
+
1064
+    /**
1065
+     * Support reactions
1066
+     *
1067
+     * @return bool
1068
+     * @since 24.0.0
1069
+     */
1070
+    public function supportReactions(): bool {
1071
+        return $this->dbConn->supports4ByteText();
1072
+    }
1073
+
1074
+    /**
1075
+     * @throws PreConditionNotMetException
1076
+     * @since 24.0.0
1077
+     */
1078
+    private function throwIfNotSupportReactions() {
1079
+        if (!$this->supportReactions()) {
1080
+            throw new PreConditionNotMetException('The database does not support reactions');
1081
+        }
1082
+    }
1083
+
1084
+    /**
1085
+     * Get all comments on list
1086
+     *
1087
+     * @param int[] $commentIds
1088
+     * @return IComment[]
1089
+     * @since 24.0.0
1090
+     */
1091
+    private function getCommentsById(array $commentIds): array {
1092
+        if (!$commentIds) {
1093
+            return [];
1094
+        }
1095
+        $query = $this->dbConn->getQueryBuilder();
1096
+
1097
+        $query->select('*')
1098
+            ->from('comments')
1099
+            ->where($query->expr()->in('id', $query->createNamedParameter($commentIds, IQueryBuilder::PARAM_STR_ARRAY)))
1100
+            ->orderBy('creation_timestamp', 'DESC')
1101
+            ->addOrderBy('id', 'DESC');
1102
+
1103
+        $comments = [];
1104
+        $result = $query->executeQuery();
1105
+        while ($data = $result->fetch()) {
1106
+            $comment = $this->getCommentFromData($data);
1107
+            $this->cache($comment);
1108
+            $comments[] = $comment;
1109
+        }
1110
+        $result->closeCursor();
1111
+        return $comments;
1112
+    }
1113
+
1114
+    /**
1115
+     * saves the comment permanently
1116
+     *
1117
+     * if the supplied comment has an empty ID, a new entry comment will be
1118
+     * saved and the instance updated with the new ID.
1119
+     *
1120
+     * Otherwise, an existing comment will be updated.
1121
+     *
1122
+     * Throws NotFoundException when a comment that is to be updated does not
1123
+     * exist anymore at this point of time.
1124
+     *
1125
+     * Throws PreConditionNotMetException when the system haven't the minimum requirements to
1126
+     * use reactions
1127
+     *
1128
+     * @param IComment $comment
1129
+     * @return bool
1130
+     * @throws NotFoundException
1131
+     * @throws PreConditionNotMetException
1132
+     * @since 9.0.0
1133
+     */
1134
+    public function save(IComment $comment) {
1135
+        if ($comment->getVerb() === 'reaction') {
1136
+            $this->throwIfNotSupportReactions();
1137
+        }
1138
+
1139
+        if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
1140
+            $result = $this->insert($comment);
1141
+        } else {
1142
+            $result = $this->update($comment);
1143
+        }
1144
+
1145
+        if ($result && !!$comment->getParentId()) {
1146
+            $this->updateChildrenInformation(
1147
+                $comment->getParentId(),
1148
+                $comment->getCreationDateTime()
1149
+            );
1150
+            $this->cache($comment);
1151
+        }
1152
+
1153
+        return $result;
1154
+    }
1155
+
1156
+    /**
1157
+     * inserts the provided comment in the database
1158
+     *
1159
+     * @param IComment $comment
1160
+     * @return bool
1161
+     */
1162
+    protected function insert(IComment $comment): bool {
1163
+        try {
1164
+            $result = $this->insertQuery($comment, true);
1165
+        } catch (InvalidFieldNameException $e) {
1166
+            // The reference id field was only added in Nextcloud 19.
1167
+            // In order to not cause too long waiting times on the update,
1168
+            // it was decided to only add it lazy, as it is also not a critical
1169
+            // feature, but only helps to have a better experience while commenting.
1170
+            // So in case the reference_id field is missing,
1171
+            // we simply save the comment without that field.
1172
+            $result = $this->insertQuery($comment, false);
1173
+        }
1174
+
1175
+        return $result;
1176
+    }
1177
+
1178
+    protected function insertQuery(IComment $comment, bool $tryWritingReferenceId): bool {
1179
+        $qb = $this->dbConn->getQueryBuilder();
1180
+
1181
+        $values = [
1182
+            'parent_id' => $qb->createNamedParameter($comment->getParentId()),
1183
+            'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
1184
+            'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
1185
+            'actor_type' => $qb->createNamedParameter($comment->getActorType()),
1186
+            'actor_id' => $qb->createNamedParameter($comment->getActorId()),
1187
+            'message' => $qb->createNamedParameter($comment->getMessage()),
1188
+            'verb' => $qb->createNamedParameter($comment->getVerb()),
1189
+            'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
1190
+            'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
1191
+            'object_type' => $qb->createNamedParameter($comment->getObjectType()),
1192
+            'object_id' => $qb->createNamedParameter($comment->getObjectId()),
1193
+        ];
1194
+
1195
+        if ($tryWritingReferenceId) {
1196
+            $values['reference_id'] = $qb->createNamedParameter($comment->getReferenceId());
1197
+        }
1198
+
1199
+        $affectedRows = $qb->insert('comments')
1200
+            ->values($values)
1201
+            ->execute();
1202
+
1203
+        if ($affectedRows > 0) {
1204
+            $comment->setId((string)$qb->getLastInsertId());
1205
+            if ($comment->getVerb() === 'reaction') {
1206
+                $this->addReaction($comment);
1207
+            }
1208
+            $this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
1209
+        }
1210
+
1211
+        return $affectedRows > 0;
1212
+    }
1213
+
1214
+    private function addReaction(IComment $reaction): void {
1215
+        // Prevent violate constraint
1216
+        $qb = $this->dbConn->getQueryBuilder();
1217
+        $qb->select($qb->func()->count('*'))
1218
+            ->from('reactions')
1219
+            ->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($reaction->getParentId())))
1220
+            ->andWhere($qb->expr()->eq('actor_type', $qb->createNamedParameter($reaction->getActorType())))
1221
+            ->andWhere($qb->expr()->eq('actor_id', $qb->createNamedParameter($reaction->getActorId())))
1222
+            ->andWhere($qb->expr()->eq('reaction', $qb->createNamedParameter($reaction->getMessage())));
1223
+        $result = $qb->executeQuery();
1224
+        $exists = (int) $result->fetchOne();
1225
+        if (!$exists) {
1226
+            $qb = $this->dbConn->getQueryBuilder();
1227
+            try {
1228
+                $qb->insert('reactions')
1229
+                    ->values([
1230
+                        'parent_id' => $qb->createNamedParameter($reaction->getParentId()),
1231
+                        'message_id' => $qb->createNamedParameter($reaction->getId()),
1232
+                        'actor_type' => $qb->createNamedParameter($reaction->getActorType()),
1233
+                        'actor_id' => $qb->createNamedParameter($reaction->getActorId()),
1234
+                        'reaction' => $qb->createNamedParameter($reaction->getMessage()),
1235
+                    ])
1236
+                    ->executeStatement();
1237
+            } catch (\Exception $e) {
1238
+                $this->logger->error($e->getMessage(), [
1239
+                    'exception' => $e,
1240
+                    'app' => 'core_comments',
1241
+                ]);
1242
+            }
1243
+        }
1244
+        $this->sumReactions($reaction->getParentId());
1245
+    }
1246
+
1247
+    private function sumReactions(string $parentId): void {
1248
+        $qb = $this->dbConn->getQueryBuilder();
1249
+
1250
+        $totalQuery = $this->dbConn->getQueryBuilder();
1251
+        $totalQuery
1252
+            ->selectAlias(
1253
+                $totalQuery->func()->concat(
1254
+                    $totalQuery->expr()->literal('"'),
1255
+                    'reaction',
1256
+                    $totalQuery->expr()->literal('":'),
1257
+                    $totalQuery->func()->count('id')
1258
+                ),
1259
+                'colonseparatedvalue'
1260
+            )
1261
+            ->selectAlias($totalQuery->func()->count('id'), 'total')
1262
+            ->from('reactions', 'r')
1263
+            ->where($totalQuery->expr()->eq('r.parent_id', $qb->createNamedParameter($parentId)))
1264
+            ->groupBy('r.reaction')
1265
+            ->orderBy('total', 'DESC')
1266
+            ->setMaxResults(20);
1267
+
1268
+        $jsonQuery = $this->dbConn->getQueryBuilder();
1269
+        $jsonQuery
1270
+            ->selectAlias(
1271
+                $jsonQuery->func()->concat(
1272
+                    $jsonQuery->expr()->literal('{'),
1273
+                    $jsonQuery->func()->groupConcat('colonseparatedvalue'),
1274
+                    $jsonQuery->expr()->literal('}')
1275
+                ),
1276
+                'json'
1277
+            )
1278
+            ->from($jsonQuery->createFunction('(' . $totalQuery->getSQL() . ')'), 'json');
1279
+
1280
+        $qb
1281
+            ->update('comments')
1282
+            ->set('reactions', $jsonQuery->createFunction('(' . $jsonQuery->getSQL() . ')'))
1283
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($parentId)))
1284
+            ->executeStatement();
1285
+    }
1286
+
1287
+    /**
1288
+     * updates a Comment data row
1289
+     *
1290
+     * @param IComment $comment
1291
+     * @return bool
1292
+     * @throws NotFoundException
1293
+     */
1294
+    protected function update(IComment $comment) {
1295
+        // for properly working preUpdate Events we need the old comments as is
1296
+        // in the DB and overcome caching. Also avoid that outdated information stays.
1297
+        $this->uncache($comment->getId());
1298
+        $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
1299
+        $this->uncache($comment->getId());
1300
+
1301
+        try {
1302
+            $result = $this->updateQuery($comment, true);
1303
+        } catch (InvalidFieldNameException $e) {
1304
+            // See function insert() for explanation
1305
+            $result = $this->updateQuery($comment, false);
1306
+        }
1307
+
1308
+        if ($comment->getVerb() === 'reaction_deleted') {
1309
+            $this->deleteReaction($comment);
1310
+        }
1311
+
1312
+        $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
1313
+
1314
+        return $result;
1315
+    }
1316
+
1317
+    protected function updateQuery(IComment $comment, bool $tryWritingReferenceId): bool {
1318
+        $qb = $this->dbConn->getQueryBuilder();
1319
+        $qb
1320
+            ->update('comments')
1321
+            ->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
1322
+            ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
1323
+            ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
1324
+            ->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
1325
+            ->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
1326
+            ->set('message', $qb->createNamedParameter($comment->getMessage()))
1327
+            ->set('verb', $qb->createNamedParameter($comment->getVerb()))
1328
+            ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
1329
+            ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
1330
+            ->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
1331
+            ->set('object_id', $qb->createNamedParameter($comment->getObjectId()));
1332
+
1333
+        if ($tryWritingReferenceId) {
1334
+            $qb->set('reference_id', $qb->createNamedParameter($comment->getReferenceId()));
1335
+        }
1336
+
1337
+        $affectedRows = $qb->where($qb->expr()->eq('id', $qb->createNamedParameter($comment->getId())))
1338
+            ->execute();
1339
+
1340
+        if ($affectedRows === 0) {
1341
+            throw new NotFoundException('Comment to update does ceased to exist');
1342
+        }
1343
+
1344
+        return $affectedRows > 0;
1345
+    }
1346
+
1347
+    /**
1348
+     * removes references to specific actor (e.g. on user delete) of a comment.
1349
+     * The comment itself must not get lost/deleted.
1350
+     *
1351
+     * @param string $actorType the actor type (e.g. 'users')
1352
+     * @param string $actorId a user id
1353
+     * @return boolean
1354
+     * @since 9.0.0
1355
+     */
1356
+    public function deleteReferencesOfActor($actorType, $actorId) {
1357
+        $this->checkRoleParameters('Actor', $actorType, $actorId);
1358
+
1359
+        $qb = $this->dbConn->getQueryBuilder();
1360
+        $affectedRows = $qb
1361
+            ->update('comments')
1362
+            ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
1363
+            ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
1364
+            ->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
1365
+            ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
1366
+            ->setParameter('type', $actorType)
1367
+            ->setParameter('id', $actorId)
1368
+            ->execute();
1369
+
1370
+        $this->commentsCache = [];
1371
+
1372
+        return is_int($affectedRows);
1373
+    }
1374
+
1375
+    /**
1376
+     * deletes all comments made of a specific object (e.g. on file delete)
1377
+     *
1378
+     * @param string $objectType the object type (e.g. 'files')
1379
+     * @param string $objectId e.g. the file id
1380
+     * @return boolean
1381
+     * @since 9.0.0
1382
+     */
1383
+    public function deleteCommentsAtObject($objectType, $objectId) {
1384
+        $this->checkRoleParameters('Object', $objectType, $objectId);
1385
+
1386
+        $qb = $this->dbConn->getQueryBuilder();
1387
+        $affectedRows = $qb
1388
+            ->delete('comments')
1389
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
1390
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
1391
+            ->setParameter('type', $objectType)
1392
+            ->setParameter('id', $objectId)
1393
+            ->execute();
1394
+
1395
+        $this->commentsCache = [];
1396
+
1397
+        return is_int($affectedRows);
1398
+    }
1399
+
1400
+    /**
1401
+     * deletes the read markers for the specified user
1402
+     *
1403
+     * @param \OCP\IUser $user
1404
+     * @return bool
1405
+     * @since 9.0.0
1406
+     */
1407
+    public function deleteReadMarksFromUser(IUser $user) {
1408
+        $qb = $this->dbConn->getQueryBuilder();
1409
+        $query = $qb->delete('comments_read_markers')
1410
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
1411
+            ->setParameter('user_id', $user->getUID());
1412
+
1413
+        try {
1414
+            $affectedRows = $query->execute();
1415
+        } catch (DriverException $e) {
1416
+            $this->logger->error($e->getMessage(), [
1417
+                'exception' => $e,
1418
+                'app' => 'core_comments',
1419
+            ]);
1420
+            return false;
1421
+        }
1422
+        return ($affectedRows > 0);
1423
+    }
1424
+
1425
+    /**
1426
+     * sets the read marker for a given file to the specified date for the
1427
+     * provided user
1428
+     *
1429
+     * @param string $objectType
1430
+     * @param string $objectId
1431
+     * @param \DateTime $dateTime
1432
+     * @param IUser $user
1433
+     * @since 9.0.0
1434
+     */
1435
+    public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
1436
+        $this->checkRoleParameters('Object', $objectType, $objectId);
1437
+
1438
+        $qb = $this->dbConn->getQueryBuilder();
1439
+        $values = [
1440
+            'user_id' => $qb->createNamedParameter($user->getUID()),
1441
+            'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
1442
+            'object_type' => $qb->createNamedParameter($objectType),
1443
+            'object_id' => $qb->createNamedParameter($objectId),
1444
+        ];
1445
+
1446
+        // Strategy: try to update, if this does not return affected rows, do an insert.
1447
+        $affectedRows = $qb
1448
+            ->update('comments_read_markers')
1449
+            ->set('user_id', $values['user_id'])
1450
+            ->set('marker_datetime', $values['marker_datetime'])
1451
+            ->set('object_type', $values['object_type'])
1452
+            ->set('object_id', $values['object_id'])
1453
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
1454
+            ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
1455
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
1456
+            ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
1457
+            ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
1458
+            ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
1459
+            ->execute();
1460
+
1461
+        if ($affectedRows > 0) {
1462
+            return;
1463
+        }
1464
+
1465
+        $qb->insert('comments_read_markers')
1466
+            ->values($values)
1467
+            ->execute();
1468
+    }
1469
+
1470
+    /**
1471
+     * returns the read marker for a given file to the specified date for the
1472
+     * provided user. It returns null, when the marker is not present, i.e.
1473
+     * no comments were marked as read.
1474
+     *
1475
+     * @param string $objectType
1476
+     * @param string $objectId
1477
+     * @param IUser $user
1478
+     * @return \DateTime|null
1479
+     * @since 9.0.0
1480
+     */
1481
+    public function getReadMark($objectType, $objectId, IUser $user) {
1482
+        $qb = $this->dbConn->getQueryBuilder();
1483
+        $resultStatement = $qb->select('marker_datetime')
1484
+            ->from('comments_read_markers')
1485
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
1486
+            ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
1487
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
1488
+            ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
1489
+            ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
1490
+            ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
1491
+            ->execute();
1492
+
1493
+        $data = $resultStatement->fetch();
1494
+        $resultStatement->closeCursor();
1495
+        if (!$data || is_null($data['marker_datetime'])) {
1496
+            return null;
1497
+        }
1498
+
1499
+        return new \DateTime($data['marker_datetime']);
1500
+    }
1501
+
1502
+    /**
1503
+     * deletes the read markers on the specified object
1504
+     *
1505
+     * @param string $objectType
1506
+     * @param string $objectId
1507
+     * @return bool
1508
+     * @since 9.0.0
1509
+     */
1510
+    public function deleteReadMarksOnObject($objectType, $objectId) {
1511
+        $this->checkRoleParameters('Object', $objectType, $objectId);
1512
+
1513
+        $qb = $this->dbConn->getQueryBuilder();
1514
+        $query = $qb->delete('comments_read_markers')
1515
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
1516
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
1517
+            ->setParameter('object_type', $objectType)
1518
+            ->setParameter('object_id', $objectId);
1519
+
1520
+        try {
1521
+            $affectedRows = $query->execute();
1522
+        } catch (DriverException $e) {
1523
+            $this->logger->error($e->getMessage(), [
1524
+                'exception' => $e,
1525
+                'app' => 'core_comments',
1526
+            ]);
1527
+            return false;
1528
+        }
1529
+        return ($affectedRows > 0);
1530
+    }
1531
+
1532
+    /**
1533
+     * registers an Entity to the manager, so event notifications can be send
1534
+     * to consumers of the comments infrastructure
1535
+     *
1536
+     * @param \Closure $closure
1537
+     */
1538
+    public function registerEventHandler(\Closure $closure) {
1539
+        $this->eventHandlerClosures[] = $closure;
1540
+        $this->eventHandlers = [];
1541
+    }
1542
+
1543
+    /**
1544
+     * registers a method that resolves an ID to a display name for a given type
1545
+     *
1546
+     * @param string $type
1547
+     * @param \Closure $closure
1548
+     * @throws \OutOfBoundsException
1549
+     * @since 11.0.0
1550
+     *
1551
+     * Only one resolver shall be registered per type. Otherwise a
1552
+     * \OutOfBoundsException has to thrown.
1553
+     */
1554
+    public function registerDisplayNameResolver($type, \Closure $closure) {
1555
+        if (!is_string($type)) {
1556
+            throw new \InvalidArgumentException('String expected.');
1557
+        }
1558
+        if (isset($this->displayNameResolvers[$type])) {
1559
+            throw new \OutOfBoundsException('Displayname resolver for this type already registered');
1560
+        }
1561
+        $this->displayNameResolvers[$type] = $closure;
1562
+    }
1563
+
1564
+    /**
1565
+     * resolves a given ID of a given Type to a display name.
1566
+     *
1567
+     * @param string $type
1568
+     * @param string $id
1569
+     * @return string
1570
+     * @throws \OutOfBoundsException
1571
+     * @since 11.0.0
1572
+     *
1573
+     * If a provided type was not registered, an \OutOfBoundsException shall
1574
+     * be thrown. It is upon the resolver discretion what to return of the
1575
+     * provided ID is unknown. It must be ensured that a string is returned.
1576
+     */
1577
+    public function resolveDisplayName($type, $id) {
1578
+        if (!is_string($type)) {
1579
+            throw new \InvalidArgumentException('String expected.');
1580
+        }
1581
+        if (!isset($this->displayNameResolvers[$type])) {
1582
+            throw new \OutOfBoundsException('No Displayname resolver for this type registered');
1583
+        }
1584
+        return (string)$this->displayNameResolvers[$type]($id);
1585
+    }
1586
+
1587
+    /**
1588
+     * returns valid, registered entities
1589
+     *
1590
+     * @return \OCP\Comments\ICommentsEventHandler[]
1591
+     */
1592
+    private function getEventHandlers() {
1593
+        if (!empty($this->eventHandlers)) {
1594
+            return $this->eventHandlers;
1595
+        }
1596
+
1597
+        $this->eventHandlers = [];
1598
+        foreach ($this->eventHandlerClosures as $name => $closure) {
1599
+            $entity = $closure();
1600
+            if (!($entity instanceof ICommentsEventHandler)) {
1601
+                throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
1602
+            }
1603
+            $this->eventHandlers[$name] = $entity;
1604
+        }
1605
+
1606
+        return $this->eventHandlers;
1607
+    }
1608
+
1609
+    /**
1610
+     * sends notifications to the registered entities
1611
+     *
1612
+     * @param $eventType
1613
+     * @param IComment $comment
1614
+     */
1615
+    private function sendEvent($eventType, IComment $comment) {
1616
+        $entities = $this->getEventHandlers();
1617
+        $event = new CommentsEvent($eventType, $comment);
1618
+        foreach ($entities as $entity) {
1619
+            $entity->handle($event);
1620
+        }
1621
+    }
1622
+
1623
+    /**
1624
+     * Load the Comments app into the page
1625
+     *
1626
+     * @since 21.0.0
1627
+     */
1628
+    public function load(): void {
1629
+        $this->initialStateService->provideInitialState('comments', 'max-message-length', IComment::MAX_MESSAGE_LENGTH);
1630
+        Util::addScript('comments', 'comments-app');
1631
+    }
1632 1632
 }
Please login to merge, or discard this patch.