You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Manager.php 41KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338
  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. if ($verb !== '') {
  610. return $this->getNumberOfCommentsWithVerbsForObjectSinceComment($objectType, $objectId, $lastRead, [$verb]);
  611. }
  612. $query = $this->dbConn->getQueryBuilder();
  613. $query->select($query->func()->count('id', 'num_messages'))
  614. ->from('comments')
  615. ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
  616. ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
  617. ->andWhere($query->expr()->gt('id', $query->createNamedParameter($lastRead)));
  618. $result = $query->executeQuery();
  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 int $lastRead
  627. * @param string[] $verbs
  628. * @return int
  629. * @since 24.0.0
  630. */
  631. public function getNumberOfCommentsWithVerbsForObjectSinceComment(string $objectType, string $objectId, int $lastRead, array $verbs): int {
  632. $query = $this->dbConn->getQueryBuilder();
  633. $query->select($query->func()->count('id', 'num_messages'))
  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()->gt('id', $query->createNamedParameter($lastRead)))
  638. ->andWhere($query->expr()->in('verb', $query->createNamedParameter($verbs, IQueryBuilder::PARAM_STR_ARRAY)));
  639. $result = $query->executeQuery();
  640. $data = $result->fetch();
  641. $result->closeCursor();
  642. return (int) ($data['num_messages'] ?? 0);
  643. }
  644. /**
  645. * @param string $objectType
  646. * @param string $objectId
  647. * @param \DateTime $beforeDate
  648. * @param string $verb
  649. * @return int
  650. * @since 21.0.0
  651. */
  652. public function getLastCommentBeforeDate(string $objectType, string $objectId, \DateTime $beforeDate, string $verb = ''): int {
  653. $query = $this->dbConn->getQueryBuilder();
  654. $query->select('id')
  655. ->from('comments')
  656. ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
  657. ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
  658. ->andWhere($query->expr()->lt('creation_timestamp', $query->createNamedParameter($beforeDate, IQueryBuilder::PARAM_DATE)))
  659. ->orderBy('creation_timestamp', 'desc');
  660. if ($verb !== '') {
  661. $query->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)));
  662. }
  663. $result = $query->execute();
  664. $data = $result->fetch();
  665. $result->closeCursor();
  666. return (int) ($data['id'] ?? 0);
  667. }
  668. /**
  669. * @param string $objectType
  670. * @param string $objectId
  671. * @param string $verb
  672. * @param string $actorType
  673. * @param string[] $actors
  674. * @return \DateTime[] Map of "string actor" => "\DateTime most recent comment date"
  675. * @psalm-return array<string, \DateTime>
  676. * @since 21.0.0
  677. */
  678. public function getLastCommentDateByActor(
  679. string $objectType,
  680. string $objectId,
  681. string $verb,
  682. string $actorType,
  683. array $actors
  684. ): array {
  685. $lastComments = [];
  686. $query = $this->dbConn->getQueryBuilder();
  687. $query->select('actor_id')
  688. ->selectAlias($query->createFunction('MAX(' . $query->getColumnName('creation_timestamp') . ')'), 'last_comment')
  689. ->from('comments')
  690. ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
  691. ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
  692. ->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)))
  693. ->andWhere($query->expr()->eq('actor_type', $query->createNamedParameter($actorType)))
  694. ->andWhere($query->expr()->in('actor_id', $query->createNamedParameter($actors, IQueryBuilder::PARAM_STR_ARRAY)))
  695. ->groupBy('actor_id');
  696. $result = $query->execute();
  697. while ($row = $result->fetch()) {
  698. $lastComments[$row['actor_id']] = $this->timeFactory->getDateTime($row['last_comment']);
  699. }
  700. $result->closeCursor();
  701. return $lastComments;
  702. }
  703. /**
  704. * Get the number of unread comments for all files in a folder
  705. *
  706. * @param int $folderId
  707. * @param IUser $user
  708. * @return array [$fileId => $unreadCount]
  709. */
  710. public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
  711. $qb = $this->dbConn->getQueryBuilder();
  712. $query = $qb->select('f.fileid')
  713. ->addSelect($qb->func()->count('c.id', 'num_ids'))
  714. ->from('filecache', 'f')
  715. ->leftJoin('f', 'comments', 'c', $qb->expr()->andX(
  716. $qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT)),
  717. $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files'))
  718. ))
  719. ->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX(
  720. $qb->expr()->eq('c.object_id', 'm.object_id'),
  721. $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files'))
  722. ))
  723. ->where(
  724. $qb->expr()->andX(
  725. $qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId)),
  726. $qb->expr()->orX(
  727. $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
  728. $qb->expr()->isNull('c.object_type')
  729. ),
  730. $qb->expr()->orX(
  731. $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')),
  732. $qb->expr()->isNull('m.object_type')
  733. ),
  734. $qb->expr()->orX(
  735. $qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID())),
  736. $qb->expr()->isNull('m.user_id')
  737. ),
  738. $qb->expr()->orX(
  739. $qb->expr()->gt('c.creation_timestamp', 'm.marker_datetime'),
  740. $qb->expr()->isNull('m.marker_datetime')
  741. )
  742. )
  743. )->groupBy('f.fileid');
  744. $resultStatement = $query->execute();
  745. $results = [];
  746. while ($row = $resultStatement->fetch()) {
  747. $results[$row['fileid']] = (int) $row['num_ids'];
  748. }
  749. $resultStatement->closeCursor();
  750. return $results;
  751. }
  752. /**
  753. * creates a new comment and returns it. At this point of time, it is not
  754. * saved in the used data storage. Use save() after setting other fields
  755. * of the comment (e.g. message or verb).
  756. *
  757. * @param string $actorType the actor type (e.g. 'users')
  758. * @param string $actorId a user id
  759. * @param string $objectType the object type the comment is attached to
  760. * @param string $objectId the object id the comment is attached to
  761. * @return IComment
  762. * @since 9.0.0
  763. */
  764. public function create($actorType, $actorId, $objectType, $objectId) {
  765. $comment = new Comment();
  766. $comment
  767. ->setActor($actorType, $actorId)
  768. ->setObject($objectType, $objectId);
  769. return $comment;
  770. }
  771. /**
  772. * permanently deletes the comment specified by the ID
  773. *
  774. * When the comment has child comments, their parent ID will be changed to
  775. * the parent ID of the item that is to be deleted.
  776. *
  777. * @param string $id
  778. * @return bool
  779. * @throws \InvalidArgumentException
  780. * @since 9.0.0
  781. */
  782. public function delete($id) {
  783. if (!is_string($id)) {
  784. throw new \InvalidArgumentException('Parameter must be string');
  785. }
  786. try {
  787. $comment = $this->get($id);
  788. } catch (\Exception $e) {
  789. // Ignore exceptions, we just don't fire a hook then
  790. $comment = null;
  791. }
  792. $qb = $this->dbConn->getQueryBuilder();
  793. $query = $qb->delete('comments')
  794. ->where($qb->expr()->eq('id', $qb->createParameter('id')))
  795. ->setParameter('id', $id);
  796. try {
  797. $affectedRows = $query->execute();
  798. $this->uncache($id);
  799. } catch (DriverException $e) {
  800. $this->logger->error($e->getMessage(), [
  801. 'exception' => $e,
  802. 'app' => 'core_comments',
  803. ]);
  804. return false;
  805. }
  806. if ($affectedRows > 0 && $comment instanceof IComment) {
  807. $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
  808. }
  809. return ($affectedRows > 0);
  810. }
  811. /**
  812. * saves the comment permanently
  813. *
  814. * if the supplied comment has an empty ID, a new entry comment will be
  815. * saved and the instance updated with the new ID.
  816. *
  817. * Otherwise, an existing comment will be updated.
  818. *
  819. * Throws NotFoundException when a comment that is to be updated does not
  820. * exist anymore at this point of time.
  821. *
  822. * @param IComment $comment
  823. * @return bool
  824. * @throws NotFoundException
  825. * @since 9.0.0
  826. */
  827. public function save(IComment $comment) {
  828. if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
  829. $result = $this->insert($comment);
  830. } else {
  831. $result = $this->update($comment);
  832. }
  833. if ($result && !!$comment->getParentId()) {
  834. $this->updateChildrenInformation(
  835. $comment->getParentId(),
  836. $comment->getCreationDateTime()
  837. );
  838. $this->cache($comment);
  839. }
  840. return $result;
  841. }
  842. /**
  843. * inserts the provided comment in the database
  844. *
  845. * @param IComment $comment
  846. * @return bool
  847. */
  848. protected function insert(IComment $comment): bool {
  849. try {
  850. $result = $this->insertQuery($comment, true);
  851. } catch (InvalidFieldNameException $e) {
  852. // The reference id field was only added in Nextcloud 19.
  853. // In order to not cause too long waiting times on the update,
  854. // it was decided to only add it lazy, as it is also not a critical
  855. // feature, but only helps to have a better experience while commenting.
  856. // So in case the reference_id field is missing,
  857. // we simply save the comment without that field.
  858. $result = $this->insertQuery($comment, false);
  859. }
  860. return $result;
  861. }
  862. protected function insertQuery(IComment $comment, bool $tryWritingReferenceId): bool {
  863. $qb = $this->dbConn->getQueryBuilder();
  864. $values = [
  865. 'parent_id' => $qb->createNamedParameter($comment->getParentId()),
  866. 'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
  867. 'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
  868. 'actor_type' => $qb->createNamedParameter($comment->getActorType()),
  869. 'actor_id' => $qb->createNamedParameter($comment->getActorId()),
  870. 'message' => $qb->createNamedParameter($comment->getMessage()),
  871. 'verb' => $qb->createNamedParameter($comment->getVerb()),
  872. 'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
  873. 'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
  874. 'object_type' => $qb->createNamedParameter($comment->getObjectType()),
  875. 'object_id' => $qb->createNamedParameter($comment->getObjectId()),
  876. ];
  877. if ($tryWritingReferenceId) {
  878. $values['reference_id'] = $qb->createNamedParameter($comment->getReferenceId());
  879. }
  880. $affectedRows = $qb->insert('comments')
  881. ->values($values)
  882. ->execute();
  883. if ($affectedRows > 0) {
  884. $comment->setId((string)$qb->getLastInsertId());
  885. $this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
  886. }
  887. return $affectedRows > 0;
  888. }
  889. /**
  890. * updates a Comment data row
  891. *
  892. * @param IComment $comment
  893. * @return bool
  894. * @throws NotFoundException
  895. */
  896. protected function update(IComment $comment) {
  897. // for properly working preUpdate Events we need the old comments as is
  898. // in the DB and overcome caching. Also avoid that outdated information stays.
  899. $this->uncache($comment->getId());
  900. $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
  901. $this->uncache($comment->getId());
  902. try {
  903. $result = $this->updateQuery($comment, true);
  904. } catch (InvalidFieldNameException $e) {
  905. // See function insert() for explanation
  906. $result = $this->updateQuery($comment, false);
  907. }
  908. $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
  909. return $result;
  910. }
  911. protected function updateQuery(IComment $comment, bool $tryWritingReferenceId): bool {
  912. $qb = $this->dbConn->getQueryBuilder();
  913. $qb
  914. ->update('comments')
  915. ->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
  916. ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
  917. ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
  918. ->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
  919. ->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
  920. ->set('message', $qb->createNamedParameter($comment->getMessage()))
  921. ->set('verb', $qb->createNamedParameter($comment->getVerb()))
  922. ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
  923. ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
  924. ->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
  925. ->set('object_id', $qb->createNamedParameter($comment->getObjectId()));
  926. if ($tryWritingReferenceId) {
  927. $qb->set('reference_id', $qb->createNamedParameter($comment->getReferenceId()));
  928. }
  929. $affectedRows = $qb->where($qb->expr()->eq('id', $qb->createNamedParameter($comment->getId())))
  930. ->execute();
  931. if ($affectedRows === 0) {
  932. throw new NotFoundException('Comment to update does ceased to exist');
  933. }
  934. return $affectedRows > 0;
  935. }
  936. /**
  937. * removes references to specific actor (e.g. on user delete) of a comment.
  938. * The comment itself must not get lost/deleted.
  939. *
  940. * @param string $actorType the actor type (e.g. 'users')
  941. * @param string $actorId a user id
  942. * @return boolean
  943. * @since 9.0.0
  944. */
  945. public function deleteReferencesOfActor($actorType, $actorId) {
  946. $this->checkRoleParameters('Actor', $actorType, $actorId);
  947. $qb = $this->dbConn->getQueryBuilder();
  948. $affectedRows = $qb
  949. ->update('comments')
  950. ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
  951. ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
  952. ->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
  953. ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
  954. ->setParameter('type', $actorType)
  955. ->setParameter('id', $actorId)
  956. ->execute();
  957. $this->commentsCache = [];
  958. return is_int($affectedRows);
  959. }
  960. /**
  961. * deletes all comments made of a specific object (e.g. on file delete)
  962. *
  963. * @param string $objectType the object type (e.g. 'files')
  964. * @param string $objectId e.g. the file id
  965. * @return boolean
  966. * @since 9.0.0
  967. */
  968. public function deleteCommentsAtObject($objectType, $objectId) {
  969. $this->checkRoleParameters('Object', $objectType, $objectId);
  970. $qb = $this->dbConn->getQueryBuilder();
  971. $affectedRows = $qb
  972. ->delete('comments')
  973. ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
  974. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
  975. ->setParameter('type', $objectType)
  976. ->setParameter('id', $objectId)
  977. ->execute();
  978. $this->commentsCache = [];
  979. return is_int($affectedRows);
  980. }
  981. /**
  982. * deletes the read markers for the specified user
  983. *
  984. * @param \OCP\IUser $user
  985. * @return bool
  986. * @since 9.0.0
  987. */
  988. public function deleteReadMarksFromUser(IUser $user) {
  989. $qb = $this->dbConn->getQueryBuilder();
  990. $query = $qb->delete('comments_read_markers')
  991. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  992. ->setParameter('user_id', $user->getUID());
  993. try {
  994. $affectedRows = $query->execute();
  995. } catch (DriverException $e) {
  996. $this->logger->error($e->getMessage(), [
  997. 'exception' => $e,
  998. 'app' => 'core_comments',
  999. ]);
  1000. return false;
  1001. }
  1002. return ($affectedRows > 0);
  1003. }
  1004. /**
  1005. * sets the read marker for a given file to the specified date for the
  1006. * provided user
  1007. *
  1008. * @param string $objectType
  1009. * @param string $objectId
  1010. * @param \DateTime $dateTime
  1011. * @param IUser $user
  1012. * @since 9.0.0
  1013. */
  1014. public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
  1015. $this->checkRoleParameters('Object', $objectType, $objectId);
  1016. $qb = $this->dbConn->getQueryBuilder();
  1017. $values = [
  1018. 'user_id' => $qb->createNamedParameter($user->getUID()),
  1019. 'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
  1020. 'object_type' => $qb->createNamedParameter($objectType),
  1021. 'object_id' => $qb->createNamedParameter($objectId),
  1022. ];
  1023. // Strategy: try to update, if this does not return affected rows, do an insert.
  1024. $affectedRows = $qb
  1025. ->update('comments_read_markers')
  1026. ->set('user_id', $values['user_id'])
  1027. ->set('marker_datetime', $values['marker_datetime'])
  1028. ->set('object_type', $values['object_type'])
  1029. ->set('object_id', $values['object_id'])
  1030. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  1031. ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  1032. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  1033. ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
  1034. ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
  1035. ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
  1036. ->execute();
  1037. if ($affectedRows > 0) {
  1038. return;
  1039. }
  1040. $qb->insert('comments_read_markers')
  1041. ->values($values)
  1042. ->execute();
  1043. }
  1044. /**
  1045. * returns the read marker for a given file to the specified date for the
  1046. * provided user. It returns null, when the marker is not present, i.e.
  1047. * no comments were marked as read.
  1048. *
  1049. * @param string $objectType
  1050. * @param string $objectId
  1051. * @param IUser $user
  1052. * @return \DateTime|null
  1053. * @since 9.0.0
  1054. */
  1055. public function getReadMark($objectType, $objectId, IUser $user) {
  1056. $qb = $this->dbConn->getQueryBuilder();
  1057. $resultStatement = $qb->select('marker_datetime')
  1058. ->from('comments_read_markers')
  1059. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  1060. ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  1061. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  1062. ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
  1063. ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
  1064. ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
  1065. ->execute();
  1066. $data = $resultStatement->fetch();
  1067. $resultStatement->closeCursor();
  1068. if (!$data || is_null($data['marker_datetime'])) {
  1069. return null;
  1070. }
  1071. return new \DateTime($data['marker_datetime']);
  1072. }
  1073. /**
  1074. * deletes the read markers on the specified object
  1075. *
  1076. * @param string $objectType
  1077. * @param string $objectId
  1078. * @return bool
  1079. * @since 9.0.0
  1080. */
  1081. public function deleteReadMarksOnObject($objectType, $objectId) {
  1082. $this->checkRoleParameters('Object', $objectType, $objectId);
  1083. $qb = $this->dbConn->getQueryBuilder();
  1084. $query = $qb->delete('comments_read_markers')
  1085. ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  1086. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  1087. ->setParameter('object_type', $objectType)
  1088. ->setParameter('object_id', $objectId);
  1089. try {
  1090. $affectedRows = $query->execute();
  1091. } catch (DriverException $e) {
  1092. $this->logger->error($e->getMessage(), [
  1093. 'exception' => $e,
  1094. 'app' => 'core_comments',
  1095. ]);
  1096. return false;
  1097. }
  1098. return ($affectedRows > 0);
  1099. }
  1100. /**
  1101. * registers an Entity to the manager, so event notifications can be send
  1102. * to consumers of the comments infrastructure
  1103. *
  1104. * @param \Closure $closure
  1105. */
  1106. public function registerEventHandler(\Closure $closure) {
  1107. $this->eventHandlerClosures[] = $closure;
  1108. $this->eventHandlers = [];
  1109. }
  1110. /**
  1111. * registers a method that resolves an ID to a display name for a given type
  1112. *
  1113. * @param string $type
  1114. * @param \Closure $closure
  1115. * @throws \OutOfBoundsException
  1116. * @since 11.0.0
  1117. *
  1118. * Only one resolver shall be registered per type. Otherwise a
  1119. * \OutOfBoundsException has to thrown.
  1120. */
  1121. public function registerDisplayNameResolver($type, \Closure $closure) {
  1122. if (!is_string($type)) {
  1123. throw new \InvalidArgumentException('String expected.');
  1124. }
  1125. if (isset($this->displayNameResolvers[$type])) {
  1126. throw new \OutOfBoundsException('Displayname resolver for this type already registered');
  1127. }
  1128. $this->displayNameResolvers[$type] = $closure;
  1129. }
  1130. /**
  1131. * resolves a given ID of a given Type to a display name.
  1132. *
  1133. * @param string $type
  1134. * @param string $id
  1135. * @return string
  1136. * @throws \OutOfBoundsException
  1137. * @since 11.0.0
  1138. *
  1139. * If a provided type was not registered, an \OutOfBoundsException shall
  1140. * be thrown. It is upon the resolver discretion what to return of the
  1141. * provided ID is unknown. It must be ensured that a string is returned.
  1142. */
  1143. public function resolveDisplayName($type, $id) {
  1144. if (!is_string($type)) {
  1145. throw new \InvalidArgumentException('String expected.');
  1146. }
  1147. if (!isset($this->displayNameResolvers[$type])) {
  1148. throw new \OutOfBoundsException('No Displayname resolver for this type registered');
  1149. }
  1150. return (string)$this->displayNameResolvers[$type]($id);
  1151. }
  1152. /**
  1153. * returns valid, registered entities
  1154. *
  1155. * @return \OCP\Comments\ICommentsEventHandler[]
  1156. */
  1157. private function getEventHandlers() {
  1158. if (!empty($this->eventHandlers)) {
  1159. return $this->eventHandlers;
  1160. }
  1161. $this->eventHandlers = [];
  1162. foreach ($this->eventHandlerClosures as $name => $closure) {
  1163. $entity = $closure();
  1164. if (!($entity instanceof ICommentsEventHandler)) {
  1165. throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
  1166. }
  1167. $this->eventHandlers[$name] = $entity;
  1168. }
  1169. return $this->eventHandlers;
  1170. }
  1171. /**
  1172. * sends notifications to the registered entities
  1173. *
  1174. * @param $eventType
  1175. * @param IComment $comment
  1176. */
  1177. private function sendEvent($eventType, IComment $comment) {
  1178. $entities = $this->getEventHandlers();
  1179. $event = new CommentsEvent($eventType, $comment);
  1180. foreach ($entities as $entity) {
  1181. $entity->handle($event);
  1182. }
  1183. }
  1184. /**
  1185. * Load the Comments app into the page
  1186. *
  1187. * @since 21.0.0
  1188. */
  1189. public function load(): void {
  1190. $this->initialStateService->provideInitialState('comments', 'max-message-length', IComment::MAX_MESSAGE_LENGTH);
  1191. Util::addScript('comments', 'comments-app');
  1192. }
  1193. }