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.

Manager.php 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  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. * @suppress SqlInjectionChecker
  535. */
  536. public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
  537. $qb = $this->dbConn->getQueryBuilder();
  538. $query = $qb->select('f.fileid')
  539. ->addSelect($qb->func()->count('c.id', 'num_ids'))
  540. ->from('filecache', 'f')
  541. ->leftJoin('f', 'comments', 'c', $qb->expr()->andX(
  542. $qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT)),
  543. $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files'))
  544. ))
  545. ->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX(
  546. $qb->expr()->eq('c.object_id', 'm.object_id'),
  547. $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files'))
  548. ))
  549. ->where(
  550. $qb->expr()->andX(
  551. $qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId)),
  552. $qb->expr()->orX(
  553. $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
  554. $qb->expr()->isNull('c.object_type')
  555. ),
  556. $qb->expr()->orX(
  557. $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')),
  558. $qb->expr()->isNull('m.object_type')
  559. ),
  560. $qb->expr()->orX(
  561. $qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID())),
  562. $qb->expr()->isNull('m.user_id')
  563. ),
  564. $qb->expr()->orX(
  565. $qb->expr()->gt('c.creation_timestamp', 'm.marker_datetime'),
  566. $qb->expr()->isNull('m.marker_datetime')
  567. )
  568. )
  569. )->groupBy('f.fileid');
  570. $resultStatement = $query->execute();
  571. $results = [];
  572. while ($row = $resultStatement->fetch()) {
  573. $results[$row['fileid']] = (int) $row['num_ids'];
  574. }
  575. $resultStatement->closeCursor();
  576. return $results;
  577. }
  578. /**
  579. * creates a new comment and returns it. At this point of time, it is not
  580. * saved in the used data storage. Use save() after setting other fields
  581. * of the comment (e.g. message or verb).
  582. *
  583. * @param string $actorType the actor type (e.g. 'users')
  584. * @param string $actorId a user id
  585. * @param string $objectType the object type the comment is attached to
  586. * @param string $objectId the object id the comment is attached to
  587. * @return IComment
  588. * @since 9.0.0
  589. */
  590. public function create($actorType, $actorId, $objectType, $objectId) {
  591. $comment = new Comment();
  592. $comment
  593. ->setActor($actorType, $actorId)
  594. ->setObject($objectType, $objectId);
  595. return $comment;
  596. }
  597. /**
  598. * permanently deletes the comment specified by the ID
  599. *
  600. * When the comment has child comments, their parent ID will be changed to
  601. * the parent ID of the item that is to be deleted.
  602. *
  603. * @param string $id
  604. * @return bool
  605. * @throws \InvalidArgumentException
  606. * @since 9.0.0
  607. */
  608. public function delete($id) {
  609. if (!is_string($id)) {
  610. throw new \InvalidArgumentException('Parameter must be string');
  611. }
  612. try {
  613. $comment = $this->get($id);
  614. } catch (\Exception $e) {
  615. // Ignore exceptions, we just don't fire a hook then
  616. $comment = null;
  617. }
  618. $qb = $this->dbConn->getQueryBuilder();
  619. $query = $qb->delete('comments')
  620. ->where($qb->expr()->eq('id', $qb->createParameter('id')))
  621. ->setParameter('id', $id);
  622. try {
  623. $affectedRows = $query->execute();
  624. $this->uncache($id);
  625. } catch (DriverException $e) {
  626. $this->logger->logException($e, ['app' => 'core_comments']);
  627. return false;
  628. }
  629. if ($affectedRows > 0 && $comment instanceof IComment) {
  630. $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
  631. }
  632. return ($affectedRows > 0);
  633. }
  634. /**
  635. * saves the comment permanently
  636. *
  637. * if the supplied comment has an empty ID, a new entry comment will be
  638. * saved and the instance updated with the new ID.
  639. *
  640. * Otherwise, an existing comment will be updated.
  641. *
  642. * Throws NotFoundException when a comment that is to be updated does not
  643. * exist anymore at this point of time.
  644. *
  645. * @param IComment $comment
  646. * @return bool
  647. * @throws NotFoundException
  648. * @since 9.0.0
  649. */
  650. public function save(IComment $comment) {
  651. if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
  652. $result = $this->insert($comment);
  653. } else {
  654. $result = $this->update($comment);
  655. }
  656. if ($result && !!$comment->getParentId()) {
  657. $this->updateChildrenInformation(
  658. $comment->getParentId(),
  659. $comment->getCreationDateTime()
  660. );
  661. $this->cache($comment);
  662. }
  663. return $result;
  664. }
  665. /**
  666. * inserts the provided comment in the database
  667. *
  668. * @param IComment $comment
  669. * @return bool
  670. */
  671. protected function insert(IComment $comment): bool {
  672. try {
  673. $result = $this->insertQuery($comment, true);
  674. } catch (InvalidFieldNameException $e) {
  675. // The reference id field was only added in Nextcloud 19.
  676. // In order to not cause too long waiting times on the update,
  677. // it was decided to only add it lazy, as it is also not a critical
  678. // feature, but only helps to have a better experience while commenting.
  679. // So in case the reference_id field is missing,
  680. // we simply save the comment without that field.
  681. $result = $this->insertQuery($comment, false);
  682. }
  683. return $result;
  684. }
  685. protected function insertQuery(IComment $comment, bool $tryWritingReferenceId): bool {
  686. $qb = $this->dbConn->getQueryBuilder();
  687. $values = [
  688. 'parent_id' => $qb->createNamedParameter($comment->getParentId()),
  689. 'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
  690. 'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
  691. 'actor_type' => $qb->createNamedParameter($comment->getActorType()),
  692. 'actor_id' => $qb->createNamedParameter($comment->getActorId()),
  693. 'message' => $qb->createNamedParameter($comment->getMessage()),
  694. 'verb' => $qb->createNamedParameter($comment->getVerb()),
  695. 'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
  696. 'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
  697. 'object_type' => $qb->createNamedParameter($comment->getObjectType()),
  698. 'object_id' => $qb->createNamedParameter($comment->getObjectId()),
  699. ];
  700. if ($tryWritingReferenceId) {
  701. $values['reference_id'] = $qb->createNamedParameter($comment->getReferenceId());
  702. }
  703. $affectedRows = $qb->insert('comments')
  704. ->values($values)
  705. ->execute();
  706. if ($affectedRows > 0) {
  707. $comment->setId((string)$qb->getLastInsertId());
  708. $this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
  709. }
  710. return $affectedRows > 0;
  711. }
  712. /**
  713. * updates a Comment data row
  714. *
  715. * @param IComment $comment
  716. * @return bool
  717. * @throws NotFoundException
  718. */
  719. protected function update(IComment $comment) {
  720. // for properly working preUpdate Events we need the old comments as is
  721. // in the DB and overcome caching. Also avoid that outdated information stays.
  722. $this->uncache($comment->getId());
  723. $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
  724. $this->uncache($comment->getId());
  725. try {
  726. $result = $this->updateQuery($comment, true);
  727. } catch (InvalidFieldNameException $e) {
  728. // See function insert() for explanation
  729. $result = $this->updateQuery($comment, false);
  730. }
  731. $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
  732. return $result;
  733. }
  734. protected function updateQuery(IComment $comment, bool $tryWritingReferenceId): bool {
  735. $qb = $this->dbConn->getQueryBuilder();
  736. $qb
  737. ->update('comments')
  738. ->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
  739. ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
  740. ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
  741. ->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
  742. ->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
  743. ->set('message', $qb->createNamedParameter($comment->getMessage()))
  744. ->set('verb', $qb->createNamedParameter($comment->getVerb()))
  745. ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
  746. ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
  747. ->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
  748. ->set('object_id', $qb->createNamedParameter($comment->getObjectId()));
  749. if ($tryWritingReferenceId) {
  750. $qb->set('reference_id', $qb->createNamedParameter($comment->getReferenceId()));
  751. }
  752. $affectedRows = $qb->where($qb->expr()->eq('id', $qb->createNamedParameter($comment->getId())))
  753. ->execute();
  754. if ($affectedRows === 0) {
  755. throw new NotFoundException('Comment to update does ceased to exist');
  756. }
  757. return $affectedRows > 0;
  758. }
  759. /**
  760. * removes references to specific actor (e.g. on user delete) of a comment.
  761. * The comment itself must not get lost/deleted.
  762. *
  763. * @param string $actorType the actor type (e.g. 'users')
  764. * @param string $actorId a user id
  765. * @return boolean
  766. * @since 9.0.0
  767. */
  768. public function deleteReferencesOfActor($actorType, $actorId) {
  769. $this->checkRoleParameters('Actor', $actorType, $actorId);
  770. $qb = $this->dbConn->getQueryBuilder();
  771. $affectedRows = $qb
  772. ->update('comments')
  773. ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
  774. ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
  775. ->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
  776. ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
  777. ->setParameter('type', $actorType)
  778. ->setParameter('id', $actorId)
  779. ->execute();
  780. $this->commentsCache = [];
  781. return is_int($affectedRows);
  782. }
  783. /**
  784. * deletes all comments made of a specific object (e.g. on file delete)
  785. *
  786. * @param string $objectType the object type (e.g. 'files')
  787. * @param string $objectId e.g. the file id
  788. * @return boolean
  789. * @since 9.0.0
  790. */
  791. public function deleteCommentsAtObject($objectType, $objectId) {
  792. $this->checkRoleParameters('Object', $objectType, $objectId);
  793. $qb = $this->dbConn->getQueryBuilder();
  794. $affectedRows = $qb
  795. ->delete('comments')
  796. ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
  797. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
  798. ->setParameter('type', $objectType)
  799. ->setParameter('id', $objectId)
  800. ->execute();
  801. $this->commentsCache = [];
  802. return is_int($affectedRows);
  803. }
  804. /**
  805. * deletes the read markers for the specified user
  806. *
  807. * @param \OCP\IUser $user
  808. * @return bool
  809. * @since 9.0.0
  810. */
  811. public function deleteReadMarksFromUser(IUser $user) {
  812. $qb = $this->dbConn->getQueryBuilder();
  813. $query = $qb->delete('comments_read_markers')
  814. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  815. ->setParameter('user_id', $user->getUID());
  816. try {
  817. $affectedRows = $query->execute();
  818. } catch (DriverException $e) {
  819. $this->logger->logException($e, ['app' => 'core_comments']);
  820. return false;
  821. }
  822. return ($affectedRows > 0);
  823. }
  824. /**
  825. * sets the read marker for a given file to the specified date for the
  826. * provided user
  827. *
  828. * @param string $objectType
  829. * @param string $objectId
  830. * @param \DateTime $dateTime
  831. * @param IUser $user
  832. * @since 9.0.0
  833. * @suppress SqlInjectionChecker
  834. */
  835. public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
  836. $this->checkRoleParameters('Object', $objectType, $objectId);
  837. $qb = $this->dbConn->getQueryBuilder();
  838. $values = [
  839. 'user_id' => $qb->createNamedParameter($user->getUID()),
  840. 'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
  841. 'object_type' => $qb->createNamedParameter($objectType),
  842. 'object_id' => $qb->createNamedParameter($objectId),
  843. ];
  844. // Strategy: try to update, if this does not return affected rows, do an insert.
  845. $affectedRows = $qb
  846. ->update('comments_read_markers')
  847. ->set('user_id', $values['user_id'])
  848. ->set('marker_datetime', $values['marker_datetime'])
  849. ->set('object_type', $values['object_type'])
  850. ->set('object_id', $values['object_id'])
  851. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  852. ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  853. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  854. ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
  855. ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
  856. ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
  857. ->execute();
  858. if ($affectedRows > 0) {
  859. return;
  860. }
  861. $qb->insert('comments_read_markers')
  862. ->values($values)
  863. ->execute();
  864. }
  865. /**
  866. * returns the read marker for a given file to the specified date for the
  867. * provided user. It returns null, when the marker is not present, i.e.
  868. * no comments were marked as read.
  869. *
  870. * @param string $objectType
  871. * @param string $objectId
  872. * @param IUser $user
  873. * @return \DateTime|null
  874. * @since 9.0.0
  875. */
  876. public function getReadMark($objectType, $objectId, IUser $user) {
  877. $qb = $this->dbConn->getQueryBuilder();
  878. $resultStatement = $qb->select('marker_datetime')
  879. ->from('comments_read_markers')
  880. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  881. ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  882. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  883. ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
  884. ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
  885. ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
  886. ->execute();
  887. $data = $resultStatement->fetch();
  888. $resultStatement->closeCursor();
  889. if (!$data || is_null($data['marker_datetime'])) {
  890. return null;
  891. }
  892. return new \DateTime($data['marker_datetime']);
  893. }
  894. /**
  895. * deletes the read markers on the specified object
  896. *
  897. * @param string $objectType
  898. * @param string $objectId
  899. * @return bool
  900. * @since 9.0.0
  901. */
  902. public function deleteReadMarksOnObject($objectType, $objectId) {
  903. $this->checkRoleParameters('Object', $objectType, $objectId);
  904. $qb = $this->dbConn->getQueryBuilder();
  905. $query = $qb->delete('comments_read_markers')
  906. ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  907. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  908. ->setParameter('object_type', $objectType)
  909. ->setParameter('object_id', $objectId);
  910. try {
  911. $affectedRows = $query->execute();
  912. } catch (DriverException $e) {
  913. $this->logger->logException($e, ['app' => 'core_comments']);
  914. return false;
  915. }
  916. return ($affectedRows > 0);
  917. }
  918. /**
  919. * registers an Entity to the manager, so event notifications can be send
  920. * to consumers of the comments infrastructure
  921. *
  922. * @param \Closure $closure
  923. */
  924. public function registerEventHandler(\Closure $closure) {
  925. $this->eventHandlerClosures[] = $closure;
  926. $this->eventHandlers = [];
  927. }
  928. /**
  929. * registers a method that resolves an ID to a display name for a given type
  930. *
  931. * @param string $type
  932. * @param \Closure $closure
  933. * @throws \OutOfBoundsException
  934. * @since 11.0.0
  935. *
  936. * Only one resolver shall be registered per type. Otherwise a
  937. * \OutOfBoundsException has to thrown.
  938. */
  939. public function registerDisplayNameResolver($type, \Closure $closure) {
  940. if (!is_string($type)) {
  941. throw new \InvalidArgumentException('String expected.');
  942. }
  943. if (isset($this->displayNameResolvers[$type])) {
  944. throw new \OutOfBoundsException('Displayname resolver for this type already registered');
  945. }
  946. $this->displayNameResolvers[$type] = $closure;
  947. }
  948. /**
  949. * resolves a given ID of a given Type to a display name.
  950. *
  951. * @param string $type
  952. * @param string $id
  953. * @return string
  954. * @throws \OutOfBoundsException
  955. * @since 11.0.0
  956. *
  957. * If a provided type was not registered, an \OutOfBoundsException shall
  958. * be thrown. It is upon the resolver discretion what to return of the
  959. * provided ID is unknown. It must be ensured that a string is returned.
  960. */
  961. public function resolveDisplayName($type, $id) {
  962. if (!is_string($type)) {
  963. throw new \InvalidArgumentException('String expected.');
  964. }
  965. if (!isset($this->displayNameResolvers[$type])) {
  966. throw new \OutOfBoundsException('No Displayname resolver for this type registered');
  967. }
  968. return (string)$this->displayNameResolvers[$type]($id);
  969. }
  970. /**
  971. * returns valid, registered entities
  972. *
  973. * @return \OCP\Comments\ICommentsEventHandler[]
  974. */
  975. private function getEventHandlers() {
  976. if (!empty($this->eventHandlers)) {
  977. return $this->eventHandlers;
  978. }
  979. $this->eventHandlers = [];
  980. foreach ($this->eventHandlerClosures as $name => $closure) {
  981. $entity = $closure();
  982. if (!($entity instanceof ICommentsEventHandler)) {
  983. throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
  984. }
  985. $this->eventHandlers[$name] = $entity;
  986. }
  987. return $this->eventHandlers;
  988. }
  989. /**
  990. * sends notifications to the registered entities
  991. *
  992. * @param $eventType
  993. * @param IComment $comment
  994. */
  995. private function sendEvent($eventType, IComment $comment) {
  996. $entities = $this->getEventHandlers();
  997. $event = new CommentsEvent($eventType, $comment);
  998. foreach ($entities as $entity) {
  999. $entity->handle($event);
  1000. }
  1001. }
  1002. }