You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1310 lines
40 KiB

10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Joas Schilling <coding@schilljs.com>
  7. * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Robin Appelman <robin@icewind.nl>
  10. * @author Roeland Jago Douma <roeland@famdouma.nl>
  11. * @author Thomas Müller <thomas.mueller@tmit.eu>
  12. *
  13. * @license AGPL-3.0
  14. *
  15. * This code is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License, version 3,
  17. * as published by the Free Software Foundation.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License, version 3,
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>
  26. *
  27. */
  28. namespace OC\Comments;
  29. use Doctrine\DBAL\Exception\DriverException;
  30. use Doctrine\DBAL\Exception\InvalidFieldNameException;
  31. use OCA\Comments\AppInfo\Application;
  32. use OCP\AppFramework\Utility\ITimeFactory;
  33. use OCP\Comments\CommentsEvent;
  34. use OCP\Comments\IComment;
  35. use OCP\Comments\ICommentsEventHandler;
  36. use OCP\Comments\ICommentsManager;
  37. use OCP\Comments\NotFoundException;
  38. use OCP\DB\QueryBuilder\IQueryBuilder;
  39. use OCP\IConfig;
  40. use OCP\IDBConnection;
  41. use OCP\IUser;
  42. use OCP\IInitialStateService;
  43. use OCP\Util;
  44. use Psr\Log\LoggerInterface;
  45. class Manager implements ICommentsManager {
  46. /** @var IDBConnection */
  47. protected $dbConn;
  48. /** @var LoggerInterface */
  49. protected $logger;
  50. /** @var IConfig */
  51. protected $config;
  52. /** @var ITimeFactory */
  53. protected $timeFactory;
  54. /** @var IInitialStateService */
  55. protected $initialStateService;
  56. /** @var IComment[] */
  57. protected $commentsCache = [];
  58. /** @var \Closure[] */
  59. protected $eventHandlerClosures = [];
  60. /** @var ICommentsEventHandler[] */
  61. protected $eventHandlers = [];
  62. /** @var \Closure[] */
  63. protected $displayNameResolvers = [];
  64. public function __construct(IDBConnection $dbConn,
  65. LoggerInterface $logger,
  66. IConfig $config,
  67. ITimeFactory $timeFactory,
  68. IInitialStateService $initialStateService) {
  69. $this->dbConn = $dbConn;
  70. $this->logger = $logger;
  71. $this->config = $config;
  72. $this->timeFactory = $timeFactory;
  73. $this->initialStateService = $initialStateService;
  74. }
  75. /**
  76. * converts data base data into PHP native, proper types as defined by
  77. * IComment interface.
  78. *
  79. * @param array $data
  80. * @return array
  81. */
  82. protected function normalizeDatabaseData(array $data) {
  83. $data['id'] = (string)$data['id'];
  84. $data['parent_id'] = (string)$data['parent_id'];
  85. $data['topmost_parent_id'] = (string)$data['topmost_parent_id'];
  86. $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
  87. if (!is_null($data['latest_child_timestamp'])) {
  88. $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
  89. }
  90. $data['children_count'] = (int)$data['children_count'];
  91. $data['reference_id'] = $data['reference_id'] ?? null;
  92. return $data;
  93. }
  94. /**
  95. * @param array $data
  96. * @return IComment
  97. */
  98. public function getCommentFromData(array $data): IComment {
  99. return new Comment($this->normalizeDatabaseData($data));
  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. if ($comment->getId() === '') {
  120. $comment->setChildrenCount(0);
  121. $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
  122. $comment->setLatestChildDateTime(null);
  123. }
  124. if (is_null($comment->getCreationDateTime())) {
  125. $comment->setCreationDateTime(new \DateTime());
  126. }
  127. if ($comment->getParentId() !== '0') {
  128. $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
  129. } else {
  130. $comment->setTopmostParentId('0');
  131. }
  132. $this->cache($comment);
  133. return $comment;
  134. }
  135. /**
  136. * returns the topmost parent id of a given comment identified by ID
  137. *
  138. * @param string $id
  139. * @return string
  140. * @throws NotFoundException
  141. */
  142. protected function determineTopmostParentId($id) {
  143. $comment = $this->get($id);
  144. if ($comment->getParentId() === '0') {
  145. return $comment->getId();
  146. }
  147. return $this->determineTopmostParentId($comment->getParentId());
  148. }
  149. /**
  150. * updates child information of a comment
  151. *
  152. * @param string $id
  153. * @param \DateTime $cDateTime the date time of the most recent child
  154. * @throws NotFoundException
  155. */
  156. protected function updateChildrenInformation($id, \DateTime $cDateTime) {
  157. $qb = $this->dbConn->getQueryBuilder();
  158. $query = $qb->select($qb->func()->count('id'))
  159. ->from('comments')
  160. ->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
  161. ->setParameter('id', $id);
  162. $resultStatement = $query->execute();
  163. $data = $resultStatement->fetch(\PDO::FETCH_NUM);
  164. $resultStatement->closeCursor();
  165. $children = (int)$data[0];
  166. $comment = $this->get($id);
  167. $comment->setChildrenCount($children);
  168. $comment->setLatestChildDateTime($cDateTime);
  169. $this->save($comment);
  170. }
  171. /**
  172. * Tests whether actor or object type and id parameters are acceptable.
  173. * Throws exception if not.
  174. *
  175. * @param string $role
  176. * @param string $type
  177. * @param string $id
  178. * @throws \InvalidArgumentException
  179. */
  180. protected function checkRoleParameters($role, $type, $id) {
  181. if (
  182. !is_string($type) || empty($type)
  183. || !is_string($id) || empty($id)
  184. ) {
  185. throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
  186. }
  187. }
  188. /**
  189. * run-time caches a comment
  190. *
  191. * @param IComment $comment
  192. */
  193. protected function cache(IComment $comment) {
  194. $id = $comment->getId();
  195. if (empty($id)) {
  196. return;
  197. }
  198. $this->commentsCache[(string)$id] = $comment;
  199. }
  200. /**
  201. * removes an entry from the comments run time cache
  202. *
  203. * @param mixed $id the comment's id
  204. */
  205. protected function uncache($id) {
  206. $id = (string)$id;
  207. if (isset($this->commentsCache[$id])) {
  208. unset($this->commentsCache[$id]);
  209. }
  210. }
  211. /**
  212. * returns a comment instance
  213. *
  214. * @param string $id the ID of the comment
  215. * @return IComment
  216. * @throws NotFoundException
  217. * @throws \InvalidArgumentException
  218. * @since 9.0.0
  219. */
  220. public function get($id) {
  221. if ((int)$id === 0) {
  222. throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
  223. }
  224. if (isset($this->commentsCache[$id])) {
  225. return $this->commentsCache[$id];
  226. }
  227. $qb = $this->dbConn->getQueryBuilder();
  228. $resultStatement = $qb->select('*')
  229. ->from('comments')
  230. ->where($qb->expr()->eq('id', $qb->createParameter('id')))
  231. ->setParameter('id', $id, IQueryBuilder::PARAM_INT)
  232. ->execute();
  233. $data = $resultStatement->fetch();
  234. $resultStatement->closeCursor();
  235. if (!$data) {
  236. throw new NotFoundException();
  237. }
  238. $comment = $this->getCommentFromData($data);
  239. $this->cache($comment);
  240. return $comment;
  241. }
  242. /**
  243. * returns the comment specified by the id and all it's child comments.
  244. * At this point of time, we do only support one level depth.
  245. *
  246. * @param string $id
  247. * @param int $limit max number of entries to return, 0 returns all
  248. * @param int $offset the start entry
  249. * @return array
  250. * @since 9.0.0
  251. *
  252. * The return array looks like this
  253. * [
  254. * 'comment' => IComment, // root comment
  255. * 'replies' =>
  256. * [
  257. * 0 =>
  258. * [
  259. * 'comment' => IComment,
  260. * 'replies' => []
  261. * ]
  262. * 1 =>
  263. * [
  264. * 'comment' => IComment,
  265. * 'replies'=> []
  266. * ],
  267. *
  268. * ]
  269. * ]
  270. */
  271. public function getTree($id, $limit = 0, $offset = 0) {
  272. $tree = [];
  273. $tree['comment'] = $this->get($id);
  274. $tree['replies'] = [];
  275. $qb = $this->dbConn->getQueryBuilder();
  276. $query = $qb->select('*')
  277. ->from('comments')
  278. ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
  279. ->orderBy('creation_timestamp', 'DESC')
  280. ->setParameter('id', $id);
  281. if ($limit > 0) {
  282. $query->setMaxResults($limit);
  283. }
  284. if ($offset > 0) {
  285. $query->setFirstResult($offset);
  286. }
  287. $resultStatement = $query->execute();
  288. while ($data = $resultStatement->fetch()) {
  289. $comment = $this->getCommentFromData($data);
  290. $this->cache($comment);
  291. $tree['replies'][] = [
  292. 'comment' => $comment,
  293. 'replies' => []
  294. ];
  295. }
  296. $resultStatement->closeCursor();
  297. return $tree;
  298. }
  299. /**
  300. * returns comments for a specific object (e.g. a file).
  301. *
  302. * The sort order is always newest to oldest.
  303. *
  304. * @param string $objectType the object type, e.g. 'files'
  305. * @param string $objectId the id of the object
  306. * @param int $limit optional, number of maximum comments to be returned. if
  307. * not specified, all comments are returned.
  308. * @param int $offset optional, starting point
  309. * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
  310. * that may be returned
  311. * @return IComment[]
  312. * @since 9.0.0
  313. */
  314. public function getForObject(
  315. $objectType,
  316. $objectId,
  317. $limit = 0,
  318. $offset = 0,
  319. \DateTime $notOlderThan = null
  320. ) {
  321. $comments = [];
  322. $qb = $this->dbConn->getQueryBuilder();
  323. $query = $qb->select('*')
  324. ->from('comments')
  325. ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
  326. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
  327. ->orderBy('creation_timestamp', 'DESC')
  328. ->setParameter('type', $objectType)
  329. ->setParameter('id', $objectId);
  330. if ($limit > 0) {
  331. $query->setMaxResults($limit);
  332. }
  333. if ($offset > 0) {
  334. $query->setFirstResult($offset);
  335. }
  336. if (!is_null($notOlderThan)) {
  337. $query
  338. ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
  339. ->setParameter('notOlderThan', $notOlderThan, 'datetime');
  340. }
  341. $resultStatement = $query->execute();
  342. while ($data = $resultStatement->fetch()) {
  343. $comment = $this->getCommentFromData($data);
  344. $this->cache($comment);
  345. $comments[] = $comment;
  346. }
  347. $resultStatement->closeCursor();
  348. return $comments;
  349. }
  350. /**
  351. * @param string $objectType the object type, e.g. 'files'
  352. * @param string $objectId the id of the object
  353. * @param int $lastKnownCommentId the last known comment (will be used as offset)
  354. * @param string $sortDirection direction of the comments (`asc` or `desc`)
  355. * @param int $limit optional, number of maximum comments to be returned. if
  356. * set to 0, all comments are returned.
  357. * @param bool $includeLastKnown
  358. * @return IComment[]
  359. * @return array
  360. */
  361. public function getForObjectSince(
  362. string $objectType,
  363. string $objectId,
  364. int $lastKnownCommentId,
  365. string $sortDirection = 'asc',
  366. int $limit = 30,
  367. bool $includeLastKnown = false
  368. ): array {
  369. $comments = [];
  370. $query = $this->dbConn->getQueryBuilder();
  371. $query->select('*')
  372. ->from('comments')
  373. ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
  374. ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
  375. ->orderBy('creation_timestamp', $sortDirection === 'desc' ? 'DESC' : 'ASC')
  376. ->addOrderBy('id', $sortDirection === 'desc' ? 'DESC' : 'ASC');
  377. if ($limit > 0) {
  378. $query->setMaxResults($limit);
  379. }
  380. $lastKnownComment = $lastKnownCommentId > 0 ? $this->getLastKnownComment(
  381. $objectType,
  382. $objectId,
  383. $lastKnownCommentId
  384. ) : null;
  385. if ($lastKnownComment instanceof IComment) {
  386. $lastKnownCommentDateTime = $lastKnownComment->getCreationDateTime();
  387. if ($sortDirection === 'desc') {
  388. if ($includeLastKnown) {
  389. $idComparison = $query->expr()->lte('id', $query->createNamedParameter($lastKnownCommentId));
  390. } else {
  391. $idComparison = $query->expr()->lt('id', $query->createNamedParameter($lastKnownCommentId));
  392. }
  393. $query->andWhere(
  394. $query->expr()->orX(
  395. $query->expr()->lt(
  396. 'creation_timestamp',
  397. $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
  398. IQueryBuilder::PARAM_DATE
  399. ),
  400. $query->expr()->andX(
  401. $query->expr()->eq(
  402. 'creation_timestamp',
  403. $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
  404. IQueryBuilder::PARAM_DATE
  405. ),
  406. $idComparison
  407. )
  408. )
  409. );
  410. } else {
  411. if ($includeLastKnown) {
  412. $idComparison = $query->expr()->gte('id', $query->createNamedParameter($lastKnownCommentId));
  413. } else {
  414. $idComparison = $query->expr()->gt('id', $query->createNamedParameter($lastKnownCommentId));
  415. }
  416. $query->andWhere(
  417. $query->expr()->orX(
  418. $query->expr()->gt(
  419. 'creation_timestamp',
  420. $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
  421. IQueryBuilder::PARAM_DATE
  422. ),
  423. $query->expr()->andX(
  424. $query->expr()->eq(
  425. 'creation_timestamp',
  426. $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
  427. IQueryBuilder::PARAM_DATE
  428. ),
  429. $idComparison
  430. )
  431. )
  432. );
  433. }
  434. }
  435. $resultStatement = $query->execute();
  436. while ($data = $resultStatement->fetch()) {
  437. $comment = $this->getCommentFromData($data);
  438. $this->cache($comment);
  439. $comments[] = $comment;
  440. }
  441. $resultStatement->closeCursor();
  442. return $comments;
  443. }
  444. /**
  445. * @param string $objectType the object type, e.g. 'files'
  446. * @param string $objectId the id of the object
  447. * @param int $id the comment to look for
  448. * @return Comment|null
  449. */
  450. protected function getLastKnownComment(string $objectType,
  451. string $objectId,
  452. int $id) {
  453. $query = $this->dbConn->getQueryBuilder();
  454. $query->select('*')
  455. ->from('comments')
  456. ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
  457. ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
  458. ->andWhere($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
  459. $result = $query->execute();
  460. $row = $result->fetch();
  461. $result->closeCursor();
  462. if ($row) {
  463. $comment = $this->getCommentFromData($row);
  464. $this->cache($comment);
  465. return $comment;
  466. }
  467. return null;
  468. }
  469. /**
  470. * Search for comments with a given content
  471. *
  472. * @param string $search content to search for
  473. * @param string $objectType Limit the search by object type
  474. * @param string $objectId Limit the search by object id
  475. * @param string $verb Limit the verb of the comment
  476. * @param int $offset
  477. * @param int $limit
  478. * @return IComment[]
  479. */
  480. public function search(string $search, string $objectType, string $objectId, string $verb, int $offset, int $limit = 50): array {
  481. $objectIds = [];
  482. if ($objectId) {
  483. $objectIds[] = $objectIds;
  484. }
  485. return $this->searchForObjects($search, $objectType, $objectIds, $verb, $offset, $limit);
  486. }
  487. /**
  488. * Search for comments on one or more objects with a given content
  489. *
  490. * @param string $search content to search for
  491. * @param string $objectType Limit the search by object type
  492. * @param array $objectIds Limit the search by object ids
  493. * @param string $verb Limit the verb of the comment
  494. * @param int $offset
  495. * @param int $limit
  496. * @return IComment[]
  497. */
  498. public function searchForObjects(string $search, string $objectType, array $objectIds, string $verb, int $offset, int $limit = 50): array {
  499. $query = $this->dbConn->getQueryBuilder();
  500. $query->select('*')
  501. ->from('comments')
  502. ->where($query->expr()->iLike('message', $query->createNamedParameter(
  503. '%' . $this->dbConn->escapeLikeParameter($search). '%'
  504. )))
  505. ->orderBy('creation_timestamp', 'DESC')
  506. ->addOrderBy('id', 'DESC')
  507. ->setMaxResults($limit);
  508. if ($objectType !== '') {
  509. $query->andWhere($query->expr()->eq('object_type', $query->createNamedParameter($objectType)));
  510. }
  511. if (!empty($objectIds)) {
  512. $query->andWhere($query->expr()->in('object_id', $query->createNamedParameter($objectIds, IQueryBuilder::PARAM_STR_ARRAY)));
  513. }
  514. if ($verb !== '') {
  515. $query->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)));
  516. }
  517. if ($offset !== 0) {
  518. $query->setFirstResult($offset);
  519. }
  520. $comments = [];
  521. $result = $query->execute();
  522. while ($data = $result->fetch()) {
  523. $comment = $this->getCommentFromData($data);
  524. $this->cache($comment);
  525. $comments[] = $comment;
  526. }
  527. $result->closeCursor();
  528. return $comments;
  529. }
  530. /**
  531. * @param $objectType string the object type, e.g. 'files'
  532. * @param $objectId string the id of the object
  533. * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
  534. * that may be returned
  535. * @param string $verb Limit the verb of the comment - Added in 14.0.0
  536. * @return Int
  537. * @since 9.0.0
  538. */
  539. public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null, $verb = '') {
  540. $qb = $this->dbConn->getQueryBuilder();
  541. $query = $qb->select($qb->func()->count('id'))
  542. ->from('comments')
  543. ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
  544. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
  545. ->setParameter('type', $objectType)
  546. ->setParameter('id', $objectId);
  547. if (!is_null($notOlderThan)) {
  548. $query
  549. ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
  550. ->setParameter('notOlderThan', $notOlderThan, 'datetime');
  551. }
  552. if ($verb !== '') {
  553. $query->andWhere($qb->expr()->eq('verb', $qb->createNamedParameter($verb)));
  554. }
  555. $resultStatement = $query->execute();
  556. $data = $resultStatement->fetch(\PDO::FETCH_NUM);
  557. $resultStatement->closeCursor();
  558. return (int)$data[0];
  559. }
  560. /**
  561. * @param string $objectType the object type, e.g. 'files'
  562. * @param string[] $objectIds the id of the object
  563. * @param IUser $user
  564. * @param string $verb Limit the verb of the comment - Added in 14.0.0
  565. * @return array Map with object id => # of unread comments
  566. * @psalm-return array<string, int>
  567. * @since 21.0.0
  568. */
  569. public function getNumberOfUnreadCommentsForObjects(string $objectType, array $objectIds, IUser $user, $verb = ''): array {
  570. $query = $this->dbConn->getQueryBuilder();
  571. $query->select('c.object_id', $query->func()->count('c.id', 'num_comments'))
  572. ->from('comments', 'c')
  573. ->leftJoin('c', 'comments_read_markers', 'm', $query->expr()->andX(
  574. $query->expr()->eq('m.user_id', $query->createNamedParameter($user->getUID())),
  575. $query->expr()->eq('c.object_type', 'm.object_type'),
  576. $query->expr()->eq('c.object_id', 'm.object_id')
  577. ))
  578. ->where($query->expr()->eq('c.object_type', $query->createNamedParameter($objectType)))
  579. ->andWhere($query->expr()->in('c.object_id', $query->createNamedParameter($objectIds, IQueryBuilder::PARAM_STR_ARRAY)))
  580. ->andWhere($query->expr()->orX(
  581. $query->expr()->gt('c.creation_timestamp', 'm.marker_datetime'),
  582. $query->expr()->isNull('m.marker_datetime')
  583. ))
  584. ->groupBy('c.object_id');
  585. if ($verb !== '') {
  586. $query->andWhere($query->expr()->eq('c.verb', $query->createNamedParameter($verb)));
  587. }
  588. $result = $query->execute();
  589. $unreadComments = array_fill_keys($objectIds, 0);
  590. while ($row = $result->fetch()) {
  591. $unreadComments[$row['object_id']] = (int) $row['num_comments'];
  592. }
  593. $result->closeCursor();
  594. return $unreadComments;
  595. }
  596. /**
  597. * @param string $objectType
  598. * @param string $objectId
  599. * @param int $lastRead
  600. * @param string $verb
  601. * @return int
  602. * @since 21.0.0
  603. */
  604. public function getNumberOfCommentsForObjectSinceComment(string $objectType, string $objectId, int $lastRead, string $verb = ''): int {
  605. $query = $this->dbConn->getQueryBuilder();
  606. $query->select($query->func()->count('id', 'num_messages'))
  607. ->from('comments')
  608. ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
  609. ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
  610. ->andWhere($query->expr()->gt('id', $query->createNamedParameter($lastRead)));
  611. if ($verb !== '') {
  612. $query->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)));
  613. }
  614. $result = $query->execute();
  615. $data = $result->fetch();
  616. $result->closeCursor();
  617. return (int) ($data['num_messages'] ?? 0);
  618. }
  619. /**
  620. * @param string $objectType
  621. * @param string $objectId
  622. * @param \DateTime $beforeDate
  623. * @param string $verb
  624. * @return int
  625. * @since 21.0.0
  626. */
  627. public function getLastCommentBeforeDate(string $objectType, string $objectId, \DateTime $beforeDate, string $verb = ''): int {
  628. $query = $this->dbConn->getQueryBuilder();
  629. $query->select('id')
  630. ->from('comments')
  631. ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
  632. ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
  633. ->andWhere($query->expr()->lt('creation_timestamp', $query->createNamedParameter($beforeDate, IQueryBuilder::PARAM_DATE)))
  634. ->orderBy('creation_timestamp', 'desc');
  635. if ($verb !== '') {
  636. $query->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)));
  637. }
  638. $result = $query->execute();
  639. $data = $result->fetch();
  640. $result->closeCursor();
  641. return (int) ($data['id'] ?? 0);
  642. }
  643. /**
  644. * @param string $objectType
  645. * @param string $objectId
  646. * @param string $verb
  647. * @param string $actorType
  648. * @param string[] $actors
  649. * @return \DateTime[] Map of "string actor" => "\DateTime most recent comment date"
  650. * @psalm-return array<string, \DateTime>
  651. * @since 21.0.0
  652. */
  653. public function getLastCommentDateByActor(
  654. string $objectType,
  655. string $objectId,
  656. string $verb,
  657. string $actorType,
  658. array $actors
  659. ): array {
  660. $lastComments = [];
  661. $query = $this->dbConn->getQueryBuilder();
  662. $query->select('actor_id')
  663. ->selectAlias($query->createFunction('MAX(' . $query->getColumnName('creation_timestamp') . ')'), 'last_comment')
  664. ->from('comments')
  665. ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
  666. ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
  667. ->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)))
  668. ->andWhere($query->expr()->eq('actor_type', $query->createNamedParameter($actorType)))
  669. ->andWhere($query->expr()->in('actor_id', $query->createNamedParameter($actors, IQueryBuilder::PARAM_STR_ARRAY)))
  670. ->groupBy('actor_id');
  671. $result = $query->execute();
  672. while ($row = $result->fetch()) {
  673. $lastComments[$row['actor_id']] = $this->timeFactory->getDateTime($row['last_comment']);
  674. }
  675. $result->closeCursor();
  676. return $lastComments;
  677. }
  678. /**
  679. * Get the number of unread comments for all files in a folder
  680. *
  681. * @param int $folderId
  682. * @param IUser $user
  683. * @return array [$fileId => $unreadCount]
  684. */
  685. public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
  686. $qb = $this->dbConn->getQueryBuilder();
  687. $query = $qb->select('f.fileid')
  688. ->addSelect($qb->func()->count('c.id', 'num_ids'))
  689. ->from('filecache', 'f')
  690. ->leftJoin('f', 'comments', 'c', $qb->expr()->andX(
  691. $qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT)),
  692. $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files'))
  693. ))
  694. ->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX(
  695. $qb->expr()->eq('c.object_id', 'm.object_id'),
  696. $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files'))
  697. ))
  698. ->where(
  699. $qb->expr()->andX(
  700. $qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId)),
  701. $qb->expr()->orX(
  702. $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
  703. $qb->expr()->isNull('c.object_type')
  704. ),
  705. $qb->expr()->orX(
  706. $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')),
  707. $qb->expr()->isNull('m.object_type')
  708. ),
  709. $qb->expr()->orX(
  710. $qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID())),
  711. $qb->expr()->isNull('m.user_id')
  712. ),
  713. $qb->expr()->orX(
  714. $qb->expr()->gt('c.creation_timestamp', 'm.marker_datetime'),
  715. $qb->expr()->isNull('m.marker_datetime')
  716. )
  717. )
  718. )->groupBy('f.fileid');
  719. $resultStatement = $query->execute();
  720. $results = [];
  721. while ($row = $resultStatement->fetch()) {
  722. $results[$row['fileid']] = (int) $row['num_ids'];
  723. }
  724. $resultStatement->closeCursor();
  725. return $results;
  726. }
  727. /**
  728. * creates a new comment and returns it. At this point of time, it is not
  729. * saved in the used data storage. Use save() after setting other fields
  730. * of the comment (e.g. message or verb).
  731. *
  732. * @param string $actorType the actor type (e.g. 'users')
  733. * @param string $actorId a user id
  734. * @param string $objectType the object type the comment is attached to
  735. * @param string $objectId the object id the comment is attached to
  736. * @return IComment
  737. * @since 9.0.0
  738. */
  739. public function create($actorType, $actorId, $objectType, $objectId) {
  740. $comment = new Comment();
  741. $comment
  742. ->setActor($actorType, $actorId)
  743. ->setObject($objectType, $objectId);
  744. return $comment;
  745. }
  746. /**
  747. * permanently deletes the comment specified by the ID
  748. *
  749. * When the comment has child comments, their parent ID will be changed to
  750. * the parent ID of the item that is to be deleted.
  751. *
  752. * @param string $id
  753. * @return bool
  754. * @throws \InvalidArgumentException
  755. * @since 9.0.0
  756. */
  757. public function delete($id) {
  758. if (!is_string($id)) {
  759. throw new \InvalidArgumentException('Parameter must be string');
  760. }
  761. try {
  762. $comment = $this->get($id);
  763. } catch (\Exception $e) {
  764. // Ignore exceptions, we just don't fire a hook then
  765. $comment = null;
  766. }
  767. $qb = $this->dbConn->getQueryBuilder();
  768. $query = $qb->delete('comments')
  769. ->where($qb->expr()->eq('id', $qb->createParameter('id')))
  770. ->setParameter('id', $id);
  771. try {
  772. $affectedRows = $query->execute();
  773. $this->uncache($id);
  774. } catch (DriverException $e) {
  775. $this->logger->error($e->getMessage(), [
  776. 'exception' => $e,
  777. 'app' => 'core_comments',
  778. ]);
  779. return false;
  780. }
  781. if ($affectedRows > 0 && $comment instanceof IComment) {
  782. $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
  783. }
  784. return ($affectedRows > 0);
  785. }
  786. /**
  787. * saves the comment permanently
  788. *
  789. * if the supplied comment has an empty ID, a new entry comment will be
  790. * saved and the instance updated with the new ID.
  791. *
  792. * Otherwise, an existing comment will be updated.
  793. *
  794. * Throws NotFoundException when a comment that is to be updated does not
  795. * exist anymore at this point of time.
  796. *
  797. * @param IComment $comment
  798. * @return bool
  799. * @throws NotFoundException
  800. * @since 9.0.0
  801. */
  802. public function save(IComment $comment) {
  803. if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
  804. $result = $this->insert($comment);
  805. } else {
  806. $result = $this->update($comment);
  807. }
  808. if ($result && !!$comment->getParentId()) {
  809. $this->updateChildrenInformation(
  810. $comment->getParentId(),
  811. $comment->getCreationDateTime()
  812. );
  813. $this->cache($comment);
  814. }
  815. return $result;
  816. }
  817. /**
  818. * inserts the provided comment in the database
  819. *
  820. * @param IComment $comment
  821. * @return bool
  822. */
  823. protected function insert(IComment $comment): bool {
  824. try {
  825. $result = $this->insertQuery($comment, true);
  826. } catch (InvalidFieldNameException $e) {
  827. // The reference id field was only added in Nextcloud 19.
  828. // In order to not cause too long waiting times on the update,
  829. // it was decided to only add it lazy, as it is also not a critical
  830. // feature, but only helps to have a better experience while commenting.
  831. // So in case the reference_id field is missing,
  832. // we simply save the comment without that field.
  833. $result = $this->insertQuery($comment, false);
  834. }
  835. return $result;
  836. }
  837. protected function insertQuery(IComment $comment, bool $tryWritingReferenceId): bool {
  838. $qb = $this->dbConn->getQueryBuilder();
  839. $values = [
  840. 'parent_id' => $qb->createNamedParameter($comment->getParentId()),
  841. 'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
  842. 'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
  843. 'actor_type' => $qb->createNamedParameter($comment->getActorType()),
  844. 'actor_id' => $qb->createNamedParameter($comment->getActorId()),
  845. 'message' => $qb->createNamedParameter($comment->getMessage()),
  846. 'verb' => $qb->createNamedParameter($comment->getVerb()),
  847. 'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
  848. 'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
  849. 'object_type' => $qb->createNamedParameter($comment->getObjectType()),
  850. 'object_id' => $qb->createNamedParameter($comment->getObjectId()),
  851. ];
  852. if ($tryWritingReferenceId) {
  853. $values['reference_id'] = $qb->createNamedParameter($comment->getReferenceId());
  854. }
  855. $affectedRows = $qb->insert('comments')
  856. ->values($values)
  857. ->execute();
  858. if ($affectedRows > 0) {
  859. $comment->setId((string)$qb->getLastInsertId());
  860. $this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
  861. }
  862. return $affectedRows > 0;
  863. }
  864. /**
  865. * updates a Comment data row
  866. *
  867. * @param IComment $comment
  868. * @return bool
  869. * @throws NotFoundException
  870. */
  871. protected function update(IComment $comment) {
  872. // for properly working preUpdate Events we need the old comments as is
  873. // in the DB and overcome caching. Also avoid that outdated information stays.
  874. $this->uncache($comment->getId());
  875. $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
  876. $this->uncache($comment->getId());
  877. try {
  878. $result = $this->updateQuery($comment, true);
  879. } catch (InvalidFieldNameException $e) {
  880. // See function insert() for explanation
  881. $result = $this->updateQuery($comment, false);
  882. }
  883. $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
  884. return $result;
  885. }
  886. protected function updateQuery(IComment $comment, bool $tryWritingReferenceId): bool {
  887. $qb = $this->dbConn->getQueryBuilder();
  888. $qb
  889. ->update('comments')
  890. ->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
  891. ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
  892. ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
  893. ->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
  894. ->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
  895. ->set('message', $qb->createNamedParameter($comment->getMessage()))
  896. ->set('verb', $qb->createNamedParameter($comment->getVerb()))
  897. ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
  898. ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
  899. ->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
  900. ->set('object_id', $qb->createNamedParameter($comment->getObjectId()));
  901. if ($tryWritingReferenceId) {
  902. $qb->set('reference_id', $qb->createNamedParameter($comment->getReferenceId()));
  903. }
  904. $affectedRows = $qb->where($qb->expr()->eq('id', $qb->createNamedParameter($comment->getId())))
  905. ->execute();
  906. if ($affectedRows === 0) {
  907. throw new NotFoundException('Comment to update does ceased to exist');
  908. }
  909. return $affectedRows > 0;
  910. }
  911. /**
  912. * removes references to specific actor (e.g. on user delete) of a comment.
  913. * The comment itself must not get lost/deleted.
  914. *
  915. * @param string $actorType the actor type (e.g. 'users')
  916. * @param string $actorId a user id
  917. * @return boolean
  918. * @since 9.0.0
  919. */
  920. public function deleteReferencesOfActor($actorType, $actorId) {
  921. $this->checkRoleParameters('Actor', $actorType, $actorId);
  922. $qb = $this->dbConn->getQueryBuilder();
  923. $affectedRows = $qb
  924. ->update('comments')
  925. ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
  926. ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
  927. ->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
  928. ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
  929. ->setParameter('type', $actorType)
  930. ->setParameter('id', $actorId)
  931. ->execute();
  932. $this->commentsCache = [];
  933. return is_int($affectedRows);
  934. }
  935. /**
  936. * deletes all comments made of a specific object (e.g. on file delete)
  937. *
  938. * @param string $objectType the object type (e.g. 'files')
  939. * @param string $objectId e.g. the file id
  940. * @return boolean
  941. * @since 9.0.0
  942. */
  943. public function deleteCommentsAtObject($objectType, $objectId) {
  944. $this->checkRoleParameters('Object', $objectType, $objectId);
  945. $qb = $this->dbConn->getQueryBuilder();
  946. $affectedRows = $qb
  947. ->delete('comments')
  948. ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
  949. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
  950. ->setParameter('type', $objectType)
  951. ->setParameter('id', $objectId)
  952. ->execute();
  953. $this->commentsCache = [];
  954. return is_int($affectedRows);
  955. }
  956. /**
  957. * deletes the read markers for the specified user
  958. *
  959. * @param \OCP\IUser $user
  960. * @return bool
  961. * @since 9.0.0
  962. */
  963. public function deleteReadMarksFromUser(IUser $user) {
  964. $qb = $this->dbConn->getQueryBuilder();
  965. $query = $qb->delete('comments_read_markers')
  966. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  967. ->setParameter('user_id', $user->getUID());
  968. try {
  969. $affectedRows = $query->execute();
  970. } catch (DriverException $e) {
  971. $this->logger->error($e->getMessage(), [
  972. 'exception' => $e,
  973. 'app' => 'core_comments',
  974. ]);
  975. return false;
  976. }
  977. return ($affectedRows > 0);
  978. }
  979. /**
  980. * sets the read marker for a given file to the specified date for the
  981. * provided user
  982. *
  983. * @param string $objectType
  984. * @param string $objectId
  985. * @param \DateTime $dateTime
  986. * @param IUser $user
  987. * @since 9.0.0
  988. */
  989. public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
  990. $this->checkRoleParameters('Object', $objectType, $objectId);
  991. $qb = $this->dbConn->getQueryBuilder();
  992. $values = [
  993. 'user_id' => $qb->createNamedParameter($user->getUID()),
  994. 'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
  995. 'object_type' => $qb->createNamedParameter($objectType),
  996. 'object_id' => $qb->createNamedParameter($objectId),
  997. ];
  998. // Strategy: try to update, if this does not return affected rows, do an insert.
  999. $affectedRows = $qb
  1000. ->update('comments_read_markers')
  1001. ->set('user_id', $values['user_id'])
  1002. ->set('marker_datetime', $values['marker_datetime'])
  1003. ->set('object_type', $values['object_type'])
  1004. ->set('object_id', $values['object_id'])
  1005. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  1006. ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  1007. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  1008. ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
  1009. ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
  1010. ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
  1011. ->execute();
  1012. if ($affectedRows > 0) {
  1013. return;
  1014. }
  1015. $qb->insert('comments_read_markers')
  1016. ->values($values)
  1017. ->execute();
  1018. }
  1019. /**
  1020. * returns the read marker for a given file to the specified date for the
  1021. * provided user. It returns null, when the marker is not present, i.e.
  1022. * no comments were marked as read.
  1023. *
  1024. * @param string $objectType
  1025. * @param string $objectId
  1026. * @param IUser $user
  1027. * @return \DateTime|null
  1028. * @since 9.0.0
  1029. */
  1030. public function getReadMark($objectType, $objectId, IUser $user) {
  1031. $qb = $this->dbConn->getQueryBuilder();
  1032. $resultStatement = $qb->select('marker_datetime')
  1033. ->from('comments_read_markers')
  1034. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  1035. ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  1036. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  1037. ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
  1038. ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
  1039. ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
  1040. ->execute();
  1041. $data = $resultStatement->fetch();
  1042. $resultStatement->closeCursor();
  1043. if (!$data || is_null($data['marker_datetime'])) {
  1044. return null;
  1045. }
  1046. return new \DateTime($data['marker_datetime']);
  1047. }
  1048. /**
  1049. * deletes the read markers on the specified object
  1050. *
  1051. * @param string $objectType
  1052. * @param string $objectId
  1053. * @return bool
  1054. * @since 9.0.0
  1055. */
  1056. public function deleteReadMarksOnObject($objectType, $objectId) {
  1057. $this->checkRoleParameters('Object', $objectType, $objectId);
  1058. $qb = $this->dbConn->getQueryBuilder();
  1059. $query = $qb->delete('comments_read_markers')
  1060. ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  1061. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  1062. ->setParameter('object_type', $objectType)
  1063. ->setParameter('object_id', $objectId);
  1064. try {
  1065. $affectedRows = $query->execute();
  1066. } catch (DriverException $e) {
  1067. $this->logger->error($e->getMessage(), [
  1068. 'exception' => $e,
  1069. 'app' => 'core_comments',
  1070. ]);
  1071. return false;
  1072. }
  1073. return ($affectedRows > 0);
  1074. }
  1075. /**
  1076. * registers an Entity to the manager, so event notifications can be send
  1077. * to consumers of the comments infrastructure
  1078. *
  1079. * @param \Closure $closure
  1080. */
  1081. public function registerEventHandler(\Closure $closure) {
  1082. $this->eventHandlerClosures[] = $closure;
  1083. $this->eventHandlers = [];
  1084. }
  1085. /**
  1086. * registers a method that resolves an ID to a display name for a given type
  1087. *
  1088. * @param string $type
  1089. * @param \Closure $closure
  1090. * @throws \OutOfBoundsException
  1091. * @since 11.0.0
  1092. *
  1093. * Only one resolver shall be registered per type. Otherwise a
  1094. * \OutOfBoundsException has to thrown.
  1095. */
  1096. public function registerDisplayNameResolver($type, \Closure $closure) {
  1097. if (!is_string($type)) {
  1098. throw new \InvalidArgumentException('String expected.');
  1099. }
  1100. if (isset($this->displayNameResolvers[$type])) {
  1101. throw new \OutOfBoundsException('Displayname resolver for this type already registered');
  1102. }
  1103. $this->displayNameResolvers[$type] = $closure;
  1104. }
  1105. /**
  1106. * resolves a given ID of a given Type to a display name.
  1107. *
  1108. * @param string $type
  1109. * @param string $id
  1110. * @return string
  1111. * @throws \OutOfBoundsException
  1112. * @since 11.0.0
  1113. *
  1114. * If a provided type was not registered, an \OutOfBoundsException shall
  1115. * be thrown. It is upon the resolver discretion what to return of the
  1116. * provided ID is unknown. It must be ensured that a string is returned.
  1117. */
  1118. public function resolveDisplayName($type, $id) {
  1119. if (!is_string($type)) {
  1120. throw new \InvalidArgumentException('String expected.');
  1121. }
  1122. if (!isset($this->displayNameResolvers[$type])) {
  1123. throw new \OutOfBoundsException('No Displayname resolver for this type registered');
  1124. }
  1125. return (string)$this->displayNameResolvers[$type]($id);
  1126. }
  1127. /**
  1128. * returns valid, registered entities
  1129. *
  1130. * @return \OCP\Comments\ICommentsEventHandler[]
  1131. */
  1132. private function getEventHandlers() {
  1133. if (!empty($this->eventHandlers)) {
  1134. return $this->eventHandlers;
  1135. }
  1136. $this->eventHandlers = [];
  1137. foreach ($this->eventHandlerClosures as $name => $closure) {
  1138. $entity = $closure();
  1139. if (!($entity instanceof ICommentsEventHandler)) {
  1140. throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
  1141. }
  1142. $this->eventHandlers[$name] = $entity;
  1143. }
  1144. return $this->eventHandlers;
  1145. }
  1146. /**
  1147. * sends notifications to the registered entities
  1148. *
  1149. * @param $eventType
  1150. * @param IComment $comment
  1151. */
  1152. private function sendEvent($eventType, IComment $comment) {
  1153. $entities = $this->getEventHandlers();
  1154. $event = new CommentsEvent($eventType, $comment);
  1155. foreach ($entities as $entity) {
  1156. $entity->handle($event);
  1157. }
  1158. }
  1159. /**
  1160. * Load the Comments app into the page
  1161. *
  1162. * @since 21.0.0
  1163. */
  1164. public function load(): void {
  1165. $this->initialStateService->provideInitialState(Application::APP_ID, 'max-message-length', IComment::MAX_MESSAGE_LENGTH);
  1166. Util::addScript(Application::APP_ID, 'comments-app');
  1167. }
  1168. }