Completed
Pull Request — master (#4146)
by Robin
15:10
created
lib/private/Comments/Manager.php 3 patches
Unused Use Statements   -3 removed lines patch added patch discarded remove patch
@@ -25,9 +25,6 @@
 block discarded – undo
25 25
 namespace OC\Comments;
26 26
 
27 27
 use Doctrine\DBAL\Exception\DriverException;
28
-use OC\DB\QueryBuilder\Literal;
29
-use OC\DB\QueryBuilder\QueryBuilder;
30
-use OC\DB\QueryBuilder\QueryFunction;
31 28
 use OCP\Comments\CommentsEvent;
32 29
 use OCP\Comments\IComment;
33 30
 use OCP\Comments\ICommentsEventHandler;
Please login to merge, or discard this patch.
Indentation   +838 added lines, -838 removed lines patch added patch discarded remove patch
@@ -41,842 +41,842 @@
 block discarded – undo
41 41
 
42 42
 class Manager implements ICommentsManager {
43 43
 
44
-	/** @var  IDBConnection */
45
-	protected $dbConn;
46
-
47
-	/** @var  ILogger */
48
-	protected $logger;
49
-
50
-	/** @var IConfig */
51
-	protected $config;
52
-
53
-	/** @var IComment[] */
54
-	protected $commentsCache = [];
55
-
56
-	/** @var  \Closure[] */
57
-	protected $eventHandlerClosures = [];
58
-
59
-	/** @var  ICommentsEventHandler[] */
60
-	protected $eventHandlers = [];
61
-
62
-	/** @var \Closure[] */
63
-	protected $displayNameResolvers = [];
64
-
65
-	/**
66
-	 * Manager constructor.
67
-	 *
68
-	 * @param IDBConnection $dbConn
69
-	 * @param ILogger $logger
70
-	 * @param IConfig $config
71
-	 */
72
-	public function __construct(
73
-		IDBConnection $dbConn,
74
-		ILogger $logger,
75
-		IConfig $config
76
-	) {
77
-		$this->dbConn = $dbConn;
78
-		$this->logger = $logger;
79
-		$this->config = $config;
80
-	}
81
-
82
-	/**
83
-	 * converts data base data into PHP native, proper types as defined by
84
-	 * IComment interface.
85
-	 *
86
-	 * @param array $data
87
-	 * @return array
88
-	 */
89
-	protected function normalizeDatabaseData(array $data) {
90
-		$data['id'] = strval($data['id']);
91
-		$data['parent_id'] = strval($data['parent_id']);
92
-		$data['topmost_parent_id'] = strval($data['topmost_parent_id']);
93
-		$data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
94
-		if (!is_null($data['latest_child_timestamp'])) {
95
-			$data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
96
-		}
97
-		$data['children_count'] = intval($data['children_count']);
98
-		return $data;
99
-	}
100
-
101
-	/**
102
-	 * prepares a comment for an insert or update operation after making sure
103
-	 * all necessary fields have a value assigned.
104
-	 *
105
-	 * @param IComment $comment
106
-	 * @return IComment returns the same updated IComment instance as provided
107
-	 *                  by parameter for convenience
108
-	 * @throws \UnexpectedValueException
109
-	 */
110
-	protected function prepareCommentForDatabaseWrite(IComment $comment) {
111
-		if (!$comment->getActorType()
112
-			|| !$comment->getActorId()
113
-			|| !$comment->getObjectType()
114
-			|| !$comment->getObjectId()
115
-			|| !$comment->getVerb()
116
-		) {
117
-			throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
118
-		}
119
-
120
-		if ($comment->getId() === '') {
121
-			$comment->setChildrenCount(0);
122
-			$comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
123
-			$comment->setLatestChildDateTime(null);
124
-		}
125
-
126
-		if (is_null($comment->getCreationDateTime())) {
127
-			$comment->setCreationDateTime(new \DateTime());
128
-		}
129
-
130
-		if ($comment->getParentId() !== '0') {
131
-			$comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
132
-		} else {
133
-			$comment->setTopmostParentId('0');
134
-		}
135
-
136
-		$this->cache($comment);
137
-
138
-		return $comment;
139
-	}
140
-
141
-	/**
142
-	 * returns the topmost parent id of a given comment identified by ID
143
-	 *
144
-	 * @param string $id
145
-	 * @return string
146
-	 * @throws NotFoundException
147
-	 */
148
-	protected function determineTopmostParentId($id) {
149
-		$comment = $this->get($id);
150
-		if ($comment->getParentId() === '0') {
151
-			return $comment->getId();
152
-		} else {
153
-			return $this->determineTopmostParentId($comment->getId());
154
-		}
155
-	}
156
-
157
-	/**
158
-	 * updates child information of a comment
159
-	 *
160
-	 * @param string $id
161
-	 * @param \DateTime $cDateTime the date time of the most recent child
162
-	 * @throws NotFoundException
163
-	 */
164
-	protected function updateChildrenInformation($id, \DateTime $cDateTime) {
165
-		$qb = $this->dbConn->getQueryBuilder();
166
-		$query = $qb->select($qb->createFunction('COUNT(`id`)'))
167
-			->from('comments')
168
-			->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
169
-			->setParameter('id', $id);
170
-
171
-		$resultStatement = $query->execute();
172
-		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
173
-		$resultStatement->closeCursor();
174
-		$children = intval($data[0]);
175
-
176
-		$comment = $this->get($id);
177
-		$comment->setChildrenCount($children);
178
-		$comment->setLatestChildDateTime($cDateTime);
179
-		$this->save($comment);
180
-	}
181
-
182
-	/**
183
-	 * Tests whether actor or object type and id parameters are acceptable.
184
-	 * Throws exception if not.
185
-	 *
186
-	 * @param string $role
187
-	 * @param string $type
188
-	 * @param string $id
189
-	 * @throws \InvalidArgumentException
190
-	 */
191
-	protected function checkRoleParameters($role, $type, $id) {
192
-		if (
193
-			!is_string($type) || empty($type)
194
-			|| !is_string($id) || empty($id)
195
-		) {
196
-			throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
197
-		}
198
-	}
199
-
200
-	/**
201
-	 * run-time caches a comment
202
-	 *
203
-	 * @param IComment $comment
204
-	 */
205
-	protected function cache(IComment $comment) {
206
-		$id = $comment->getId();
207
-		if (empty($id)) {
208
-			return;
209
-		}
210
-		$this->commentsCache[strval($id)] = $comment;
211
-	}
212
-
213
-	/**
214
-	 * removes an entry from the comments run time cache
215
-	 *
216
-	 * @param mixed $id the comment's id
217
-	 */
218
-	protected function uncache($id) {
219
-		$id = strval($id);
220
-		if (isset($this->commentsCache[$id])) {
221
-			unset($this->commentsCache[$id]);
222
-		}
223
-	}
224
-
225
-	/**
226
-	 * returns a comment instance
227
-	 *
228
-	 * @param string $id the ID of the comment
229
-	 * @return IComment
230
-	 * @throws NotFoundException
231
-	 * @throws \InvalidArgumentException
232
-	 * @since 9.0.0
233
-	 */
234
-	public function get($id) {
235
-		if (intval($id) === 0) {
236
-			throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
237
-		}
238
-
239
-		if (isset($this->commentsCache[$id])) {
240
-			return $this->commentsCache[$id];
241
-		}
242
-
243
-		$qb = $this->dbConn->getQueryBuilder();
244
-		$resultStatement = $qb->select('*')
245
-			->from('comments')
246
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
247
-			->setParameter('id', $id, IQueryBuilder::PARAM_INT)
248
-			->execute();
249
-
250
-		$data = $resultStatement->fetch();
251
-		$resultStatement->closeCursor();
252
-		if (!$data) {
253
-			throw new NotFoundException();
254
-		}
255
-
256
-		$comment = new Comment($this->normalizeDatabaseData($data));
257
-		$this->cache($comment);
258
-		return $comment;
259
-	}
260
-
261
-	/**
262
-	 * returns the comment specified by the id and all it's child comments.
263
-	 * At this point of time, we do only support one level depth.
264
-	 *
265
-	 * @param string $id
266
-	 * @param int $limit max number of entries to return, 0 returns all
267
-	 * @param int $offset the start entry
268
-	 * @return array
269
-	 * @since 9.0.0
270
-	 *
271
-	 * The return array looks like this
272
-	 * [
273
-	 *   'comment' => IComment, // root comment
274
-	 *   'replies' =>
275
-	 *   [
276
-	 *     0 =>
277
-	 *     [
278
-	 *       'comment' => IComment,
279
-	 *       'replies' => []
280
-	 *     ]
281
-	 *     1 =>
282
-	 *     [
283
-	 *       'comment' => IComment,
284
-	 *       'replies'=> []
285
-	 *     ],
286
-	 *     …
287
-	 *   ]
288
-	 * ]
289
-	 */
290
-	public function getTree($id, $limit = 0, $offset = 0) {
291
-		$tree = [];
292
-		$tree['comment'] = $this->get($id);
293
-		$tree['replies'] = [];
294
-
295
-		$qb = $this->dbConn->getQueryBuilder();
296
-		$query = $qb->select('*')
297
-			->from('comments')
298
-			->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
299
-			->orderBy('creation_timestamp', 'DESC')
300
-			->setParameter('id', $id);
301
-
302
-		if ($limit > 0) {
303
-			$query->setMaxResults($limit);
304
-		}
305
-		if ($offset > 0) {
306
-			$query->setFirstResult($offset);
307
-		}
308
-
309
-		$resultStatement = $query->execute();
310
-		while ($data = $resultStatement->fetch()) {
311
-			$comment = new Comment($this->normalizeDatabaseData($data));
312
-			$this->cache($comment);
313
-			$tree['replies'][] = [
314
-				'comment' => $comment,
315
-				'replies' => []
316
-			];
317
-		}
318
-		$resultStatement->closeCursor();
319
-
320
-		return $tree;
321
-	}
322
-
323
-	/**
324
-	 * returns comments for a specific object (e.g. a file).
325
-	 *
326
-	 * The sort order is always newest to oldest.
327
-	 *
328
-	 * @param string $objectType the object type, e.g. 'files'
329
-	 * @param string $objectId the id of the object
330
-	 * @param int $limit optional, number of maximum comments to be returned. if
331
-	 * not specified, all comments are returned.
332
-	 * @param int $offset optional, starting point
333
-	 * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
334
-	 * that may be returned
335
-	 * @return IComment[]
336
-	 * @since 9.0.0
337
-	 */
338
-	public function getForObject(
339
-		$objectType,
340
-		$objectId,
341
-		$limit = 0,
342
-		$offset = 0,
343
-		\DateTime $notOlderThan = null
344
-	) {
345
-		$comments = [];
346
-
347
-		$qb = $this->dbConn->getQueryBuilder();
348
-		$query = $qb->select('*')
349
-			->from('comments')
350
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
351
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
352
-			->orderBy('creation_timestamp', 'DESC')
353
-			->setParameter('type', $objectType)
354
-			->setParameter('id', $objectId);
355
-
356
-		if ($limit > 0) {
357
-			$query->setMaxResults($limit);
358
-		}
359
-		if ($offset > 0) {
360
-			$query->setFirstResult($offset);
361
-		}
362
-		if (!is_null($notOlderThan)) {
363
-			$query
364
-				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
365
-				->setParameter('notOlderThan', $notOlderThan, 'datetime');
366
-		}
367
-
368
-		$resultStatement = $query->execute();
369
-		while ($data = $resultStatement->fetch()) {
370
-			$comment = new Comment($this->normalizeDatabaseData($data));
371
-			$this->cache($comment);
372
-			$comments[] = $comment;
373
-		}
374
-		$resultStatement->closeCursor();
375
-
376
-		return $comments;
377
-	}
378
-
379
-	/**
380
-	 * @param $objectType string the object type, e.g. 'files'
381
-	 * @param $objectId string the id of the object
382
-	 * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
383
-	 * that may be returned
384
-	 * @return Int
385
-	 * @since 9.0.0
386
-	 */
387
-	public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null) {
388
-		$qb = $this->dbConn->getQueryBuilder();
389
-		$query = $qb->select($qb->createFunction('COUNT(`id`)'))
390
-			->from('comments')
391
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
392
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
393
-			->setParameter('type', $objectType)
394
-			->setParameter('id', $objectId);
395
-
396
-		if (!is_null($notOlderThan)) {
397
-			$query
398
-				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
399
-				->setParameter('notOlderThan', $notOlderThan, 'datetime');
400
-		}
401
-
402
-		$resultStatement = $query->execute();
403
-		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
404
-		$resultStatement->closeCursor();
405
-		return intval($data[0]);
406
-	}
407
-
408
-	/**
409
-	 * Get the number of unread comments for all files in a folder
410
-	 *
411
-	 * @param int $folderId
412
-	 * @param IUser $user
413
-	 * @return array [$fileId => $unreadCount]
414
-	 */
415
-	public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
416
-		$qb = $this->dbConn->getQueryBuilder();
417
-		$query = $qb->select('fileid', $qb->createFunction(
418
-			'COUNT(' . $qb->getColumnName('c.id') . ')')
419
-		)->from('comments', 'c')
420
-			->innerJoin('c', 'filecache', 'f', $qb->expr()->andX(
421
-				$qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
422
-				$qb->expr()->eq('f.fileid', $qb->createFunction(
423
-					'cast(' . $qb->getColumnName('c.object_id') . ' as int)'
424
-				))
425
-			))
426
-			->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX(
427
-				$qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')),
428
-				$qb->expr()->eq('m.object_id', 'c.object_id'),
429
-				$qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID()))
430
-			))
431
-			->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId)))
432
-			->andWhere($qb->expr()->orX(
433
-				$qb->expr()->gt('c.creation_timestamp', 'marker_datetime'),
434
-				$qb->expr()->isNull('marker_datetime')
435
-			))
436
-			->groupBy('f.fileid');
437
-
438
-		$resultStatement = $query->execute();
439
-		return $resultStatement->fetchAll(\PDO::FETCH_KEY_PAIR);
440
-	}
441
-
442
-	/**
443
-	 * creates a new comment and returns it. At this point of time, it is not
444
-	 * saved in the used data storage. Use save() after setting other fields
445
-	 * of the comment (e.g. message or verb).
446
-	 *
447
-	 * @param string $actorType the actor type (e.g. 'users')
448
-	 * @param string $actorId a user id
449
-	 * @param string $objectType the object type the comment is attached to
450
-	 * @param string $objectId the object id the comment is attached to
451
-	 * @return IComment
452
-	 * @since 9.0.0
453
-	 */
454
-	public function create($actorType, $actorId, $objectType, $objectId) {
455
-		$comment = new Comment();
456
-		$comment
457
-			->setActor($actorType, $actorId)
458
-			->setObject($objectType, $objectId);
459
-		return $comment;
460
-	}
461
-
462
-	/**
463
-	 * permanently deletes the comment specified by the ID
464
-	 *
465
-	 * When the comment has child comments, their parent ID will be changed to
466
-	 * the parent ID of the item that is to be deleted.
467
-	 *
468
-	 * @param string $id
469
-	 * @return bool
470
-	 * @throws \InvalidArgumentException
471
-	 * @since 9.0.0
472
-	 */
473
-	public function delete($id) {
474
-		if (!is_string($id)) {
475
-			throw new \InvalidArgumentException('Parameter must be string');
476
-		}
477
-
478
-		try {
479
-			$comment = $this->get($id);
480
-		} catch (\Exception $e) {
481
-			// Ignore exceptions, we just don't fire a hook then
482
-			$comment = null;
483
-		}
484
-
485
-		$qb = $this->dbConn->getQueryBuilder();
486
-		$query = $qb->delete('comments')
487
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
488
-			->setParameter('id', $id);
489
-
490
-		try {
491
-			$affectedRows = $query->execute();
492
-			$this->uncache($id);
493
-		} catch (DriverException $e) {
494
-			$this->logger->logException($e, ['app' => 'core_comments']);
495
-			return false;
496
-		}
497
-
498
-		if ($affectedRows > 0 && $comment instanceof IComment) {
499
-			$this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
500
-		}
501
-
502
-		return ($affectedRows > 0);
503
-	}
504
-
505
-	/**
506
-	 * saves the comment permanently
507
-	 *
508
-	 * if the supplied comment has an empty ID, a new entry comment will be
509
-	 * saved and the instance updated with the new ID.
510
-	 *
511
-	 * Otherwise, an existing comment will be updated.
512
-	 *
513
-	 * Throws NotFoundException when a comment that is to be updated does not
514
-	 * exist anymore at this point of time.
515
-	 *
516
-	 * @param IComment $comment
517
-	 * @return bool
518
-	 * @throws NotFoundException
519
-	 * @since 9.0.0
520
-	 */
521
-	public function save(IComment $comment) {
522
-		if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
523
-			$result = $this->insert($comment);
524
-		} else {
525
-			$result = $this->update($comment);
526
-		}
527
-
528
-		if ($result && !!$comment->getParentId()) {
529
-			$this->updateChildrenInformation(
530
-				$comment->getParentId(),
531
-				$comment->getCreationDateTime()
532
-			);
533
-			$this->cache($comment);
534
-		}
535
-
536
-		return $result;
537
-	}
538
-
539
-	/**
540
-	 * inserts the provided comment in the database
541
-	 *
542
-	 * @param IComment $comment
543
-	 * @return bool
544
-	 */
545
-	protected function insert(IComment &$comment) {
546
-		$qb = $this->dbConn->getQueryBuilder();
547
-		$affectedRows = $qb
548
-			->insert('comments')
549
-			->values([
550
-				'parent_id' => $qb->createNamedParameter($comment->getParentId()),
551
-				'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
552
-				'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
553
-				'actor_type' => $qb->createNamedParameter($comment->getActorType()),
554
-				'actor_id' => $qb->createNamedParameter($comment->getActorId()),
555
-				'message' => $qb->createNamedParameter($comment->getMessage()),
556
-				'verb' => $qb->createNamedParameter($comment->getVerb()),
557
-				'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
558
-				'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
559
-				'object_type' => $qb->createNamedParameter($comment->getObjectType()),
560
-				'object_id' => $qb->createNamedParameter($comment->getObjectId()),
561
-			])
562
-			->execute();
563
-
564
-		if ($affectedRows > 0) {
565
-			$comment->setId(strval($qb->getLastInsertId()));
566
-			$this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
567
-		}
568
-
569
-		return $affectedRows > 0;
570
-	}
571
-
572
-	/**
573
-	 * updates a Comment data row
574
-	 *
575
-	 * @param IComment $comment
576
-	 * @return bool
577
-	 * @throws NotFoundException
578
-	 */
579
-	protected function update(IComment $comment) {
580
-		// for properly working preUpdate Events we need the old comments as is
581
-		// in the DB and overcome caching. Also avoid that outdated information stays.
582
-		$this->uncache($comment->getId());
583
-		$this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
584
-		$this->uncache($comment->getId());
585
-
586
-		$qb = $this->dbConn->getQueryBuilder();
587
-		$affectedRows = $qb
588
-			->update('comments')
589
-			->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
590
-			->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
591
-			->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
592
-			->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
593
-			->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
594
-			->set('message', $qb->createNamedParameter($comment->getMessage()))
595
-			->set('verb', $qb->createNamedParameter($comment->getVerb()))
596
-			->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
597
-			->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
598
-			->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
599
-			->set('object_id', $qb->createNamedParameter($comment->getObjectId()))
600
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
601
-			->setParameter('id', $comment->getId())
602
-			->execute();
603
-
604
-		if ($affectedRows === 0) {
605
-			throw new NotFoundException('Comment to update does ceased to exist');
606
-		}
607
-
608
-		$this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
609
-
610
-		return $affectedRows > 0;
611
-	}
612
-
613
-	/**
614
-	 * removes references to specific actor (e.g. on user delete) of a comment.
615
-	 * The comment itself must not get lost/deleted.
616
-	 *
617
-	 * @param string $actorType the actor type (e.g. 'users')
618
-	 * @param string $actorId a user id
619
-	 * @return boolean
620
-	 * @since 9.0.0
621
-	 */
622
-	public function deleteReferencesOfActor($actorType, $actorId) {
623
-		$this->checkRoleParameters('Actor', $actorType, $actorId);
624
-
625
-		$qb = $this->dbConn->getQueryBuilder();
626
-		$affectedRows = $qb
627
-			->update('comments')
628
-			->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
629
-			->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
630
-			->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
631
-			->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
632
-			->setParameter('type', $actorType)
633
-			->setParameter('id', $actorId)
634
-			->execute();
635
-
636
-		$this->commentsCache = [];
637
-
638
-		return is_int($affectedRows);
639
-	}
640
-
641
-	/**
642
-	 * deletes all comments made of a specific object (e.g. on file delete)
643
-	 *
644
-	 * @param string $objectType the object type (e.g. 'files')
645
-	 * @param string $objectId e.g. the file id
646
-	 * @return boolean
647
-	 * @since 9.0.0
648
-	 */
649
-	public function deleteCommentsAtObject($objectType, $objectId) {
650
-		$this->checkRoleParameters('Object', $objectType, $objectId);
651
-
652
-		$qb = $this->dbConn->getQueryBuilder();
653
-		$affectedRows = $qb
654
-			->delete('comments')
655
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
656
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
657
-			->setParameter('type', $objectType)
658
-			->setParameter('id', $objectId)
659
-			->execute();
660
-
661
-		$this->commentsCache = [];
662
-
663
-		return is_int($affectedRows);
664
-	}
665
-
666
-	/**
667
-	 * deletes the read markers for the specified user
668
-	 *
669
-	 * @param \OCP\IUser $user
670
-	 * @return bool
671
-	 * @since 9.0.0
672
-	 */
673
-	public function deleteReadMarksFromUser(IUser $user) {
674
-		$qb = $this->dbConn->getQueryBuilder();
675
-		$query = $qb->delete('comments_read_markers')
676
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
677
-			->setParameter('user_id', $user->getUID());
678
-
679
-		try {
680
-			$affectedRows = $query->execute();
681
-		} catch (DriverException $e) {
682
-			$this->logger->logException($e, ['app' => 'core_comments']);
683
-			return false;
684
-		}
685
-		return ($affectedRows > 0);
686
-	}
687
-
688
-	/**
689
-	 * sets the read marker for a given file to the specified date for the
690
-	 * provided user
691
-	 *
692
-	 * @param string $objectType
693
-	 * @param string $objectId
694
-	 * @param \DateTime $dateTime
695
-	 * @param IUser $user
696
-	 * @since 9.0.0
697
-	 */
698
-	public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
699
-		$this->checkRoleParameters('Object', $objectType, $objectId);
700
-
701
-		$qb = $this->dbConn->getQueryBuilder();
702
-		$values = [
703
-			'user_id' => $qb->createNamedParameter($user->getUID()),
704
-			'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
705
-			'object_type' => $qb->createNamedParameter($objectType),
706
-			'object_id' => $qb->createNamedParameter($objectId),
707
-		];
708
-
709
-		// Strategy: try to update, if this does not return affected rows, do an insert.
710
-		$affectedRows = $qb
711
-			->update('comments_read_markers')
712
-			->set('user_id', $values['user_id'])
713
-			->set('marker_datetime', $values['marker_datetime'])
714
-			->set('object_type', $values['object_type'])
715
-			->set('object_id', $values['object_id'])
716
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
717
-			->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
718
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
719
-			->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
720
-			->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
721
-			->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
722
-			->execute();
723
-
724
-		if ($affectedRows > 0) {
725
-			return;
726
-		}
727
-
728
-		$qb->insert('comments_read_markers')
729
-			->values($values)
730
-			->execute();
731
-	}
732
-
733
-	/**
734
-	 * returns the read marker for a given file to the specified date for the
735
-	 * provided user. It returns null, when the marker is not present, i.e.
736
-	 * no comments were marked as read.
737
-	 *
738
-	 * @param string $objectType
739
-	 * @param string $objectId
740
-	 * @param IUser $user
741
-	 * @return \DateTime|null
742
-	 * @since 9.0.0
743
-	 */
744
-	public function getReadMark($objectType, $objectId, IUser $user) {
745
-		$qb = $this->dbConn->getQueryBuilder();
746
-		$resultStatement = $qb->select('marker_datetime')
747
-			->from('comments_read_markers')
748
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
749
-			->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
750
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
751
-			->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
752
-			->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
753
-			->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
754
-			->execute();
755
-
756
-		$data = $resultStatement->fetch();
757
-		$resultStatement->closeCursor();
758
-		if (!$data || is_null($data['marker_datetime'])) {
759
-			return null;
760
-		}
761
-
762
-		return new \DateTime($data['marker_datetime']);
763
-	}
764
-
765
-	/**
766
-	 * deletes the read markers on the specified object
767
-	 *
768
-	 * @param string $objectType
769
-	 * @param string $objectId
770
-	 * @return bool
771
-	 * @since 9.0.0
772
-	 */
773
-	public function deleteReadMarksOnObject($objectType, $objectId) {
774
-		$this->checkRoleParameters('Object', $objectType, $objectId);
775
-
776
-		$qb = $this->dbConn->getQueryBuilder();
777
-		$query = $qb->delete('comments_read_markers')
778
-			->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
779
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
780
-			->setParameter('object_type', $objectType)
781
-			->setParameter('object_id', $objectId);
782
-
783
-		try {
784
-			$affectedRows = $query->execute();
785
-		} catch (DriverException $e) {
786
-			$this->logger->logException($e, ['app' => 'core_comments']);
787
-			return false;
788
-		}
789
-		return ($affectedRows > 0);
790
-	}
791
-
792
-	/**
793
-	 * registers an Entity to the manager, so event notifications can be send
794
-	 * to consumers of the comments infrastructure
795
-	 *
796
-	 * @param \Closure $closure
797
-	 */
798
-	public function registerEventHandler(\Closure $closure) {
799
-		$this->eventHandlerClosures[] = $closure;
800
-		$this->eventHandlers = [];
801
-	}
802
-
803
-	/**
804
-	 * registers a method that resolves an ID to a display name for a given type
805
-	 *
806
-	 * @param string $type
807
-	 * @param \Closure $closure
808
-	 * @throws \OutOfBoundsException
809
-	 * @since 11.0.0
810
-	 *
811
-	 * Only one resolver shall be registered per type. Otherwise a
812
-	 * \OutOfBoundsException has to thrown.
813
-	 */
814
-	public function registerDisplayNameResolver($type, \Closure $closure) {
815
-		if (!is_string($type)) {
816
-			throw new \InvalidArgumentException('String expected.');
817
-		}
818
-		if (isset($this->displayNameResolvers[$type])) {
819
-			throw new \OutOfBoundsException('Displayname resolver for this type already registered');
820
-		}
821
-		$this->displayNameResolvers[$type] = $closure;
822
-	}
823
-
824
-	/**
825
-	 * resolves a given ID of a given Type to a display name.
826
-	 *
827
-	 * @param string $type
828
-	 * @param string $id
829
-	 * @return string
830
-	 * @throws \OutOfBoundsException
831
-	 * @since 11.0.0
832
-	 *
833
-	 * If a provided type was not registered, an \OutOfBoundsException shall
834
-	 * be thrown. It is upon the resolver discretion what to return of the
835
-	 * provided ID is unknown. It must be ensured that a string is returned.
836
-	 */
837
-	public function resolveDisplayName($type, $id) {
838
-		if (!is_string($type)) {
839
-			throw new \InvalidArgumentException('String expected.');
840
-		}
841
-		if (!isset($this->displayNameResolvers[$type])) {
842
-			throw new \OutOfBoundsException('No Displayname resolver for this type registered');
843
-		}
844
-		return (string)$this->displayNameResolvers[$type]($id);
845
-	}
846
-
847
-	/**
848
-	 * returns valid, registered entities
849
-	 *
850
-	 * @return \OCP\Comments\ICommentsEventHandler[]
851
-	 */
852
-	private function getEventHandlers() {
853
-		if (!empty($this->eventHandlers)) {
854
-			return $this->eventHandlers;
855
-		}
856
-
857
-		$this->eventHandlers = [];
858
-		foreach ($this->eventHandlerClosures as $name => $closure) {
859
-			$entity = $closure();
860
-			if (!($entity instanceof ICommentsEventHandler)) {
861
-				throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
862
-			}
863
-			$this->eventHandlers[$name] = $entity;
864
-		}
865
-
866
-		return $this->eventHandlers;
867
-	}
868
-
869
-	/**
870
-	 * sends notifications to the registered entities
871
-	 *
872
-	 * @param $eventType
873
-	 * @param IComment $comment
874
-	 */
875
-	private function sendEvent($eventType, IComment $comment) {
876
-		$entities = $this->getEventHandlers();
877
-		$event = new CommentsEvent($eventType, $comment);
878
-		foreach ($entities as $entity) {
879
-			$entity->handle($event);
880
-		}
881
-	}
44
+    /** @var  IDBConnection */
45
+    protected $dbConn;
46
+
47
+    /** @var  ILogger */
48
+    protected $logger;
49
+
50
+    /** @var IConfig */
51
+    protected $config;
52
+
53
+    /** @var IComment[] */
54
+    protected $commentsCache = [];
55
+
56
+    /** @var  \Closure[] */
57
+    protected $eventHandlerClosures = [];
58
+
59
+    /** @var  ICommentsEventHandler[] */
60
+    protected $eventHandlers = [];
61
+
62
+    /** @var \Closure[] */
63
+    protected $displayNameResolvers = [];
64
+
65
+    /**
66
+     * Manager constructor.
67
+     *
68
+     * @param IDBConnection $dbConn
69
+     * @param ILogger $logger
70
+     * @param IConfig $config
71
+     */
72
+    public function __construct(
73
+        IDBConnection $dbConn,
74
+        ILogger $logger,
75
+        IConfig $config
76
+    ) {
77
+        $this->dbConn = $dbConn;
78
+        $this->logger = $logger;
79
+        $this->config = $config;
80
+    }
81
+
82
+    /**
83
+     * converts data base data into PHP native, proper types as defined by
84
+     * IComment interface.
85
+     *
86
+     * @param array $data
87
+     * @return array
88
+     */
89
+    protected function normalizeDatabaseData(array $data) {
90
+        $data['id'] = strval($data['id']);
91
+        $data['parent_id'] = strval($data['parent_id']);
92
+        $data['topmost_parent_id'] = strval($data['topmost_parent_id']);
93
+        $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
94
+        if (!is_null($data['latest_child_timestamp'])) {
95
+            $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
96
+        }
97
+        $data['children_count'] = intval($data['children_count']);
98
+        return $data;
99
+    }
100
+
101
+    /**
102
+     * prepares a comment for an insert or update operation after making sure
103
+     * all necessary fields have a value assigned.
104
+     *
105
+     * @param IComment $comment
106
+     * @return IComment returns the same updated IComment instance as provided
107
+     *                  by parameter for convenience
108
+     * @throws \UnexpectedValueException
109
+     */
110
+    protected function prepareCommentForDatabaseWrite(IComment $comment) {
111
+        if (!$comment->getActorType()
112
+            || !$comment->getActorId()
113
+            || !$comment->getObjectType()
114
+            || !$comment->getObjectId()
115
+            || !$comment->getVerb()
116
+        ) {
117
+            throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
118
+        }
119
+
120
+        if ($comment->getId() === '') {
121
+            $comment->setChildrenCount(0);
122
+            $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
123
+            $comment->setLatestChildDateTime(null);
124
+        }
125
+
126
+        if (is_null($comment->getCreationDateTime())) {
127
+            $comment->setCreationDateTime(new \DateTime());
128
+        }
129
+
130
+        if ($comment->getParentId() !== '0') {
131
+            $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
132
+        } else {
133
+            $comment->setTopmostParentId('0');
134
+        }
135
+
136
+        $this->cache($comment);
137
+
138
+        return $comment;
139
+    }
140
+
141
+    /**
142
+     * returns the topmost parent id of a given comment identified by ID
143
+     *
144
+     * @param string $id
145
+     * @return string
146
+     * @throws NotFoundException
147
+     */
148
+    protected function determineTopmostParentId($id) {
149
+        $comment = $this->get($id);
150
+        if ($comment->getParentId() === '0') {
151
+            return $comment->getId();
152
+        } else {
153
+            return $this->determineTopmostParentId($comment->getId());
154
+        }
155
+    }
156
+
157
+    /**
158
+     * updates child information of a comment
159
+     *
160
+     * @param string $id
161
+     * @param \DateTime $cDateTime the date time of the most recent child
162
+     * @throws NotFoundException
163
+     */
164
+    protected function updateChildrenInformation($id, \DateTime $cDateTime) {
165
+        $qb = $this->dbConn->getQueryBuilder();
166
+        $query = $qb->select($qb->createFunction('COUNT(`id`)'))
167
+            ->from('comments')
168
+            ->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
169
+            ->setParameter('id', $id);
170
+
171
+        $resultStatement = $query->execute();
172
+        $data = $resultStatement->fetch(\PDO::FETCH_NUM);
173
+        $resultStatement->closeCursor();
174
+        $children = intval($data[0]);
175
+
176
+        $comment = $this->get($id);
177
+        $comment->setChildrenCount($children);
178
+        $comment->setLatestChildDateTime($cDateTime);
179
+        $this->save($comment);
180
+    }
181
+
182
+    /**
183
+     * Tests whether actor or object type and id parameters are acceptable.
184
+     * Throws exception if not.
185
+     *
186
+     * @param string $role
187
+     * @param string $type
188
+     * @param string $id
189
+     * @throws \InvalidArgumentException
190
+     */
191
+    protected function checkRoleParameters($role, $type, $id) {
192
+        if (
193
+            !is_string($type) || empty($type)
194
+            || !is_string($id) || empty($id)
195
+        ) {
196
+            throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
197
+        }
198
+    }
199
+
200
+    /**
201
+     * run-time caches a comment
202
+     *
203
+     * @param IComment $comment
204
+     */
205
+    protected function cache(IComment $comment) {
206
+        $id = $comment->getId();
207
+        if (empty($id)) {
208
+            return;
209
+        }
210
+        $this->commentsCache[strval($id)] = $comment;
211
+    }
212
+
213
+    /**
214
+     * removes an entry from the comments run time cache
215
+     *
216
+     * @param mixed $id the comment's id
217
+     */
218
+    protected function uncache($id) {
219
+        $id = strval($id);
220
+        if (isset($this->commentsCache[$id])) {
221
+            unset($this->commentsCache[$id]);
222
+        }
223
+    }
224
+
225
+    /**
226
+     * returns a comment instance
227
+     *
228
+     * @param string $id the ID of the comment
229
+     * @return IComment
230
+     * @throws NotFoundException
231
+     * @throws \InvalidArgumentException
232
+     * @since 9.0.0
233
+     */
234
+    public function get($id) {
235
+        if (intval($id) === 0) {
236
+            throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
237
+        }
238
+
239
+        if (isset($this->commentsCache[$id])) {
240
+            return $this->commentsCache[$id];
241
+        }
242
+
243
+        $qb = $this->dbConn->getQueryBuilder();
244
+        $resultStatement = $qb->select('*')
245
+            ->from('comments')
246
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
247
+            ->setParameter('id', $id, IQueryBuilder::PARAM_INT)
248
+            ->execute();
249
+
250
+        $data = $resultStatement->fetch();
251
+        $resultStatement->closeCursor();
252
+        if (!$data) {
253
+            throw new NotFoundException();
254
+        }
255
+
256
+        $comment = new Comment($this->normalizeDatabaseData($data));
257
+        $this->cache($comment);
258
+        return $comment;
259
+    }
260
+
261
+    /**
262
+     * returns the comment specified by the id and all it's child comments.
263
+     * At this point of time, we do only support one level depth.
264
+     *
265
+     * @param string $id
266
+     * @param int $limit max number of entries to return, 0 returns all
267
+     * @param int $offset the start entry
268
+     * @return array
269
+     * @since 9.0.0
270
+     *
271
+     * The return array looks like this
272
+     * [
273
+     *   'comment' => IComment, // root comment
274
+     *   'replies' =>
275
+     *   [
276
+     *     0 =>
277
+     *     [
278
+     *       'comment' => IComment,
279
+     *       'replies' => []
280
+     *     ]
281
+     *     1 =>
282
+     *     [
283
+     *       'comment' => IComment,
284
+     *       'replies'=> []
285
+     *     ],
286
+     *     …
287
+     *   ]
288
+     * ]
289
+     */
290
+    public function getTree($id, $limit = 0, $offset = 0) {
291
+        $tree = [];
292
+        $tree['comment'] = $this->get($id);
293
+        $tree['replies'] = [];
294
+
295
+        $qb = $this->dbConn->getQueryBuilder();
296
+        $query = $qb->select('*')
297
+            ->from('comments')
298
+            ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
299
+            ->orderBy('creation_timestamp', 'DESC')
300
+            ->setParameter('id', $id);
301
+
302
+        if ($limit > 0) {
303
+            $query->setMaxResults($limit);
304
+        }
305
+        if ($offset > 0) {
306
+            $query->setFirstResult($offset);
307
+        }
308
+
309
+        $resultStatement = $query->execute();
310
+        while ($data = $resultStatement->fetch()) {
311
+            $comment = new Comment($this->normalizeDatabaseData($data));
312
+            $this->cache($comment);
313
+            $tree['replies'][] = [
314
+                'comment' => $comment,
315
+                'replies' => []
316
+            ];
317
+        }
318
+        $resultStatement->closeCursor();
319
+
320
+        return $tree;
321
+    }
322
+
323
+    /**
324
+     * returns comments for a specific object (e.g. a file).
325
+     *
326
+     * The sort order is always newest to oldest.
327
+     *
328
+     * @param string $objectType the object type, e.g. 'files'
329
+     * @param string $objectId the id of the object
330
+     * @param int $limit optional, number of maximum comments to be returned. if
331
+     * not specified, all comments are returned.
332
+     * @param int $offset optional, starting point
333
+     * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
334
+     * that may be returned
335
+     * @return IComment[]
336
+     * @since 9.0.0
337
+     */
338
+    public function getForObject(
339
+        $objectType,
340
+        $objectId,
341
+        $limit = 0,
342
+        $offset = 0,
343
+        \DateTime $notOlderThan = null
344
+    ) {
345
+        $comments = [];
346
+
347
+        $qb = $this->dbConn->getQueryBuilder();
348
+        $query = $qb->select('*')
349
+            ->from('comments')
350
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
351
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
352
+            ->orderBy('creation_timestamp', 'DESC')
353
+            ->setParameter('type', $objectType)
354
+            ->setParameter('id', $objectId);
355
+
356
+        if ($limit > 0) {
357
+            $query->setMaxResults($limit);
358
+        }
359
+        if ($offset > 0) {
360
+            $query->setFirstResult($offset);
361
+        }
362
+        if (!is_null($notOlderThan)) {
363
+            $query
364
+                ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
365
+                ->setParameter('notOlderThan', $notOlderThan, 'datetime');
366
+        }
367
+
368
+        $resultStatement = $query->execute();
369
+        while ($data = $resultStatement->fetch()) {
370
+            $comment = new Comment($this->normalizeDatabaseData($data));
371
+            $this->cache($comment);
372
+            $comments[] = $comment;
373
+        }
374
+        $resultStatement->closeCursor();
375
+
376
+        return $comments;
377
+    }
378
+
379
+    /**
380
+     * @param $objectType string the object type, e.g. 'files'
381
+     * @param $objectId string the id of the object
382
+     * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
383
+     * that may be returned
384
+     * @return Int
385
+     * @since 9.0.0
386
+     */
387
+    public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null) {
388
+        $qb = $this->dbConn->getQueryBuilder();
389
+        $query = $qb->select($qb->createFunction('COUNT(`id`)'))
390
+            ->from('comments')
391
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
392
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
393
+            ->setParameter('type', $objectType)
394
+            ->setParameter('id', $objectId);
395
+
396
+        if (!is_null($notOlderThan)) {
397
+            $query
398
+                ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
399
+                ->setParameter('notOlderThan', $notOlderThan, 'datetime');
400
+        }
401
+
402
+        $resultStatement = $query->execute();
403
+        $data = $resultStatement->fetch(\PDO::FETCH_NUM);
404
+        $resultStatement->closeCursor();
405
+        return intval($data[0]);
406
+    }
407
+
408
+    /**
409
+     * Get the number of unread comments for all files in a folder
410
+     *
411
+     * @param int $folderId
412
+     * @param IUser $user
413
+     * @return array [$fileId => $unreadCount]
414
+     */
415
+    public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
416
+        $qb = $this->dbConn->getQueryBuilder();
417
+        $query = $qb->select('fileid', $qb->createFunction(
418
+            'COUNT(' . $qb->getColumnName('c.id') . ')')
419
+        )->from('comments', 'c')
420
+            ->innerJoin('c', 'filecache', 'f', $qb->expr()->andX(
421
+                $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
422
+                $qb->expr()->eq('f.fileid', $qb->createFunction(
423
+                    'cast(' . $qb->getColumnName('c.object_id') . ' as int)'
424
+                ))
425
+            ))
426
+            ->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX(
427
+                $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')),
428
+                $qb->expr()->eq('m.object_id', 'c.object_id'),
429
+                $qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID()))
430
+            ))
431
+            ->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId)))
432
+            ->andWhere($qb->expr()->orX(
433
+                $qb->expr()->gt('c.creation_timestamp', 'marker_datetime'),
434
+                $qb->expr()->isNull('marker_datetime')
435
+            ))
436
+            ->groupBy('f.fileid');
437
+
438
+        $resultStatement = $query->execute();
439
+        return $resultStatement->fetchAll(\PDO::FETCH_KEY_PAIR);
440
+    }
441
+
442
+    /**
443
+     * creates a new comment and returns it. At this point of time, it is not
444
+     * saved in the used data storage. Use save() after setting other fields
445
+     * of the comment (e.g. message or verb).
446
+     *
447
+     * @param string $actorType the actor type (e.g. 'users')
448
+     * @param string $actorId a user id
449
+     * @param string $objectType the object type the comment is attached to
450
+     * @param string $objectId the object id the comment is attached to
451
+     * @return IComment
452
+     * @since 9.0.0
453
+     */
454
+    public function create($actorType, $actorId, $objectType, $objectId) {
455
+        $comment = new Comment();
456
+        $comment
457
+            ->setActor($actorType, $actorId)
458
+            ->setObject($objectType, $objectId);
459
+        return $comment;
460
+    }
461
+
462
+    /**
463
+     * permanently deletes the comment specified by the ID
464
+     *
465
+     * When the comment has child comments, their parent ID will be changed to
466
+     * the parent ID of the item that is to be deleted.
467
+     *
468
+     * @param string $id
469
+     * @return bool
470
+     * @throws \InvalidArgumentException
471
+     * @since 9.0.0
472
+     */
473
+    public function delete($id) {
474
+        if (!is_string($id)) {
475
+            throw new \InvalidArgumentException('Parameter must be string');
476
+        }
477
+
478
+        try {
479
+            $comment = $this->get($id);
480
+        } catch (\Exception $e) {
481
+            // Ignore exceptions, we just don't fire a hook then
482
+            $comment = null;
483
+        }
484
+
485
+        $qb = $this->dbConn->getQueryBuilder();
486
+        $query = $qb->delete('comments')
487
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
488
+            ->setParameter('id', $id);
489
+
490
+        try {
491
+            $affectedRows = $query->execute();
492
+            $this->uncache($id);
493
+        } catch (DriverException $e) {
494
+            $this->logger->logException($e, ['app' => 'core_comments']);
495
+            return false;
496
+        }
497
+
498
+        if ($affectedRows > 0 && $comment instanceof IComment) {
499
+            $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
500
+        }
501
+
502
+        return ($affectedRows > 0);
503
+    }
504
+
505
+    /**
506
+     * saves the comment permanently
507
+     *
508
+     * if the supplied comment has an empty ID, a new entry comment will be
509
+     * saved and the instance updated with the new ID.
510
+     *
511
+     * Otherwise, an existing comment will be updated.
512
+     *
513
+     * Throws NotFoundException when a comment that is to be updated does not
514
+     * exist anymore at this point of time.
515
+     *
516
+     * @param IComment $comment
517
+     * @return bool
518
+     * @throws NotFoundException
519
+     * @since 9.0.0
520
+     */
521
+    public function save(IComment $comment) {
522
+        if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
523
+            $result = $this->insert($comment);
524
+        } else {
525
+            $result = $this->update($comment);
526
+        }
527
+
528
+        if ($result && !!$comment->getParentId()) {
529
+            $this->updateChildrenInformation(
530
+                $comment->getParentId(),
531
+                $comment->getCreationDateTime()
532
+            );
533
+            $this->cache($comment);
534
+        }
535
+
536
+        return $result;
537
+    }
538
+
539
+    /**
540
+     * inserts the provided comment in the database
541
+     *
542
+     * @param IComment $comment
543
+     * @return bool
544
+     */
545
+    protected function insert(IComment &$comment) {
546
+        $qb = $this->dbConn->getQueryBuilder();
547
+        $affectedRows = $qb
548
+            ->insert('comments')
549
+            ->values([
550
+                'parent_id' => $qb->createNamedParameter($comment->getParentId()),
551
+                'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
552
+                'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
553
+                'actor_type' => $qb->createNamedParameter($comment->getActorType()),
554
+                'actor_id' => $qb->createNamedParameter($comment->getActorId()),
555
+                'message' => $qb->createNamedParameter($comment->getMessage()),
556
+                'verb' => $qb->createNamedParameter($comment->getVerb()),
557
+                'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
558
+                'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
559
+                'object_type' => $qb->createNamedParameter($comment->getObjectType()),
560
+                'object_id' => $qb->createNamedParameter($comment->getObjectId()),
561
+            ])
562
+            ->execute();
563
+
564
+        if ($affectedRows > 0) {
565
+            $comment->setId(strval($qb->getLastInsertId()));
566
+            $this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
567
+        }
568
+
569
+        return $affectedRows > 0;
570
+    }
571
+
572
+    /**
573
+     * updates a Comment data row
574
+     *
575
+     * @param IComment $comment
576
+     * @return bool
577
+     * @throws NotFoundException
578
+     */
579
+    protected function update(IComment $comment) {
580
+        // for properly working preUpdate Events we need the old comments as is
581
+        // in the DB and overcome caching. Also avoid that outdated information stays.
582
+        $this->uncache($comment->getId());
583
+        $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
584
+        $this->uncache($comment->getId());
585
+
586
+        $qb = $this->dbConn->getQueryBuilder();
587
+        $affectedRows = $qb
588
+            ->update('comments')
589
+            ->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
590
+            ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
591
+            ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
592
+            ->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
593
+            ->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
594
+            ->set('message', $qb->createNamedParameter($comment->getMessage()))
595
+            ->set('verb', $qb->createNamedParameter($comment->getVerb()))
596
+            ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
597
+            ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
598
+            ->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
599
+            ->set('object_id', $qb->createNamedParameter($comment->getObjectId()))
600
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
601
+            ->setParameter('id', $comment->getId())
602
+            ->execute();
603
+
604
+        if ($affectedRows === 0) {
605
+            throw new NotFoundException('Comment to update does ceased to exist');
606
+        }
607
+
608
+        $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
609
+
610
+        return $affectedRows > 0;
611
+    }
612
+
613
+    /**
614
+     * removes references to specific actor (e.g. on user delete) of a comment.
615
+     * The comment itself must not get lost/deleted.
616
+     *
617
+     * @param string $actorType the actor type (e.g. 'users')
618
+     * @param string $actorId a user id
619
+     * @return boolean
620
+     * @since 9.0.0
621
+     */
622
+    public function deleteReferencesOfActor($actorType, $actorId) {
623
+        $this->checkRoleParameters('Actor', $actorType, $actorId);
624
+
625
+        $qb = $this->dbConn->getQueryBuilder();
626
+        $affectedRows = $qb
627
+            ->update('comments')
628
+            ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
629
+            ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
630
+            ->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
631
+            ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
632
+            ->setParameter('type', $actorType)
633
+            ->setParameter('id', $actorId)
634
+            ->execute();
635
+
636
+        $this->commentsCache = [];
637
+
638
+        return is_int($affectedRows);
639
+    }
640
+
641
+    /**
642
+     * deletes all comments made of a specific object (e.g. on file delete)
643
+     *
644
+     * @param string $objectType the object type (e.g. 'files')
645
+     * @param string $objectId e.g. the file id
646
+     * @return boolean
647
+     * @since 9.0.0
648
+     */
649
+    public function deleteCommentsAtObject($objectType, $objectId) {
650
+        $this->checkRoleParameters('Object', $objectType, $objectId);
651
+
652
+        $qb = $this->dbConn->getQueryBuilder();
653
+        $affectedRows = $qb
654
+            ->delete('comments')
655
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
656
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
657
+            ->setParameter('type', $objectType)
658
+            ->setParameter('id', $objectId)
659
+            ->execute();
660
+
661
+        $this->commentsCache = [];
662
+
663
+        return is_int($affectedRows);
664
+    }
665
+
666
+    /**
667
+     * deletes the read markers for the specified user
668
+     *
669
+     * @param \OCP\IUser $user
670
+     * @return bool
671
+     * @since 9.0.0
672
+     */
673
+    public function deleteReadMarksFromUser(IUser $user) {
674
+        $qb = $this->dbConn->getQueryBuilder();
675
+        $query = $qb->delete('comments_read_markers')
676
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
677
+            ->setParameter('user_id', $user->getUID());
678
+
679
+        try {
680
+            $affectedRows = $query->execute();
681
+        } catch (DriverException $e) {
682
+            $this->logger->logException($e, ['app' => 'core_comments']);
683
+            return false;
684
+        }
685
+        return ($affectedRows > 0);
686
+    }
687
+
688
+    /**
689
+     * sets the read marker for a given file to the specified date for the
690
+     * provided user
691
+     *
692
+     * @param string $objectType
693
+     * @param string $objectId
694
+     * @param \DateTime $dateTime
695
+     * @param IUser $user
696
+     * @since 9.0.0
697
+     */
698
+    public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
699
+        $this->checkRoleParameters('Object', $objectType, $objectId);
700
+
701
+        $qb = $this->dbConn->getQueryBuilder();
702
+        $values = [
703
+            'user_id' => $qb->createNamedParameter($user->getUID()),
704
+            'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
705
+            'object_type' => $qb->createNamedParameter($objectType),
706
+            'object_id' => $qb->createNamedParameter($objectId),
707
+        ];
708
+
709
+        // Strategy: try to update, if this does not return affected rows, do an insert.
710
+        $affectedRows = $qb
711
+            ->update('comments_read_markers')
712
+            ->set('user_id', $values['user_id'])
713
+            ->set('marker_datetime', $values['marker_datetime'])
714
+            ->set('object_type', $values['object_type'])
715
+            ->set('object_id', $values['object_id'])
716
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
717
+            ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
718
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
719
+            ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
720
+            ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
721
+            ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
722
+            ->execute();
723
+
724
+        if ($affectedRows > 0) {
725
+            return;
726
+        }
727
+
728
+        $qb->insert('comments_read_markers')
729
+            ->values($values)
730
+            ->execute();
731
+    }
732
+
733
+    /**
734
+     * returns the read marker for a given file to the specified date for the
735
+     * provided user. It returns null, when the marker is not present, i.e.
736
+     * no comments were marked as read.
737
+     *
738
+     * @param string $objectType
739
+     * @param string $objectId
740
+     * @param IUser $user
741
+     * @return \DateTime|null
742
+     * @since 9.0.0
743
+     */
744
+    public function getReadMark($objectType, $objectId, IUser $user) {
745
+        $qb = $this->dbConn->getQueryBuilder();
746
+        $resultStatement = $qb->select('marker_datetime')
747
+            ->from('comments_read_markers')
748
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
749
+            ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
750
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
751
+            ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
752
+            ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
753
+            ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
754
+            ->execute();
755
+
756
+        $data = $resultStatement->fetch();
757
+        $resultStatement->closeCursor();
758
+        if (!$data || is_null($data['marker_datetime'])) {
759
+            return null;
760
+        }
761
+
762
+        return new \DateTime($data['marker_datetime']);
763
+    }
764
+
765
+    /**
766
+     * deletes the read markers on the specified object
767
+     *
768
+     * @param string $objectType
769
+     * @param string $objectId
770
+     * @return bool
771
+     * @since 9.0.0
772
+     */
773
+    public function deleteReadMarksOnObject($objectType, $objectId) {
774
+        $this->checkRoleParameters('Object', $objectType, $objectId);
775
+
776
+        $qb = $this->dbConn->getQueryBuilder();
777
+        $query = $qb->delete('comments_read_markers')
778
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
779
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
780
+            ->setParameter('object_type', $objectType)
781
+            ->setParameter('object_id', $objectId);
782
+
783
+        try {
784
+            $affectedRows = $query->execute();
785
+        } catch (DriverException $e) {
786
+            $this->logger->logException($e, ['app' => 'core_comments']);
787
+            return false;
788
+        }
789
+        return ($affectedRows > 0);
790
+    }
791
+
792
+    /**
793
+     * registers an Entity to the manager, so event notifications can be send
794
+     * to consumers of the comments infrastructure
795
+     *
796
+     * @param \Closure $closure
797
+     */
798
+    public function registerEventHandler(\Closure $closure) {
799
+        $this->eventHandlerClosures[] = $closure;
800
+        $this->eventHandlers = [];
801
+    }
802
+
803
+    /**
804
+     * registers a method that resolves an ID to a display name for a given type
805
+     *
806
+     * @param string $type
807
+     * @param \Closure $closure
808
+     * @throws \OutOfBoundsException
809
+     * @since 11.0.0
810
+     *
811
+     * Only one resolver shall be registered per type. Otherwise a
812
+     * \OutOfBoundsException has to thrown.
813
+     */
814
+    public function registerDisplayNameResolver($type, \Closure $closure) {
815
+        if (!is_string($type)) {
816
+            throw new \InvalidArgumentException('String expected.');
817
+        }
818
+        if (isset($this->displayNameResolvers[$type])) {
819
+            throw new \OutOfBoundsException('Displayname resolver for this type already registered');
820
+        }
821
+        $this->displayNameResolvers[$type] = $closure;
822
+    }
823
+
824
+    /**
825
+     * resolves a given ID of a given Type to a display name.
826
+     *
827
+     * @param string $type
828
+     * @param string $id
829
+     * @return string
830
+     * @throws \OutOfBoundsException
831
+     * @since 11.0.0
832
+     *
833
+     * If a provided type was not registered, an \OutOfBoundsException shall
834
+     * be thrown. It is upon the resolver discretion what to return of the
835
+     * provided ID is unknown. It must be ensured that a string is returned.
836
+     */
837
+    public function resolveDisplayName($type, $id) {
838
+        if (!is_string($type)) {
839
+            throw new \InvalidArgumentException('String expected.');
840
+        }
841
+        if (!isset($this->displayNameResolvers[$type])) {
842
+            throw new \OutOfBoundsException('No Displayname resolver for this type registered');
843
+        }
844
+        return (string)$this->displayNameResolvers[$type]($id);
845
+    }
846
+
847
+    /**
848
+     * returns valid, registered entities
849
+     *
850
+     * @return \OCP\Comments\ICommentsEventHandler[]
851
+     */
852
+    private function getEventHandlers() {
853
+        if (!empty($this->eventHandlers)) {
854
+            return $this->eventHandlers;
855
+        }
856
+
857
+        $this->eventHandlers = [];
858
+        foreach ($this->eventHandlerClosures as $name => $closure) {
859
+            $entity = $closure();
860
+            if (!($entity instanceof ICommentsEventHandler)) {
861
+                throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
862
+            }
863
+            $this->eventHandlers[$name] = $entity;
864
+        }
865
+
866
+        return $this->eventHandlers;
867
+    }
868
+
869
+    /**
870
+     * sends notifications to the registered entities
871
+     *
872
+     * @param $eventType
873
+     * @param IComment $comment
874
+     */
875
+    private function sendEvent($eventType, IComment $comment) {
876
+        $entities = $this->getEventHandlers();
877
+        $event = new CommentsEvent($eventType, $comment);
878
+        foreach ($entities as $entity) {
879
+            $entity->handle($event);
880
+        }
881
+    }
882 882
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -193,7 +193,7 @@  discard block
 block discarded – undo
