Manager.php 32 KB

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