Manager.php 40 KB

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