193 193
 			!is_string($type) || empty($type)
194 194
 			|| !is_string($id) || empty($id)
195 195
 		) {
196
-			throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
196
+			throw new \InvalidArgumentException($role.' parameters must be string and not empty');
197 197
 		}
198 198
 	}
199 199
 
@@ -415,12 +415,12 @@  discard block
 block discarded – undo
415 415
 	public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
416 416
 		$qb = $this->dbConn->getQueryBuilder();
417 417
 		$query = $qb->select('fileid', $qb->createFunction(
418
-			'COUNT(' . $qb->getColumnName('c.id') . ')')
418
+			'COUNT('.$qb->getColumnName('c.id').')')
419 419
 		)->from('comments', 'c')
420 420
 			->innerJoin('c', 'filecache', 'f', $qb->expr()->andX(
421 421
 				$qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
422 422
 				$qb->expr()->eq('f.fileid', $qb->createFunction(
423
-					'cast(' . $qb->getColumnName('c.object_id') . ' as int)'
423
+					'cast('.$qb->getColumnName('c.object_id').' as int)'
424 424
 				))
425 425
 			))
426 426
 			->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX(
@@ -542,7 +542,7 @@  discard block
 block discarded – undo
542 542
 	 * @param IComment $comment
543 543
 	 * @return bool
544 544
 	 */
545
-	protected function insert(IComment &$comment) {
545
+	protected function insert(IComment & $comment) {
546 546
 		$qb = $this->dbConn->getQueryBuilder();
547 547
 		$affectedRows = $qb
548 548
 			->insert('comments')
@@ -841,7 +841,7 @@  discard block
 block discarded – undo
841 841
 		if (!isset($this->displayNameResolvers[$type])) {
842 842
 			throw new \OutOfBoundsException('No Displayname resolver for this type registered');
843 843
 		}
844
-		return (string)$this->displayNameResolvers[$type]($id);
844
+		return (string) $this->displayNameResolvers[$type]($id);
845 845
 	}
846 846
 
847 847
 	/**
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php 1 patch
Indentation   +127 added lines, -127 removed lines patch added patch discarded remove patch
@@ -29,132 +29,132 @@
 block discarded – undo
29 29
 
30 30
 class CommentPropertiesPlugin extends ServerPlugin {
31 31
 
32
-	const PROPERTY_NAME_HREF   = '{http://owncloud.org/ns}comments-href';
33
-	const PROPERTY_NAME_COUNT  = '{http://owncloud.org/ns}comments-count';
34
-	const PROPERTY_NAME_UNREAD = '{http://owncloud.org/ns}comments-unread';
35
-
36
-	/** @var  \Sabre\DAV\Server */
37
-	protected $server;
38
-
39
-	/** @var ICommentsManager */
40
-	private $commentsManager;
41
-
42
-	/** @var IUserSession */
43
-	private $userSession;
44
-
45
-	private $cachedUnreadCount = [];
46
-
47
-	private $cachedFolders = [];
48
-
49
-	public function __construct(ICommentsManager $commentsManager, IUserSession $userSession) {
50
-		$this->commentsManager = $commentsManager;
51
-		$this->userSession = $userSession;
52
-	}
53
-
54
-	/**
55
-	 * This initializes the plugin.
56
-	 *
57
-	 * This function is called by Sabre\DAV\Server, after
58
-	 * addPlugin is called.
59
-	 *
60
-	 * This method should set up the required event subscriptions.
61
-	 *
62
-	 * @param \Sabre\DAV\Server $server
63
-	 * @return void
64
-	 */
65
-	function initialize(\Sabre\DAV\Server $server) {
66
-		$this->server = $server;
67
-		$this->server->on('propFind', array($this, 'handleGetProperties'));
68
-	}
69
-
70
-	/**
71
-	 * Adds tags and favorites properties to the response,
72
-	 * if requested.
73
-	 *
74
-	 * @param PropFind $propFind
75
-	 * @param \Sabre\DAV\INode $node
76
-	 * @return void
77
-	 */
78
-	public function handleGetProperties(
79
-		PropFind $propFind,
80
-		\Sabre\DAV\INode $node
81
-	) {
82
-		if (!($node instanceof File) && !($node instanceof Directory)) {
83
-			return;
84
-		}
85
-
86
-		// need prefetch ?
87
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Directory
88
-			&& $propFind->getDepth() !== 0
89
-			&& !is_null($propFind->getStatus(self::PROPERTY_NAME_UNREAD))
90
-		) {
91
-			$unreadCounts = $this->commentsManager->getNumberOfUnreadCommentsForFolder($node->getId(), $this->userSession->getUser());
92
-			$this->cachedFolders[] = $node->getPath();
93
-			foreach ($unreadCounts as $id => $count) {
94
-				$this->cachedUnreadCount[$id] = $count;
95
-			}
96
-		}
97
-
98
-		$propFind->handle(self::PROPERTY_NAME_COUNT, function() use ($node) {
99
-			return $this->commentsManager->getNumberOfCommentsForObject('files', strval($node->getId()));
100
-		});
101
-
102
-		$propFind->handle(self::PROPERTY_NAME_HREF, function() use ($node) {
103
-			return $this->getCommentsLink($node);
104
-		});
105
-
106
-		$propFind->handle(self::PROPERTY_NAME_UNREAD, function() use ($node) {
107
-			if (isset($this->cachedUnreadCount[$node->getId()])) {
108
-				return $this->cachedUnreadCount[$node->getId()];
109
-			} else {
110
-				list($parentPath,) = \Sabre\Uri\split($node->getPath());
111
-				if ($parentPath === '') {
112
-					$parentPath = '/';
113
-				}
114
-				// if we already cached the folder this file is in we know there are no shares for this file
115
-				if (array_search($parentPath, $this->cachedFolders) === false) {
116
-					return $this->getUnreadCount($node);
117
-				} else {
118
-					return 0;
119
-				}
120
-			}
121
-		});
122
-	}
123
-
124
-	/**
125
-	 * returns a reference to the comments node
126
-	 *
127
-	 * @param Node $node
128
-	 * @return mixed|string
129
-	 */
130
-	public function getCommentsLink(Node $node) {
131
-		$href =  $this->server->getBaseUri();
132
-		$entryPoint = strpos($href, '/remote.php/');
133
-		if($entryPoint === false) {
134
-			// in case we end up somewhere else, unexpectedly.
135
-			return null;
136
-		}
137
-		$commentsPart = 'dav/comments/files/' . rawurldecode($node->getId());
138
-		$href = substr_replace($href, $commentsPart, $entryPoint + strlen('/remote.php/'));
139
-		return $href;
140
-	}
141
-
142
-	/**
143
-	 * returns the number of unread comments for the currently logged in user
144
-	 * on the given file or directory node
145
-	 *
146
-	 * @param Node $node
147
-	 * @return Int|null
148
-	 */
149
-	public function getUnreadCount(Node $node) {
150
-		$user = $this->userSession->getUser();
151
-		if(is_null($user)) {
152
-			return null;
153
-		}
154
-
155
-		$lastRead = $this->commentsManager->getReadMark('files', strval($node->getId()), $user);
156
-
157
-		return $this->commentsManager->getNumberOfCommentsForObject('files', strval($node->getId()), $lastRead);
158
-	}
32
+    const PROPERTY_NAME_HREF   = '{http://owncloud.org/ns}comments-href';
33
+    const PROPERTY_NAME_COUNT  = '{http://owncloud.org/ns}comments-count';
34
+    const PROPERTY_NAME_UNREAD = '{http://owncloud.org/ns}comments-unread';
35
+
36
+    /** @var  \Sabre\DAV\Server */
37
+    protected $server;
38
+
39
+    /** @var ICommentsManager */
40
+    private $commentsManager;
41
+
42
+    /** @var IUserSession */
43
+    private $userSession;
44
+
45
+    private $cachedUnreadCount = [];
46
+
47
+    private $cachedFolders = [];
48
+
49
+    public function __construct(ICommentsManager $commentsManager, IUserSession $userSession) {
50
+        $this->commentsManager = $commentsManager;
51
+        $this->userSession = $userSession;
52
+    }
53
+
54
+    /**
55
+     * This initializes the plugin.
56
+     *
57
+     * This function is called by Sabre\DAV\Server, after
58
+     * addPlugin is called.
59
+     *
60
+     * This method should set up the required event subscriptions.
61
+     *
62
+     * @param \Sabre\DAV\Server $server
63
+     * @return void
64
+     */
65
+    function initialize(\Sabre\DAV\Server $server) {
66
+        $this->server = $server;
67
+        $this->server->on('propFind', array($this, 'handleGetProperties'));
68
+    }
69
+
70
+    /**
71
+     * Adds tags and favorites properties to the response,
72
+     * if requested.
73
+     *
74
+     * @param PropFind $propFind
75
+     * @param \Sabre\DAV\INode $node
76
+     * @return void
77
+     */
78
+    public function handleGetProperties(
79
+        PropFind $propFind,
80
+        \Sabre\DAV\INode $node
81
+    ) {
82
+        if (!($node instanceof File) && !($node instanceof Directory)) {
83
+            return;
84
+        }
85
+
86
+        // need prefetch ?
87
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Directory
88
+            && $propFind->getDepth() !== 0
89
+            && !is_null($propFind->getStatus(self::PROPERTY_NAME_UNREAD))
90
+        ) {
91
+            $unreadCounts = $this->commentsManager->getNumberOfUnreadCommentsForFolder($node->getId(), $this->userSession->getUser());
92
+            $this->cachedFolders[] = $node->getPath();
93
+            foreach ($unreadCounts as $id => $count) {
94
+                $this->cachedUnreadCount[$id] = $count;
95
+            }
96
+        }
97
+
98
+        $propFind->handle(self::PROPERTY_NAME_COUNT, function() use ($node) {
99
+            return $this->commentsManager->getNumberOfCommentsForObject('files', strval($node->getId()));
100
+        });
101
+
102
+        $propFind->handle(self::PROPERTY_NAME_HREF, function() use ($node) {
103
+            return $this->getCommentsLink($node);
104
+        });
105
+
106
+        $propFind->handle(self::PROPERTY_NAME_UNREAD, function() use ($node) {
107
+            if (isset($this->cachedUnreadCount[$node->getId()])) {
108
+                return $this->cachedUnreadCount[$node->getId()];
109
+            } else {
110
+                list($parentPath,) = \Sabre\Uri\split($node->getPath());
111
+                if ($parentPath === '') {
112
+                    $parentPath = '/';
113
+                }
114
+                // if we already cached the folder this file is in we know there are no shares for this file
115
+                if (array_search($parentPath, $this->cachedFolders) === false) {
116
+                    return $this->getUnreadCount($node);
117
+                } else {
118
+                    return 0;
119
+                }
120
+            }
121
+        });
122
+    }
123
+
124
+    /**
125
+     * returns a reference to the comments node
126
+     *
127
+     * @param Node $node
128
+     * @return mixed|string
129
+     */
130
+    public function getCommentsLink(Node $node) {
131
+        $href =  $this->server->getBaseUri();
132
+        $entryPoint = strpos($href, '/remote.php/');
133
+        if($entryPoint === false) {
134
+            // in case we end up somewhere else, unexpectedly.
135
+            return null;
136
+        }
137
+        $commentsPart = 'dav/comments/files/' . rawurldecode($node->getId());
138
+        $href = substr_replace($href, $commentsPart, $entryPoint + strlen('/remote.php/'));
139
+        return $href;
140
+    }
141
+
142
+    /**
143
+     * returns the number of unread comments for the currently logged in user
144
+     * on the given file or directory node
145
+     *
146
+     * @param Node $node
147
+     * @return Int|null
148
+     */
149
+    public function getUnreadCount(Node $node) {
150
+        $user = $this->userSession->getUser();
151
+        if(is_null($user)) {
152
+            return null;
153
+        }
154
+
155
+        $lastRead = $this->commentsManager->getReadMark('files', strval($node->getId()), $user);
156
+
157
+        return $this->commentsManager->getNumberOfCommentsForObject('files', strval($node->getId()), $lastRead);
158
+    }
159 159
 
