1
0

Manager.php 32 KB

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