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.

1121 lines
33 KiB

3 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 Lukas Reschke <lukas@statuscode.ch>
  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 OCP\Comments\CommentsEvent;
  32. use OCP\Comments\IComment;
  33. use OCP\Comments\ICommentsEventHandler;
  34. use OCP\Comments\ICommentsManager;
  35. use OCP\Comments\NotFoundException;
  36. use OCP\DB\QueryBuilder\IQueryBuilder;
  37. use OCP\IConfig;
  38. use OCP\IDBConnection;
  39. use OCP\ILogger;
  40. use OCP\IUser;
  41. class Manager implements ICommentsManager {
  42. /** @var IDBConnection */
  43. protected $dbConn;
  44. /** @var ILogger */
  45. protected $logger;
  46. /** @var IConfig */
  47. protected $config;
  48. /** @var IComment[] */
  49. protected $commentsCache = [];
  50. /** @var \Closure[] */
  51. protected $eventHandlerClosures = [];
  52. /** @var ICommentsEventHandler[] */
  53. protected $eventHandlers = [];
  54. /** @var \Closure[] */
  55. protected $displayNameResolvers = [];
  56. /**
  57. * Manager constructor.
  58. *
  59. * @param IDBConnection $dbConn
  60. * @param ILogger $logger
  61. * @param IConfig $config
  62. */
  63. public function __construct(
  64. IDBConnection $dbConn,
  65. ILogger $logger,
  66. IConfig $config
  67. ) {
  68. $this->dbConn = $dbConn;
  69. $this->logger = $logger;
  70. $this->config = $config;
  71. }
  72. /**
  73. * converts data base data into PHP native, proper types as defined by
  74. * IComment interface.
  75. *
  76. * @param array $data
  77. * @return array
  78. */
  79. protected function normalizeDatabaseData(array $data) {
  80. $data['id'] = (string)$data['id'];
  81. $data['parent_id'] = (string)$data['parent_id'];
  82. $data['topmost_parent_id'] = (string)$data['topmost_parent_id'];
  83. $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
  84. if (!is_null($data['latest_child_timestamp'])) {
  85. $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
  86. }
  87. $data['children_count'] = (int)$data['children_count'];
  88. $data['reference_id'] = $data['reference_id'] ?? null;
  89. return $data;
  90. }
  91. /**
  92. * @param array $data
  93. * @return IComment
  94. */
  95. public function getCommentFromData(array $data): IComment {
  96. return new Comment($this->normalizeDatabaseData($data));
  97. }
  98. /**
  99. * prepares a comment for an insert or update operation after making sure
  100. * all necessary fields have a value assigned.
  101. *
  102. * @param IComment $comment
  103. * @return IComment returns the same updated IComment instance as provided
  104. * by parameter for convenience
  105. * @throws \UnexpectedValueException
  106. */
  107. protected function prepareCommentForDatabaseWrite(IComment $comment) {
  108. if (!$comment->getActorType()
  109. || $comment->getActorId() === ''
  110. || !$comment->getObjectType()
  111. || $comment->getObjectId() === ''
  112. || !$comment->getVerb()
  113. ) {
  114. throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
  115. }
  116. if ($comment->getId() === '') {
  117. $comment->setChildrenCount(0);
  118. $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
  119. $comment->setLatestChildDateTime(null);
  120. }
  121. if (is_null($comment->getCreationDateTime())) {
  122. $comment->setCreationDateTime(new \DateTime());
  123. }
  124. if ($comment->getParentId() !== '0') {
  125. $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
  126. } else {
  127. $comment->setTopmostParentId('0');
  128. }
  129. $this->cache($comment);
  130. return $comment;
  131. }
  132. /**
  133. * returns the topmost parent id of a given comment identified by ID
  134. *
  135. * @param string $id
  136. * @return string
  137. * @throws NotFoundException
  138. */
  139. protected function determineTopmostParentId($id) {
  140. $comment = $this->get($id);
  141. if ($comment->getParentId() === '0') {
  142. return $comment->getId();
  143. }
  144. return $this->determineTopmostParentId($comment->getParentId());
  145. }
  146. /**
  147. * updates child information of a comment
  148. *
  149. * @param string $id
  150. * @param \DateTime $cDateTime the date time of the most recent child
  151. * @throws NotFoundException
  152. */
  153. protected function updateChildrenInformation($id, \DateTime $cDateTime) {
  154. $qb = $this->dbConn->getQueryBuilder();
  155. $query = $qb->select($qb->func()->count('id'))
  156. ->from('comments')
  157. ->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
  158. ->setParameter('id', $id);
  159. $resultStatement = $query->execute();
  160. $data = $resultStatement->fetch(\PDO::FETCH_NUM);
  161. $resultStatement->closeCursor();
  162. $children = (int)$data[0];
  163. $comment = $this->get($id);
  164. $comment->setChildrenCount($children);
  165. $comment->setLatestChildDateTime($cDateTime);
  166. $this->save($comment);
  167. }
  168. /**
  169. * Tests whether actor or object type and id parameters are acceptable.
  170. * Throws exception if not.
  171. *
  172. * @param string $role
  173. * @param string $type
  174. * @param string $id
  175. * @throws \InvalidArgumentException
  176. */
  177. protected function checkRoleParameters($role, $type, $id) {
  178. if (
  179. !is_string($type) || empty($type)
  180. || !is_string($id) || empty($id)
  181. ) {
  182. throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
  183. }
  184. }
  185. /**
  186. * run-time caches a comment
  187. *
  188. * @param IComment $comment
  189. */
  190. protected function cache(IComment $comment) {
  191. $id = $comment->getId();
  192. if (empty($id)) {
  193. return;
  194. }
  195. $this->commentsCache[(string)$id] = $comment;
  196. }
  197. /**
  198. * removes an entry from the comments run time cache
  199. *
  200. * @param mixed $id the comment's id
  201. */
  202. protected function uncache($id) {
  203. $id = (string)$id;
  204. if (isset($this->commentsCache[$id])) {
  205. unset($this->commentsCache[$id]);
  206. }
  207. }
  208. /**
  209. * returns a comment instance
  210. *
  211. * @param string $id the ID of the comment
  212. * @return IComment
  213. * @throws NotFoundException
  214. * @throws \InvalidArgumentException
  215. * @since 9.0.0
  216. */
  217. public function get($id) {
  218. if ((int)$id === 0) {
  219. throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
  220. }
  221. if (isset($this->commentsCache[$id])) {
  222. return $this->commentsCache[$id];
  223. }
  224. $qb = $this->dbConn->getQueryBuilder();
  225. $resultStatement = $qb->select('*')
  226. ->from('comments')
  227. ->where($qb->expr()->eq('id', $qb->createParameter('id')))
  228. ->setParameter('id', $id, IQueryBuilder::PARAM_INT)
  229. ->execute();
  230. $data = $resultStatement->fetch();
  231. $resultStatement->closeCursor();
  232. if (!$data) {
  233. throw new NotFoundException();
  234. }
  235. $comment = $this->getCommentFromData($data);
  236. $this->cache($comment);
  237. return $comment;
  238. }
  239. /**
  240. * returns the comment specified by the id and all it's child comments.
  241. * At this point of time, we do only support one level depth.
  242. *
  243. * @param string $id
  244. * @param int $limit max number of entries to return, 0 returns all
  245. * @param int $offset the start entry
  246. * @return array
  247. * @since 9.0.0
  248. *
  249. * The return array looks like this
  250. * [
  251. * 'comment' => IComment, // root comment
  252. * 'replies' =>
  253. * [
  254. * 0 =>
  255. * [
  256. * 'comment' => IComment,
  257. * 'replies' => []
  258. * ]
  259. * 1 =>
  260. * [
  261. * 'comment' => IComment,
  262. * 'replies'=> []
  263. * ],
  264. *
  265. * ]
  266. * ]
  267. */
  268. public function getTree($id, $limit = 0, $offset = 0) {
  269. $tree = [];
  270. $tree['comment'] = $this->get($id);
  271. $tree['replies'] = [];
  272. $qb = $this->dbConn->getQueryBuilder();
  273. $query = $qb->select('*')
  274. ->from('comments')
  275. ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
  276. ->orderBy('creation_timestamp', 'DESC')
  277. ->setParameter('id', $id);
  278. if ($limit > 0) {
  279. $query->setMaxResults($limit);
  280. }
  281. if ($offset > 0) {
  282. $query->setFirstResult($offset);
  283. }
  284. $resultStatement = $query->execute();
  285. while ($data = $resultStatement->fetch()) {
  286. $comment = $this->getCommentFromData($data);
  287. $this->cache($comment);
  288. $tree['replies'][] = [
  289. 'comment' => $comment,
  290. 'replies' => []
  291. ];
  292. }
  293. $resultStatement->closeCursor();
  294. return $tree;
  295. }
  296. /**
  297. * returns comments for a specific object (e.g. a file).
  298. *
  299. * The sort order is always newest to oldest.
  300. *
  301. * @param string $objectType the object type, e.g. 'files'
  302. * @param string $objectId the id of the object
  303. * @param int $limit optional, number of maximum comments to be returned. if
  304. * not specified, all comments are returned.
  305. * @param int $offset optional, starting point
  306. * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
  307. * that may be returned
  308. * @return IComment[]
  309. * @since 9.0.0
  310. */
  311. public function getForObject(
  312. $objectType,
  313. $objectId,
  314. $limit = 0,
  315. $offset = 0,
  316. \DateTime $notOlderThan = null
  317. ) {
  318. $comments = [];
  319. $qb = $this->dbConn->getQueryBuilder();
  320. $query = $qb->select('*')
  321. ->from('comments')
  322. ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
  323. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
  324. ->orderBy('creation_timestamp', 'DESC')
  325. ->setParameter('type', $objectType)
  326. ->setParameter('id', $objectId);
  327. if ($limit > 0) {
  328. $query->setMaxResults($limit);
  329. }
  330. if ($offset > 0) {
  331. $query->setFirstResult($offset);
  332. }
  333. if (!is_null($notOlderThan)) {
  334. $query
  335. ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
  336. ->setParameter('notOlderThan', $notOlderThan, 'datetime');
  337. }
  338. $resultStatement = $query->execute();
  339. while ($data = $resultStatement->fetch()) {
  340. $comment = $this->getCommentFromData($data);
  341. $this->cache($comment);
  342. $comments[] = $comment;
  343. }
  344. $resultStatement->closeCursor();
  345. return $comments;
  346. }
  347. /**
  348. * @param string $objectType the object type, e.g. 'files'
  349. * @param string $objectId the id of the object
  350. * @param int $lastKnownCommentId the last known comment (will be used as offset)
  351. * @param string $sortDirection direction of the comments (`asc` or `desc`)
  352. * @param int $limit optional, number of maximum comments to be returned. if
  353. * set to 0, all comments are returned.
  354. * @return IComment[]
  355. * @return array
  356. */
  357. public function getForObjectSince(
  358. string $objectType,
  359. string $objectId,
  360. int $lastKnownCommentId,
  361. string $sortDirection = 'asc',
  362. int $limit = 30
  363. ): array {
  364. $comments = [];
  365. $query = $this->dbConn->getQueryBuilder();
  366. $query->select('*')
  367. ->from('comments')
  368. ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
  369. ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
  370. ->orderBy('creation_timestamp', $sortDirection === 'desc' ? 'DESC' : 'ASC')
  371. ->addOrderBy('id', $sortDirection === 'desc' ? 'DESC' : 'ASC');
  372. if ($limit > 0) {
  373. $query->setMaxResults($limit);
  374. }
  375. $lastKnownComment = $lastKnownCommentId > 0 ? $this->getLastKnownComment(
  376. $objectType,
  377. $objectId,
  378. $lastKnownCommentId
  379. ) : null;
  380. if ($lastKnownComment instanceof IComment) {
  381. $lastKnownCommentDateTime = $lastKnownComment->getCreationDateTime();
  382. if ($sortDirection === 'desc') {
  383. $query->andWhere(
  384. $query->expr()->orX(
  385. $query->expr()->lt(
  386. 'creation_timestamp',
  387. $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
  388. IQueryBuilder::PARAM_DATE
  389. ),
  390. $query->expr()->andX(
  391. $query->expr()->eq(
  392. 'creation_timestamp',
  393. $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
  394. IQueryBuilder::PARAM_DATE
  395. ),
  396. $query->expr()->lt('id', $query->createNamedParameter($lastKnownCommentId))
  397. )
  398. )
  399. );
  400. } else {
  401. $query->andWhere(
  402. $query->expr()->orX(
  403. $query->expr()->gt(
  404. 'creation_timestamp',
  405. $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
  406. IQueryBuilder::PARAM_DATE
  407. ),
  408. $query->expr()->andX(
  409. $query->expr()->eq(
  410. 'creation_timestamp',
  411. $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
  412. IQueryBuilder::PARAM_DATE
  413. ),
  414. $query->expr()->gt('id', $query->createNamedParameter($lastKnownCommentId))
  415. )
  416. )
  417. );
  418. }
  419. }
  420. $resultStatement = $query->execute();
  421. while ($data = $resultStatement->fetch()) {
  422. $comment = $this->getCommentFromData($data);
  423. $this->cache($comment);
  424. $comments[] = $comment;
  425. }
  426. $resultStatement->closeCursor();
  427. return $comments;
  428. }
  429. /**
  430. * @param string $objectType the object type, e.g. 'files'
  431. * @param string $objectId the id of the object
  432. * @param int $id the comment to look for
  433. * @return Comment|null
  434. */
  435. protected function getLastKnownComment(string $objectType,
  436. string $objectId,
  437. int $id) {
  438. $query = $this->dbConn->getQueryBuilder();
  439. $query->select('*')
  440. ->from('comments')
  441. ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
  442. ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
  443. ->andWhere($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
  444. $result = $query->execute();
  445. $row = $result->fetch();
  446. $result->closeCursor();
  447. if ($row) {
  448. $comment = $this->getCommentFromData($row);
  449. $this->cache($comment);
  450. return $comment;
  451. }
  452. return null;
  453. }
  454. /**
  455. * Search for comments with a given content
  456. *
  457. * @param string $search content to search for
  458. * @param string $objectType Limit the search by object type
  459. * @param string $objectId Limit the search by object id
  460. * @param string $verb Limit the verb of the comment
  461. * @param int $offset
  462. * @param int $limit
  463. * @return IComment[]
  464. */
  465. public function search(string $search, string $objectType, string $objectId, string $verb, int $offset, int $limit = 50): array {
  466. $query = $this->dbConn->getQueryBuilder();
  467. $query->select('*')
  468. ->from('comments')
  469. ->where($query->expr()->iLike('message', $query->createNamedParameter(
  470. '%' . $this->dbConn->escapeLikeParameter($search). '%'
  471. )))
  472. ->orderBy('creation_timestamp', 'DESC')
  473. ->addOrderBy('id', 'DESC')
  474. ->setMaxResults($limit);
  475. if ($objectType !== '') {
  476. $query->andWhere($query->expr()->eq('object_type', $query->createNamedParameter($objectType)));
  477. }
  478. if ($objectId !== '') {
  479. $query->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)));
  480. }
  481. if ($verb !== '') {
  482. $query->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)));
  483. }
  484. if ($offset !== 0) {
  485. $query->setFirstResult($offset);
  486. }
  487. $comments = [];
  488. $result = $query->execute();
  489. while ($data = $result->fetch()) {
  490. $comment = $this->getCommentFromData($data);
  491. $this->cache($comment);
  492. $comments[] = $comment;
  493. }
  494. $result->closeCursor();
  495. return $comments;
  496. }
  497. /**
  498. * @param $objectType string the object type, e.g. 'files'
  499. * @param $objectId string the id of the object
  500. * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
  501. * that may be returned
  502. * @param string $verb Limit the verb of the comment - Added in 14.0.0
  503. * @return Int
  504. * @since 9.0.0
  505. */
  506. public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null, $verb = '') {
  507. $qb = $this->dbConn->getQueryBuilder();
  508. $query = $qb->select($qb->func()->count('id'))
  509. ->from('comments')
  510. ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
  511. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
  512. ->setParameter('type', $objectType)
  513. ->setParameter('id', $objectId);
  514. if (!is_null($notOlderThan)) {
  515. $query
  516. ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
  517. ->setParameter('notOlderThan', $notOlderThan, 'datetime');
  518. }
  519. if ($verb !== '') {
  520. $query->andWhere($qb->expr()->eq('verb', $qb->createNamedParameter($verb)));
  521. }
  522. $resultStatement = $query->execute();
  523. $data = $resultStatement->fetch(\PDO::FETCH_NUM);
  524. $resultStatement->closeCursor();
  525. return (int)$data[0];
  526. }
  527. /**
  528. * Get the number of unread comments for all files in a folder
  529. *
  530. * @param int $folderId
  531. * @param IUser $user
  532. * @return array [$fileId => $unreadCount]
  533. */
  534. public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
  535. $qb = $this->dbConn->getQueryBuilder();
  536. $query = $qb->select('f.fileid')
  537. ->addSelect($qb->func()->count('c.id', 'num_ids'))
  538. ->from('filecache', 'f')
  539. ->leftJoin('f', 'comments', 'c', $qb->expr()->andX(
  540. $qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT)),
  541. $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files'))
  542. ))
  543. ->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX(
  544. $qb->expr()->eq('c.object_id', 'm.object_id'),
  545. $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files'))
  546. ))
  547. ->where(
  548. $qb->expr()->andX(
  549. $qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId)),
  550. $qb->expr()->orX(
  551. $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
  552. $qb->expr()->isNull('c.object_type')
  553. ),
  554. $qb->expr()->orX(
  555. $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')),
  556. $qb->expr()->isNull('m.object_type')
  557. ),
  558. $qb->expr()->orX(
  559. $qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID())),
  560. $qb->expr()->isNull('m.user_id')
  561. ),
  562. $qb->expr()->orX(
  563. $qb->expr()->gt('c.creation_timestamp', 'm.marker_datetime'),
  564. $qb->expr()->isNull('m.marker_datetime')
  565. )
  566. )
  567. )->groupBy('f.fileid');
  568. $resultStatement = $query->execute();
  569. $results = [];
  570. while ($row = $resultStatement->fetch()) {
  571. $results[$row['fileid']] = (int) $row['num_ids'];
  572. }
  573. $resultStatement->closeCursor();
  574. return $results;
  575. }
  576. /**
  577. * creates a new comment and returns it. At this point of time, it is not
  578. * saved in the used data storage. Use save() after setting other fields
  579. * of the comment (e.g. message or verb).
  580. *
  581. * @param string $actorType the actor type (e.g. 'users')
  582. * @param string $actorId a user id
  583. * @param string $objectType the object type the comment is attached to
  584. * @param string $objectId the object id the comment is attached to
  585. * @return IComment
  586. * @since 9.0.0
  587. */
  588. public function create($actorType, $actorId, $objectType, $objectId) {
  589. $comment = new Comment();
  590. $comment
  591. ->setActor($actorType, $actorId)
  592. ->setObject($objectType, $objectId);
  593. return $comment;
  594. }
  595. /**
  596. * permanently deletes the comment specified by the ID
  597. *
  598. * When the comment has child comments, their parent ID will be changed to
  599. * the parent ID of the item that is to be deleted.
  600. *
  601. * @param string $id
  602. * @return bool
  603. * @throws \InvalidArgumentException
  604. * @since 9.0.0
  605. */
  606. public function delete($id) {
  607. if (!is_string($id)) {
  608. throw new \InvalidArgumentException('Parameter must be string');
  609. }
  610. try {
  611. $comment = $this->get($id);
  612. } catch (\Exception $e) {
  613. // Ignore exceptions, we just don't fire a hook then
  614. $comment = null;
  615. }
  616. $qb = $this->dbConn->getQueryBuilder();
  617. $query = $qb->delete('comments')
  618. ->where($qb->expr()->eq('id', $qb->createParameter('id')))
  619. ->setParameter('id', $id);
  620. try {
  621. $affectedRows = $query->execute();
  622. $this->uncache($id);
  623. } catch (DriverException $e) {
  624. $this->logger->logException($e, ['app' => 'core_comments']);
  625. return false;
  626. }
  627. if ($affectedRows > 0 && $comment instanceof IComment) {
  628. $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
  629. }
  630. return ($affectedRows > 0);
  631. }
  632. /**
  633. * saves the comment permanently
  634. *
  635. * if the supplied comment has an empty ID, a new entry comment will be
  636. * saved and the instance updated with the new ID.
  637. *
  638. * Otherwise, an existing comment will be updated.
  639. *
  640. * Throws NotFoundException when a comment that is to be updated does not
  641. * exist anymore at this point of time.
  642. *
  643. * @param IComment $comment
  644. * @return bool
  645. * @throws NotFoundException
  646. * @since 9.0.0
  647. */
  648. public function save(IComment $comment) {
  649. if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
  650. $result = $this->insert($comment);
  651. } else {
  652. $result = $this->update($comment);
  653. }
  654. if ($result && !!$comment->getParentId()) {
  655. $this->updateChildrenInformation(
  656. $comment->getParentId(),
  657. $comment->getCreationDateTime()
  658. );
  659. $this->cache($comment);
  660. }
  661. return $result;
  662. }
  663. /**
  664. * inserts the provided comment in the database
  665. *
  666. * @param IComment $comment
  667. * @return bool
  668. */
  669. protected function insert(IComment $comment): bool {
  670. try {
  671. $result = $this->insertQuery($comment, true);
  672. } catch (InvalidFieldNameException $e) {
  673. // The reference id field was only added in Nextcloud 19.
  674. // In order to not cause too long waiting times on the update,
  675. // it was decided to only add it lazy, as it is also not a critical
  676. // feature, but only helps to have a better experience while commenting.
  677. // So in case the reference_id field is missing,
  678. // we simply save the comment without that field.
  679. $result = $this->insertQuery($comment, false);
  680. }
  681. return $result;
  682. }
  683. protected function insertQuery(IComment $comment, bool $tryWritingReferenceId): bool {
  684. $qb = $this->dbConn->getQueryBuilder();
  685. $values = [
  686. 'parent_id' => $qb->createNamedParameter($comment->getParentId()),
  687. 'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
  688. 'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
  689. 'actor_type' => $qb->createNamedParameter($comment->getActorType()),
  690. 'actor_id' => $qb->createNamedParameter($comment->getActorId()),
  691. 'message' => $qb->createNamedParameter($comment->getMessage()),
  692. 'verb' => $qb->createNamedParameter($comment->getVerb()),
  693. 'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
  694. 'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
  695. 'object_type' => $qb->createNamedParameter($comment->getObjectType()),
  696. 'object_id' => $qb->createNamedParameter($comment->getObjectId()),
  697. ];
  698. if ($tryWritingReferenceId) {
  699. $values['reference_id'] = $qb->createNamedParameter($comment->getReferenceId());
  700. }
  701. $affectedRows = $qb->insert('comments')
  702. ->values($values)
  703. ->execute();
  704. if ($affectedRows > 0) {
  705. $comment->setId((string)$qb->getLastInsertId());
  706. $this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
  707. }
  708. return $affectedRows > 0;
  709. }
  710. /**
  711. * updates a Comment data row
  712. *
  713. * @param IComment $comment
  714. * @return bool
  715. * @throws NotFoundException
  716. */
  717. protected function update(IComment $comment) {
  718. // for properly working preUpdate Events we need the old comments as is
  719. // in the DB and overcome caching. Also avoid that outdated information stays.
  720. $this->uncache($comment->getId());
  721. $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
  722. $this->uncache($comment->getId());
  723. try {
  724. $result = $this->updateQuery($comment, true);
  725. } catch (InvalidFieldNameException $e) {
  726. // See function insert() for explanation
  727. $result = $this->updateQuery($comment, false);
  728. }
  729. $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
  730. return $result;
  731. }
  732. protected function updateQuery(IComment $comment, bool $tryWritingReferenceId): bool {
  733. $qb = $this->dbConn->getQueryBuilder();
  734. $qb
  735. ->update('comments')
  736. ->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
  737. ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
  738. ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
  739. ->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
  740. ->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
  741. ->set('message', $qb->createNamedParameter($comment->getMessage()))
  742. ->set('verb', $qb->createNamedParameter($comment->getVerb()))
  743. ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
  744. ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
  745. ->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
  746. ->set('object_id', $qb->createNamedParameter($comment->getObjectId()));
  747. if ($tryWritingReferenceId) {
  748. $qb->set('reference_id', $qb->createNamedParameter($comment->getReferenceId()));
  749. }
  750. $affectedRows = $qb->where($qb->expr()->eq('id', $qb->createNamedParameter($comment->getId())))
  751. ->execute();
  752. if ($affectedRows === 0) {
  753. throw new NotFoundException('Comment to update does ceased to exist');
  754. }
  755. return $affectedRows > 0;
  756. }
  757. /**
  758. * removes references to specific actor (e.g. on user delete) of a comment.
  759. * The comment itself must not get lost/deleted.
  760. *
  761. * @param string $actorType the actor type (e.g. 'users')
  762. * @param string $actorId a user id
  763. * @return boolean
  764. * @since 9.0.0
  765. */
  766. public function deleteReferencesOfActor($actorType, $actorId) {
  767. $this->checkRoleParameters('Actor', $actorType, $actorId);
  768. $qb = $this->dbConn->getQueryBuilder();
  769. $affectedRows = $qb
  770. ->update('comments')
  771. ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
  772. ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
  773. ->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
  774. ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
  775. ->setParameter('type', $actorType)
  776. ->setParameter('id', $actorId)
  777. ->execute();
  778. $this->commentsCache = [];
  779. return is_int($affectedRows);
  780. }
  781. /**
  782. * deletes all comments made of a specific object (e.g. on file delete)
  783. *
  784. * @param string $objectType the object type (e.g. 'files')
  785. * @param string $objectId e.g. the file id
  786. * @return boolean
  787. * @since 9.0.0
  788. */
  789. public function deleteCommentsAtObject($objectType, $objectId) {
  790. $this->checkRoleParameters('Object', $objectType, $objectId);
  791. $qb = $this->dbConn->getQueryBuilder();
  792. $affectedRows = $qb
  793. ->delete('comments')
  794. ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
  795. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
  796. ->setParameter('type', $objectType)
  797. ->setParameter('id', $objectId)
  798. ->execute();
  799. $this->commentsCache = [];
  800. return is_int($affectedRows);
  801. }
  802. /**
  803. * deletes the read markers for the specified user
  804. *
  805. * @param \OCP\IUser $user
  806. * @return bool
  807. * @since 9.0.0
  808. */
  809. public function deleteReadMarksFromUser(IUser $user) {
  810. $qb = $this->dbConn->getQueryBuilder();
  811. $query = $qb->delete('comments_read_markers')
  812. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  813. ->setParameter('user_id', $user->getUID());
  814. try {
  815. $affectedRows = $query->execute();
  816. } catch (DriverException $e) {
  817. $this->logger->logException($e, ['app' => 'core_comments']);
  818. return false;
  819. }
  820. return ($affectedRows > 0);
  821. }
  822. /**
  823. * sets the read marker for a given file to the specified date for the
  824. * provided user
  825. *
  826. * @param string $objectType
  827. * @param string $objectId
  828. * @param \DateTime $dateTime
  829. * @param IUser $user
  830. * @since 9.0.0
  831. */
  832. public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
  833. $this->checkRoleParameters('Object', $objectType, $objectId);
  834. $qb = $this->dbConn->getQueryBuilder();
  835. $values = [
  836. 'user_id' => $qb->createNamedParameter($user->getUID()),
  837. 'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
  838. 'object_type' => $qb->createNamedParameter($objectType),
  839. 'object_id' => $qb->createNamedParameter($objectId),
  840. ];
  841. // Strategy: try to update, if this does not return affected rows, do an insert.
  842. $affectedRows = $qb
  843. ->update('comments_read_markers')
  844. ->set('user_id', $values['user_id'])
  845. ->set('marker_datetime', $values['marker_datetime'])
  846. ->set('object_type', $values['object_type'])
  847. ->set('object_id', $values['object_id'])
  848. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  849. ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  850. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  851. ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
  852. ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
  853. ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
  854. ->execute();
  855. if ($affectedRows > 0) {
  856. return;
  857. }
  858. $qb->insert('comments_read_markers')
  859. ->values($values)
  860. ->execute();
  861. }
  862. /**
  863. * returns the read marker for a given file to the specified date for the
  864. * provided user. It returns null, when the marker is not present, i.e.
  865. * no comments were marked as read.
  866. *
  867. * @param string $objectType
  868. * @param string $objectId
  869. * @param IUser $user
  870. * @return \DateTime|null
  871. * @since 9.0.0
  872. */
  873. public function getReadMark($objectType, $objectId, IUser $user) {
  874. $qb = $this->dbConn->getQueryBuilder();
  875. $resultStatement = $qb->select('marker_datetime')
  876. ->from('comments_read_markers')
  877. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  878. ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  879. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  880. ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
  881. ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
  882. ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
  883. ->execute();
  884. $data = $resultStatement->fetch();
  885. $resultStatement->closeCursor();
  886. if (!$data || is_null($data['marker_datetime'])) {
  887. return null;
  888. }
  889. return new \DateTime($data['marker_datetime']);
  890. }
  891. /**
  892. * deletes the read markers on the specified object
  893. *
  894. * @param string $objectType
  895. * @param string $objectId
  896. * @return bool
  897. * @since 9.0.0
  898. */
  899. public function deleteReadMarksOnObject($objectType, $objectId) {
  900. $this->checkRoleParameters('Object', $objectType, $objectId);
  901. $qb = $this->dbConn->getQueryBuilder();
  902. $query = $qb->delete('comments_read_markers')
  903. ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  904. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  905. ->setParameter('object_type', $objectType)
  906. ->setParameter('object_id', $objectId);
  907. try {
  908. $affectedRows = $query->execute();
  909. } catch (DriverException $e) {
  910. $this->logger->logException($e, ['app' => 'core_comments']);
  911. return false;
  912. }
  913. return ($affectedRows > 0);
  914. }
  915. /**
  916. * registers an Entity to the manager, so event notifications can be send
  917. * to consumers of the comments infrastructure
  918. *
  919. * @param \Closure $closure
  920. */
  921. public function registerEventHandler(\Closure $closure) {
  922. $this->eventHandlerClosures[] = $closure;
  923. $this->eventHandlers = [];
  924. }
  925. /**
  926. * registers a method that resolves an ID to a display name for a given type
  927. *
  928. * @param string $type
  929. * @param \Closure $closure
  930. * @throws \OutOfBoundsException
  931. * @since 11.0.0
  932. *
  933. * Only one resolver shall be registered per type. Otherwise a
  934. * \OutOfBoundsException has to thrown.
  935. */
  936. public function registerDisplayNameResolver($type, \Closure $closure) {
  937. if (!is_string($type)) {
  938. throw new \InvalidArgumentException('String expected.');
  939. }
  940. if (isset($this->displayNameResolvers[$type])) {
  941. throw new \OutOfBoundsException('Displayname resolver for this type already registered');
  942. }
  943. $this->displayNameResolvers[$type] = $closure;
  944. }
  945. /**
  946. * resolves a given ID of a given Type to a display name.
  947. *
  948. * @param string $type
  949. * @param string $id
  950. * @return string
  951. * @throws \OutOfBoundsException
  952. * @since 11.0.0
  953. *
  954. * If a provided type was not registered, an \OutOfBoundsException shall
  955. * be thrown. It is upon the resolver discretion what to return of the
  956. * provided ID is unknown. It must be ensured that a string is returned.
  957. */
  958. public function resolveDisplayName($type, $id) {
  959. if (!is_string($type)) {
  960. throw new \InvalidArgumentException('String expected.');
  961. }
  962. if (!isset($this->displayNameResolvers[$type])) {
  963. throw new \OutOfBoundsException('No Displayname resolver for this type registered');
  964. }
  965. return (string)$this->displayNameResolvers[$type]($id);
  966. }
  967. /**
  968. * returns valid, registered entities
  969. *
  970. * @return \OCP\Comments\ICommentsEventHandler[]
  971. */
  972. private function getEventHandlers() {
  973. if (!empty($this->eventHandlers)) {
  974. return $this->eventHandlers;
  975. }
  976. $this->eventHandlers = [];
  977. foreach ($this->eventHandlerClosures as $name => $closure) {
  978. $entity = $closure();
  979. if (!($entity instanceof ICommentsEventHandler)) {
  980. throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
  981. }
  982. $this->eventHandlers[$name] = $entity;
  983. }
  984. return $this->eventHandlers;
  985. }
  986. /**
  987. * sends notifications to the registered entities
  988. *
  989. * @param $eventType
  990. * @param IComment $comment
  991. */
  992. private function sendEvent($eventType, IComment $comment) {
  993. $entities = $this->getEventHandlers();
  994. $event = new CommentsEvent($eventType, $comment);
  995. foreach ($entities as $entity) {
  996. $entity->handle($event);
  997. }
  998. }
  999. }