160 160
 }
Please login to merge, or discard this patch.
lib/public/Comments/ICommentsManager.php 1 patch
Indentation   +233 added lines, -233 removed lines patch added patch discarded remove patch
@@ -35,255 +35,255 @@
 block discarded – undo
35 35
  */
36 36
 interface ICommentsManager {
37 37
 
38
-	/**
39
-	 * @const DELETED_USER type and id for a user that has been deleted
40
-	 * @see deleteReferencesOfActor
41
-	 * @since 9.0.0
42
-	 *
43
-	 * To be used as replacement for user type actors in deleteReferencesOfActor().
44
-	 *
45
-	 * User interfaces shall show "Deleted user" as display name, if needed.
46
-	 */
47
-	const DELETED_USER = 'deleted_users';
38
+    /**
39
+     * @const DELETED_USER type and id for a user that has been deleted
40
+     * @see deleteReferencesOfActor
41
+     * @since 9.0.0
42
+     *
43
+     * To be used as replacement for user type actors in deleteReferencesOfActor().
44
+     *
45
+     * User interfaces shall show "Deleted user" as display name, if needed.
46
+     */
47
+    const DELETED_USER = 'deleted_users';
48 48
 
49
-	/**
50
-	 * returns a comment instance
51
-	 *
52
-	 * @param string $id the ID of the comment
53
-	 * @return IComment
54
-	 * @throws NotFoundException
55
-	 * @since 9.0.0
56
-	 */
57
-	public function get($id);
49
+    /**
50
+     * returns a comment instance
51
+     *
52
+     * @param string $id the ID of the comment
53
+     * @return IComment
54
+     * @throws NotFoundException
55
+     * @since 9.0.0
56
+     */
57
+    public function get($id);
58 58
 
59
-	/**
60
-	 * returns the comment specified by the id and all it's child comments
61
-	 *
62
-	 * @param string $id
63
-	 * @param int $limit max number of entries to return, 0 returns all
64
-	 * @param int $offset the start entry
65
-	 * @return array
66
-	 * @since 9.0.0
67
-	 *
68
-	 * The return array looks like this
69
-	 * [
70
-	 * 	 'comment' => IComment, // root comment
71
-	 *   'replies' =>
72
-	 *   [
73
-	 *     0 =>
74
-	 *     [
75
-	 *       'comment' => IComment,
76
-	 *       'replies' =>
77
-	 *       [
78
-	 *         0 =>
79
-	 *         [
80
-	 *           'comment' => IComment,
81
-	 *           'replies' => [ … ]
82
-	 *         ],
83
-	 *         …
84
-	 *       ]
85
-	 *     ]
86
-	 *     1 =>
87
-	 *     [
88
-	 *       'comment' => IComment,
89
-	 *       'replies'=> [ … ]
90
-	 *     ],
91
-	 *     …
92
-	 *   ]
93
-	 * ]
94
-	 */
95
-	public function getTree($id, $limit = 0, $offset = 0);
59
+    /**
60
+     * returns the comment specified by the id and all it's child comments
61
+     *
62
+     * @param string $id
63
+     * @param int $limit max number of entries to return, 0 returns all
64
+     * @param int $offset the start entry
65
+     * @return array
66
+     * @since 9.0.0
67
+     *
68
+     * The return array looks like this
69
+     * [
70
+     * 	 'comment' => IComment, // root comment
71
+     *   'replies' =>
72
+     *   [
73
+     *     0 =>
74
+     *     [
75
+     *       'comment' => IComment,
76
+     *       'replies' =>
77
+     *       [
78
+     *         0 =>
79
+     *         [
80
+     *           'comment' => IComment,
81
+     *           'replies' => [ … ]
82
+     *         ],
83
+     *         …
84
+     *       ]
85
+     *     ]
86
+     *     1 =>
87
+     *     [
88
+     *       'comment' => IComment,
89
+     *       'replies'=> [ … ]
90
+     *     ],
91
+     *     …
92
+     *   ]
93
+     * ]
94
+     */
95
+    public function getTree($id, $limit = 0, $offset = 0);
96 96
 
97
-	/**
98
-	 * returns comments for a specific object (e.g. a file).
99
-	 *
100
-	 * The sort order is always newest to oldest.
101
-	 *
102
-	 * @param string $objectType the object type, e.g. 'files'
103
-	 * @param string $objectId the id of the object
104
-	 * @param int $limit optional, number of maximum comments to be returned. if
105
-	 * not specified, all comments are returned.
106
-	 * @param int $offset optional, starting point
107
-	 * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
108
-	 * that may be returned
109
-	 * @return IComment[]
110
-	 * @since 9.0.0
111
-	 */
112
-	public function getForObject(
113
-			$objectType,
114
-			$objectId,
115
-			$limit = 0,
116
-			$offset = 0,
117
-			\DateTime $notOlderThan = null
118
-	);
97
+    /**
98
+     * returns comments for a specific object (e.g. a file).
99
+     *
100
+     * The sort order is always newest to oldest.
101
+     *
102
+     * @param string $objectType the object type, e.g. 'files'
103
+     * @param string $objectId the id of the object
104
+     * @param int $limit optional, number of maximum comments to be returned. if
105
+     * not specified, all comments are returned.
106
+     * @param int $offset optional, starting point
107
+     * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
108
+     * that may be returned
109
+     * @return IComment[]
110
+     * @since 9.0.0
111
+     */
112
+    public function getForObject(
113
+            $objectType,
114
+            $objectId,
115
+            $limit = 0,
116
+            $offset = 0,
117
+            \DateTime $notOlderThan = null
118
+    );
119 119
 
120
-	/**
121
-	 * @param $objectType string the object type, e.g. 'files'
122
-	 * @param $objectId string the id of the object
123
-	 * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
124
-	 * that may be returned
125
-	 * @return Int
126
-	 * @since 9.0.0
127
-	 */
128
-	public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null);
120
+    /**
121
+     * @param $objectType string the object type, e.g. 'files'
122
+     * @param $objectId string the id of the object
123
+     * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
124
+     * that may be returned
125
+     * @return Int
126
+     * @since 9.0.0
127
+     */
128
+    public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null);
129 129
 
130
-	/**
131
-	 * Get the number of unread comments for all files in a folder
132
-	 *
133
-	 * @param int $folderId
134
-	 * @param IUser $user
135
-	 * @return array [$fileId => $unreadCount]
136
-	 * @since 12.0.0
137
-	 */
138
-	public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user);
130
+    /**
131
+     * Get the number of unread comments for all files in a folder
132
+     *
133
+     * @param int $folderId
134
+     * @param IUser $user
135
+     * @return array [$fileId => $unreadCount]
136
+     * @since 12.0.0
137
+     */
138
+    public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user);
139 139
 
140
-	/**
141
-	 * creates a new comment and returns it. At this point of time, it is not
142
-	 * saved in the used data storage. Use save() after setting other fields
143
-	 * of the comment (e.g. message or verb).
144
-	 *
145
-	 * @param string $actorType the actor type (e.g. 'users')
146
-	 * @param string $actorId a user id
147
-	 * @param string $objectType the object type the comment is attached to
148
-	 * @param string $objectId the object id the comment is attached to
149
-	 * @return IComment
150
-	 * @since 9.0.0
151
-	 */
152
-	public function create($actorType, $actorId, $objectType, $objectId);
140
+    /**
141
+     * creates a new comment and returns it. At this point of time, it is not
142
+     * saved in the used data storage. Use save() after setting other fields
143
+     * of the comment (e.g. message or verb).
144
+     *
145
+     * @param string $actorType the actor type (e.g. 'users')
146
+     * @param string $actorId a user id
147
+     * @param string $objectType the object type the comment is attached to
148
+     * @param string $objectId the object id the comment is attached to
149
+     * @return IComment
150
+     * @since 9.0.0
151
+     */
152
+    public function create($actorType, $actorId, $objectType, $objectId);
153 153
 
154
-	/**
155
-	 * permanently deletes the comment specified by the ID
156
-	 *
157
-	 * When the comment has child comments, their parent ID will be changed to
158
-	 * the parent ID of the item that is to be deleted.
159
-	 *
160
-	 * @param string $id
161
-	 * @return bool
162
-	 * @since 9.0.0
163
-	 */
164
-	public function delete($id);
154
+    /**
155
+     * permanently deletes the comment specified by the ID
156
+     *
157
+     * When the comment has child comments, their parent ID will be changed to
158
+     * the parent ID of the item that is to be deleted.
159
+     *
160
+     * @param string $id
161
+     * @return bool
162
+     * @since 9.0.0
163
+     */
164
+    public function delete($id);
165 165
 
166
-	/**
167
-	 * saves the comment permanently
168
-	 *
169
-	 * if the supplied comment has an empty ID, a new entry comment will be
170
-	 * saved and the instance updated with the new ID.
171
-	 *
172
-	 * Otherwise, an existing comment will be updated.
173
-	 *
174
-	 * Throws NotFoundException when a comment that is to be updated does not
175
-	 * exist anymore at this point of time.
176
-	 *
177
-	 * @param IComment $comment
178
-	 * @return bool
179
-	 * @throws NotFoundException
180
-	 * @since 9.0.0
181
-	 */
182
-	public function save(IComment $comment);
166
+    /**
167
+     * saves the comment permanently
168
+     *
169
+     * if the supplied comment has an empty ID, a new entry comment will be
170
+     * saved and the instance updated with the new ID.
171
+     *
172
+     * Otherwise, an existing comment will be updated.
173
+     *
174
+     * Throws NotFoundException when a comment that is to be updated does not
175
+     * exist anymore at this point of time.
176
+     *
177
+     * @param IComment $comment
178
+     * @return bool
179
+     * @throws NotFoundException
180
+     * @since 9.0.0
181
+     */
182
+    public function save(IComment $comment);
183 183
 
184
-	/**
185
-	 * removes references to specific actor (e.g. on user delete) of a comment.
186
-	 * The comment itself must not get lost/deleted.
187
-	 *
188
-	 * A 'users' type actor (type and id) should get replaced by the
189
-	 * value of the DELETED_USER constant of this interface.
190
-	 *
191
-	 * @param string $actorType the actor type (e.g. 'users')
192
-	 * @param string $actorId a user id
193
-	 * @return boolean
194
-	 * @since 9.0.0
195
-	 */
196
-	public function deleteReferencesOfActor($actorType, $actorId);
184
+    /**
185
+     * removes references to specific actor (e.g. on user delete) of a comment.
186
+     * The comment itself must not get lost/deleted.
187
+     *
188
+     * A 'users' type actor (type and id) should get replaced by the
189
+     * value of the DELETED_USER constant of this interface.
190
+     *
191
+     * @param string $actorType the actor type (e.g. 'users')
192
+     * @param string $actorId a user id
193
+     * @return boolean
194
+     * @since 9.0.0
195
+     */
196
+    public function deleteReferencesOfActor($actorType, $actorId);
197 197
 
198
-	/**
199
-	 * deletes all comments made of a specific object (e.g. on file delete)
200
-	 *
201
-	 * @param string $objectType the object type (e.g. 'files')
202
-	 * @param string $objectId e.g. the file id
203
-	 * @return boolean
204
-	 * @since 9.0.0
205
-	 */
206
-	public function deleteCommentsAtObject($objectType, $objectId);
198
+    /**
199
+     * deletes all comments made of a specific object (e.g. on file delete)
200
+     *
201
+     * @param string $objectType the object type (e.g. 'files')
202
+     * @param string $objectId e.g. the file id
203
+     * @return boolean
204
+     * @since 9.0.0
205
+     */
206
+    public function deleteCommentsAtObject($objectType, $objectId);
207 207
 
208
-	/**
209
-	 * sets the read marker for a given file to the specified date for the
210
-	 * provided user
211
-	 *
212
-	 * @param string $objectType
213
-	 * @param string $objectId
214
-	 * @param \DateTime $dateTime
215
-	 * @param \OCP\IUser $user
216
-	 * @since 9.0.0
217
-	 */
218
-	public function setReadMark($objectType, $objectId, \DateTime $dateTime, \OCP\IUser $user);
208
+    /**
209
+     * sets the read marker for a given file to the specified date for the
210
+     * provided user
211
+     *
212
+     * @param string $objectType
213
+     * @param string $objectId
214
+     * @param \DateTime $dateTime
215
+     * @param \OCP\IUser $user
216
+     * @since 9.0.0
217
+     */
218
+    public function setReadMark($objectType, $objectId, \DateTime $dateTime, \OCP\IUser $user);
219 219
 
220
-	/**
221
-	 * returns the read marker for a given file to the specified date for the
222
-	 * provided user. It returns null, when the marker is not present, i.e.
223
-	 * no comments were marked as read.
224
-	 *
225
-	 * @param string $objectType
226
-	 * @param string $objectId
227
-	 * @param \OCP\IUser $user
228
-	 * @return \DateTime|null
229
-	 * @since 9.0.0
230
-	 */
231
-	public function getReadMark($objectType, $objectId, \OCP\IUser $user);
220
+    /**
221
+     * returns the read marker for a given file to the specified date for the
222
+     * provided user. It returns null, when the marker is not present, i.e.
223
+     * no comments were marked as read.
224
+     *
225
+     * @param string $objectType
226
+     * @param string $objectId
227
+     * @param \OCP\IUser $user
228
+     * @return \DateTime|null
229
+     * @since 9.0.0
230
+     */
231
+    public function getReadMark($objectType, $objectId, \OCP\IUser $user);
232 232
 
233
-	/**
234
-	 * deletes the read markers for the specified user
235
-	 *
236
-	 * @param \OCP\IUser $user
237
-	 * @return bool
238
-	 * @since 9.0.0
239
-	 */
240
-	public function deleteReadMarksFromUser(\OCP\IUser $user);
233
+    /**
234
+     * deletes the read markers for the specified user
235
+     *
236
+     * @param \OCP\IUser $user
237
+     * @return bool
238
+     * @since 9.0.0
239
+     */
240
+    public function deleteReadMarksFromUser(\OCP\IUser $user);
241 241
 
242
-	/**
243
-	 * deletes the read markers on the specified object
244
-	 *
245
-	 * @param string $objectType
246
-	 * @param string $objectId
247
-	 * @return bool
248
-	 * @since 9.0.0
249
-	 */
250
-	public function deleteReadMarksOnObject($objectType, $objectId);
242
+    /**
243
+     * deletes the read markers on the specified object
244
+     *
245
+     * @param string $objectType
246
+     * @param string $objectId
247
+     * @return bool
248
+     * @since 9.0.0
249
+     */
250
+    public function deleteReadMarksOnObject($objectType, $objectId);
251 251
 
252
-	/**
253
-	 * registers an Entity to the manager, so event notifications can be send
254
-	 * to consumers of the comments infrastructure
255
-	 *
256
-	 * @param \Closure $closure
257
-	 * @since 11.0.0
258
-	 */
259
-	public function registerEventHandler(\Closure $closure);
252
+    /**
253
+     * registers an Entity to the manager, so event notifications can be send
254
+     * to consumers of the comments infrastructure
255
+     *
256
+     * @param \Closure $closure
257
+     * @since 11.0.0
258
+     */
259
+    public function registerEventHandler(\Closure $closure);
260 260
 
261
-	/**
262
-	 * registers a method that resolves an ID to a display name for a given type
263
-	 *
264
-	 * @param string $type
265
-	 * @param \Closure $closure
266
-	 * @throws \OutOfBoundsException
267
-	 * @since 11.0.0
268
-	 *
269
-	 * Only one resolver shall be registered per type. Otherwise a
270
-	 * \OutOfBoundsException has to thrown.
271
-	 */
272
-	public function registerDisplayNameResolver($type, \Closure $closure);
261
+    /**
262
+     * registers a method that resolves an ID to a display name for a given type
263
+     *
264
+     * @param string $type
265
+     * @param \Closure $closure
266
+     * @throws \OutOfBoundsException
267
+     * @since 11.0.0
268
+     *
269
+     * Only one resolver shall be registered per type. Otherwise a
270
+     * \OutOfBoundsException has to thrown.
271
+     */
272
+    public function registerDisplayNameResolver($type, \Closure $closure);
273 273
 
274
-	/**
275
-	 * resolves a given ID of a given Type to a display name.
276
-	 *
277
-	 * @param string $type
278
-	 * @param string $id
279
-	 * @return string
280
-	 * @throws \OutOfBoundsException
281
-	 * @since 11.0.0
282
-	 *
283
-	 * If a provided type was not registered, an \OutOfBoundsException shall
284
-	 * be thrown. It is upon the resolver discretion what to return of the
285
-	 * provided ID is unknown. It must be ensured that a string is returned.
286
-	 */
287
-	public function resolveDisplayName($type, $id);
274
+    /**
275
+     * resolves a given ID of a given Type to a display name.
276
+     *
277
+     * @param string $type
278
+     * @param string $id
279
+     * @return string
280
+     * @throws \OutOfBoundsException
281
+     * @since 11.0.0
282
+     *
283
+     * If a provided type was not registered, an \OutOfBoundsException shall
284
+     * be thrown. It is upon the resolver discretion what to return of the
285
+     * provided ID is unknown. It must be ensured that a string is returned.
286
+     */
287
+    public function resolveDisplayName($type, $id);
288 288
 
289 289
 }
Please login to merge, or discard this patch.
lib/private/DB/QueryBuilder/QuoteHelper.php 2 patches
Indentation   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -27,55 +27,55 @@
 block discarded – undo
27 27
 use OCP\DB\QueryBuilder\IQueryFunction;
28 28
 
29 29
 class QuoteHelper {
30
-	/**
31
-	 * @param array|string|ILiteral|IParameter|IQueryFunction $strings string, Literal or Parameter
32
-	 * @return array|string
33
-	 */
34
-	public function quoteColumnNames($strings) {
35
-		if (!is_array($strings)) {
36
-			return $this->quoteColumnName($strings);
37
-		}
30
+    /**
31
+     * @param array|string|ILiteral|IParameter|IQueryFunction $strings string, Literal or Parameter
32
+     * @return array|string
33
+     */
34
+    public function quoteColumnNames($strings) {
35
+        if (!is_array($strings)) {
36
+            return $this->quoteColumnName($strings);
37
+        }
38 38
 
39
-		$return = [];
40
-		foreach ($strings as $string) {
41
-			$return[] = $this->quoteColumnName($string);
42
-		}
39
+        $return = [];
40
+        foreach ($strings as $string) {
41
+            $return[] = $this->quoteColumnName($string);
42
+        }
43 43
 
44
-		return $return;
45
-	}
44
+        return $return;
45
+    }
46 46
 
47
-	/**
48
-	 * @param string|ILiteral|IParameter|IQueryFunction $string string, Literal or Parameter
49
-	 * @return string
50
-	 */
51
-	public function quoteColumnName($string) {
52
-		if ($string instanceof IParameter || $string instanceof ILiteral || $string instanceof IQueryFunction) {
53
-			return (string) $string;
54
-		}
47
+    /**
48
+     * @param string|ILiteral|IParameter|IQueryFunction $string string, Literal or Parameter
49
+     * @return string
50
+     */
51
+    public function quoteColumnName($string) {
52
+        if ($string instanceof IParameter || $string instanceof ILiteral || $string instanceof IQueryFunction) {
53
+            return (string) $string;
54
+        }
55 55
 
56
-		if ($string === null || $string === 'null' || $string === '*') {
57
-			return $string;
58
-		}
56
+        if ($string === null || $string === 'null' || $string === '*') {
57
+            return $string;
58
+        }
59 59
 
60
-		if (!is_string($string)) {
61
-			throw new \InvalidArgumentException('Only strings, Literals and Parameters are allowed');
62
-		}
60
+        if (!is_string($string)) {
61
+            throw new \InvalidArgumentException('Only strings, Literals and Parameters are allowed');
62
+        }
63 63
 
64
-		$string = str_replace(' AS ', ' as ', $string);
65
-		if (substr_count($string, ' as ')) {
66
-			return implode(' as ', array_map([$this, 'quoteColumnName'], explode(' as ', $string, 2)));
67
-		}
64
+        $string = str_replace(' AS ', ' as ', $string);
65
+        if (substr_count($string, ' as ')) {
66
+            return implode(' as ', array_map([$this, 'quoteColumnName'], explode(' as ', $string, 2)));
67
+        }
68 68
 
69
-		if (substr_count($string, '.')) {
70
-			list($alias, $columnName) = explode('.', $string, 2);
69
+        if (substr_count($string, '.')) {
70
+            list($alias, $columnName) = explode('.', $string, 2);
71 71
 
72
-			if ($columnName === '*') {
73
-				return $string;
74
-			}
72
+            if ($columnName === '*') {
73
+                return $string;
74
+            }
75 75
 
76
-			return '`' . $alias . '`.`' . $columnName . '`';
77
-		}
76
+            return '`' . $alias . '`.`' . $columnName . '`';
77
+        }
78 78
 
79
-		return '`' . $string . '`';
80
-	}
79
+        return '`' . $string . '`';
80
+    }
81 81
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -73,9 +73,9 @@
 block discarded – undo
73 73
 				return $string;
74 74
 			}
75 75
 
76
-			return '`' . $alias . '`.`' . $columnName . '`';
76
+			return '`'.$alias.'`.`'.$columnName.'`';
77 77
 		}
78 78
 
79
-		return '`' . $string . '`';
79
+		return '`'.$string.'`';
80 80
 	}
81 81
 }
Please login to merge, or discard this patch.