1
0

Manager.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Comments;
  8. use Doctrine\DBAL\Exception\DriverException;
  9. use OCA\DAV\Connector\Sabre\File;
  10. use OCP\AppFramework\Utility\ITimeFactory;
  11. use OCP\Comments\CommentsEvent;
  12. use OCP\Comments\IComment;
  13. use OCP\Comments\ICommentsEventHandler;
  14. use OCP\Comments\ICommentsManager;
  15. use OCP\Comments\NotFoundException;
  16. use OCP\DB\QueryBuilder\IQueryBuilder;
  17. use OCP\EventDispatcher\IEventDispatcher;
  18. use OCP\Files\FileInfo;
  19. use OCP\Files\Folder;
  20. use OCP\Files\IRootFolder;
  21. use OCP\IConfig;
  22. use OCP\IDBConnection;
  23. use OCP\IEmojiHelper;
  24. use OCP\IInitialStateService;
  25. use OCP\IUser;
  26. use OCP\PreConditionNotMetException;
  27. use OCP\Util;
  28. use Psr\Log\LoggerInterface;
  29. class Manager implements ICommentsManager {
  30. /** @var IComment[] */
  31. protected array $commentsCache = [];
  32. /** @var \Closure[] */
  33. protected array $eventHandlerClosures = [];
  34. /** @var ICommentsEventHandler[] */
  35. protected array $eventHandlers = [];
  36. /** @var \Closure[] */
  37. protected array $displayNameResolvers = [];
  38. public function __construct(
  39. protected IDBConnection $dbConn,
  40. protected LoggerInterface $logger,
  41. protected IConfig $config,
  42. protected ITimeFactory $timeFactory,
  43. protected IEmojiHelper $emojiHelper,
  44. protected IInitialStateService $initialStateService,
  45. protected IRootFolder $rootFolder,
  46. protected IEventDispatcher $eventDispatcher,
  47. ) {
  48. }
  49. /**
  50. * converts data base data into PHP native, proper types as defined by
  51. * IComment interface.
  52. *
  53. * @param array $data
  54. */
  55. protected function normalizeDatabaseData(array $data): array {
  56. $data['id'] = (string)$data['id'];
  57. $data['parent_id'] = (string)$data['parent_id'];
  58. $data['topmost_parent_id'] = (string)$data['topmost_parent_id'];
  59. $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
  60. if (!is_null($data['latest_child_timestamp'])) {
  61. $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
  62. }
  63. if (!is_null($data['expire_date'])) {
  64. $data['expire_date'] = new \DateTime($data['expire_date']);
  65. }
  66. $data['children_count'] = (int)$data['children_count'];
  67. $data['reference_id'] = $data['reference_id'];
  68. $data['meta_data'] = json_decode($data['meta_data'], true);
  69. if ($this->supportReactions()) {
  70. if ($data['reactions'] !== null) {
  71. $list = json_decode($data['reactions'], true);
  72. // Ordering does not work on the database with group concat and Oracle,
  73. // So we simply sort on the output.
  74. if (is_array($list)) {
  75. uasort($list, static function ($a, $b) {
  76. if ($a === $b) {
  77. return 0;
  78. }
  79. return ($a > $b) ? -1 : 1;
  80. });
  81. $data['reactions'] = $list;
  82. } else {
  83. $data['reactions'] = [];
  84. }
  85. } else {
  86. $data['reactions'] = [];
  87. }
  88. }
  89. return $data;
  90. }
  91. public function getCommentFromData(array $data): IComment {
  92. return new Comment($this->normalizeDatabaseData($data));
  93. }
  94. /**
  95. * prepares a comment for an insert or update operation after making sure
  96. * all necessary fields have a value assigned.
  97. *
  98. * @param IComment $comment
  99. * @return IComment returns the same updated IComment instance as provided
  100. * by parameter for convenience
  101. * @throws \UnexpectedValueException
  102. */
  103. protected function prepareCommentForDatabaseWrite(IComment $comment): IComment {
  104. if (!$comment->getActorType()
  105. || $comment->getActorId() === ''
  106. || !$comment->getObjectType()
  107. || $comment->getObjectId() === ''
  108. || !$comment->getVerb()
  109. ) {
  110. throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
  111. }
  112. if ($comment->getVerb() === 'reaction' && !$this->emojiHelper->isValidSingleEmoji($comment->getMessage())) {
  113. // 4 characters: laptop + person + gender + skin color => "🧑🏽‍💻" is a single emoji from the picker
  114. throw new \UnexpectedValueException('Reactions can only be a single emoji');
  115. }
  116. if ($comment->getId() === '') {
  117. $comment->setChildrenCount(0);
  118. $comment->setLatestChildDateTime(null);
  119. }
  120. try {
  121. $comment->getCreationDateTime();
  122. } catch(\LogicException $e) {
  123. $comment->setCreationDateTime(new \DateTime());
  124. }
  125. if ($comment->getParentId() !== '0') {
  126. $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
  127. } else {
  128. $comment->setTopmostParentId('0');
  129. }
  130. $this->cache($comment);
  131. return $comment;
  132. }
  133. /**
  134. * returns the topmost parent id of a given comment identified by ID
  135. *
  136. * @param string $id
  137. * @throws NotFoundException
  138. */
  139. protected function determineTopmostParentId($id): string {
  140. $comment = $this->get($id);
  141. if ($comment->getParentId() === '0') {
  142. return $comment->getId();
  143. }
  144. return $this->determineTopmostParentId($comment->getParentId());
  145. }
  146. /**
  147. * updates child information of a comment
  148. *
  149. * @param string $id
  150. * @param \DateTime $cDateTime the date time of the most recent child
  151. * @throws NotFoundException
  152. */
  153. protected function updateChildrenInformation($id, \DateTime $cDateTime): void {
  154. $qb = $this->dbConn->getQueryBuilder();
  155. $query = $qb->select($qb->func()->count('id'))
  156. ->from('comments')
  157. ->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
  158. ->setParameter('id', $id);
  159. $resultStatement = $query->execute();
  160. $data = $resultStatement->fetch(\PDO::FETCH_NUM);
  161. $resultStatement->closeCursor();
  162. $children = (int)$data[0];
  163. $comment = $this->get($id);
  164. $comment->setChildrenCount($children);
  165. $comment->setLatestChildDateTime($cDateTime);
  166. $this->save($comment);
  167. }
  168. /**
  169. * Tests whether actor or object type and id parameters are acceptable.
  170. * Throws exception if not.
  171. *
  172. * @param string $role
  173. * @param string $type
  174. * @param string $id
  175. * @throws \InvalidArgumentException
  176. */
  177. protected function checkRoleParameters($role, $type, $id): void {
  178. if (
  179. !is_string($type) || empty($type)
  180. || !is_string($id) || empty($id)
  181. ) {
  182. throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
  183. }
  184. }
  185. /**
  186. * run-time caches a comment
  187. */
  188. protected function cache(IComment $comment): void {
  189. $id = $comment->getId();
  190. if (empty($id)) {
  191. return;
  192. }
  193. $this->commentsCache[(string)$id] = $comment;
  194. }
  195. /**
  196. * removes an entry from the comments run time cache
  197. *
  198. * @param mixed $id the comment's id
  199. */
  200. protected function uncache($id): void {
  201. $id = (string)$id;
  202. if (isset($this->commentsCache[$id])) {
  203. unset($this->commentsCache[$id]);
  204. }
  205. }
  206. /**
  207. * returns a comment instance
  208. *
  209. * @param string $id the ID of the comment
  210. * @throws NotFoundException
  211. * @throws \InvalidArgumentException
  212. * @since 9.0.0
  213. */
  214. public function get($id): IComment {
  215. if ((int)$id === 0) {
  216. throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
  217. }
  218. if (isset($this->commentsCache[$id])) {
  219. return $this->commentsCache[$id];
  220. }
  221. $qb = $this->dbConn->getQueryBuilder();
  222. $resultStatement = $qb->select('*')
  223. ->from('comments')
  224. ->where($qb->expr()->eq('id', $qb->createParameter('id')))
  225. ->setParameter('id', $id, IQueryBuilder::PARAM_INT)
  226. ->execute();
  227. $data = $resultStatement->fetch();
  228. $resultStatement->closeCursor();
  229. if (!$data) {
  230. throw new NotFoundException();
  231. }
  232. $comment = $this->getCommentFromData($data);
  233. $this->cache($comment);
  234. return $comment;
  235. }
  236. /**
  237. * @inheritDoc
  238. */
  239. public function getTree($id, $limit = 0, $offset = 0): array {
  240. $tree = [];
  241. $tree['comment'] = $this->get($id);
  242. $tree['replies'] = [];
  243. $qb = $this->dbConn->getQueryBuilder();
  244. $query = $qb->select('*')
  245. ->from('comments')
  246. ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
  247. ->orderBy('creation_timestamp', 'DESC')
  248. ->setParameter('id', $id);
  249. if ($limit > 0) {
  250. $query->setMaxResults($limit);
  251. }
  252. if ($offset > 0) {
  253. $query->setFirstResult($offset);
  254. }
  255. $resultStatement = $query->execute();
  256. while ($data = $resultStatement->fetch()) {
  257. $comment = $this->getCommentFromData($data);
  258. $this->cache($comment);
  259. $tree['replies'][] = [
  260. 'comment' => $comment,
  261. 'replies' => []
  262. ];
  263. }
  264. $resultStatement->closeCursor();
  265. return $tree;
  266. }
  267. /**
  268. * returns comments for a specific object (e.g. a file).
  269. *
  270. * The sort order is always newest to oldest.
  271. *
  272. * @param string $objectType the object type, e.g. 'files'
  273. * @param string $objectId the id of the object
  274. * @param int $limit optional, number of maximum comments to be returned. if
  275. * not specified, all comments are returned.
  276. * @param int $offset optional, starting point
  277. * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
  278. * that may be returned
  279. * @return list<IComment>
  280. * @since 9.0.0
  281. */
  282. public function getForObject(
  283. $objectType,
  284. $objectId,
  285. $limit = 0,
  286. $offset = 0,
  287. ?\DateTime $notOlderThan = null
  288. ) {
  289. $comments = [];
  290. $qb = $this->dbConn->getQueryBuilder();
  291. $query = $qb->select('*')
  292. ->from('comments')
  293. ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
  294. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
  295. ->orderBy('creation_timestamp', 'DESC')
  296. ->setParameter('type', $objectType)
  297. ->setParameter('id', $objectId);
  298. if ($limit > 0) {
  299. $query->setMaxResults($limit);
  300. }
  301. if ($offset > 0) {
  302. $query->setFirstResult($offset);
  303. }
  304. if (!is_null($notOlderThan)) {
  305. $query
  306. ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
  307. ->setParameter('notOlderThan', $notOlderThan, 'datetime');
  308. }
  309. $resultStatement = $query->execute();
  310. while ($data = $resultStatement->fetch()) {
  311. $comment = $this->getCommentFromData($data);
  312. $this->cache($comment);
  313. $comments[] = $comment;
  314. }
  315. $resultStatement->closeCursor();
  316. return $comments;
  317. }
  318. /**
  319. * @param string $objectType the object type, e.g. 'files'
  320. * @param string $objectId the id of the object
  321. * @param int $lastKnownCommentId the last known comment (will be used as offset)
  322. * @param string $sortDirection direction of the comments (`asc` or `desc`)
  323. * @param int $limit optional, number of maximum comments to be returned. if
  324. * set to 0, all comments are returned.
  325. * @param bool $includeLastKnown
  326. * @return list<IComment>
  327. */
  328. public function getForObjectSince(
  329. string $objectType,
  330. string $objectId,
  331. int $lastKnownCommentId,
  332. string $sortDirection = 'asc',
  333. int $limit = 30,
  334. bool $includeLastKnown = false
  335. ): array {
  336. return $this->getCommentsWithVerbForObjectSinceComment(
  337. $objectType,
  338. $objectId,
  339. [],
  340. $lastKnownCommentId,
  341. $sortDirection,
  342. $limit,
  343. $includeLastKnown
  344. );
  345. }
  346. /**
  347. * @param string $objectType the object type, e.g. 'files'
  348. * @param string $objectId the id of the object
  349. * @param string[] $verbs List of verbs to filter by
  350. * @param int $lastKnownCommentId the last known comment (will be used as offset)
  351. * @param string $sortDirection direction of the comments (`asc` or `desc`)
  352. * @param int $limit optional, number of maximum comments to be returned. if
  353. * set to 0, all comments are returned.
  354. * @param bool $includeLastKnown
  355. * @return list<IComment>
  356. */
  357. public function getCommentsWithVerbForObjectSinceComment(
  358. string $objectType,
  359. string $objectId,
  360. array $verbs,
  361. int $lastKnownCommentId,
  362. string $sortDirection = 'asc',
  363. int $limit = 30,
  364. bool $includeLastKnown = false
  365. ): array {
  366. $comments = [];
  367. $query = $this->dbConn->getQueryBuilder();
  368. $query->select('*')
  369. ->from('comments')
  370. ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
  371. ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
  372. ->orderBy('creation_timestamp', $sortDirection === 'desc' ? 'DESC' : 'ASC')
  373. ->addOrderBy('id', $sortDirection === 'desc' ? 'DESC' : 'ASC');
  374. if ($limit > 0) {
  375. $query->setMaxResults($limit);
  376. }
  377. if (!empty($verbs)) {
  378. $query->andWhere($query->expr()->in('verb', $query->createNamedParameter($verbs, IQueryBuilder::PARAM_STR_ARRAY)));
  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. } elseif ($lastKnownCommentId > 0) {
  435. // We didn't find the "$lastKnownComment" but we still use the ID as an offset.
  436. // This is required as a fall-back for expired messages in talk and deleted comments in other apps.
  437. if ($sortDirection === 'desc') {
  438. if ($includeLastKnown) {
  439. $query->andWhere($query->expr()->lte('id', $query->createNamedParameter($lastKnownCommentId)));
  440. } else {
  441. $query->andWhere($query->expr()->lt('id', $query->createNamedParameter($lastKnownCommentId)));
  442. }
  443. } else {
  444. if ($includeLastKnown) {
  445. $query->andWhere($query->expr()->gte('id', $query->createNamedParameter($lastKnownCommentId)));
  446. } else {
  447. $query->andWhere($query->expr()->gt('id', $query->createNamedParameter($lastKnownCommentId)));
  448. }
  449. }
  450. }
  451. $resultStatement = $query->execute();
  452. while ($data = $resultStatement->fetch()) {
  453. $comment = $this->getCommentFromData($data);
  454. $this->cache($comment);
  455. $comments[] = $comment;
  456. }
  457. $resultStatement->closeCursor();
  458. return $comments;
  459. }
  460. /**
  461. * @param string $objectType the object type, e.g. 'files'
  462. * @param string $objectId the id of the object
  463. * @param int $id the comment to look for
  464. */
  465. protected function getLastKnownComment(string $objectType,
  466. string $objectId,
  467. int $id): ?IComment {
  468. $query = $this->dbConn->getQueryBuilder();
  469. $query->select('*')
  470. ->from('comments')
  471. ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
  472. ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
  473. ->andWhere($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
  474. $result = $query->execute();
  475. $row = $result->fetch();
  476. $result->closeCursor();
  477. if ($row) {
  478. $comment = $this->getCommentFromData($row);
  479. $this->cache($comment);
  480. return $comment;
  481. }
  482. return null;
  483. }
  484. /**
  485. * Search for comments with a given content
  486. *
  487. * @param string $search content to search for
  488. * @param string $objectType Limit the search by object type
  489. * @param string $objectId Limit the search by object id
  490. * @param string $verb Limit the verb of the comment
  491. * @param int $offset
  492. * @param int $limit
  493. * @return list<IComment>
  494. */
  495. public function search(string $search, string $objectType, string $objectId, string $verb, int $offset, int $limit = 50): array {
  496. $objectIds = [];
  497. if ($objectId) {
  498. $objectIds[] = $objectId;
  499. }
  500. return $this->searchForObjects($search, $objectType, $objectIds, $verb, $offset, $limit);
  501. }
  502. /**
  503. * Search for comments on one or more objects with a given content
  504. *
  505. * @param string $search content to search for
  506. * @param string $objectType Limit the search by object type
  507. * @param array $objectIds Limit the search by object ids
  508. * @param string $verb Limit the verb of the comment
  509. * @param int $offset
  510. * @param int $limit
  511. * @return list<IComment>
  512. */
  513. public function searchForObjects(string $search, string $objectType, array $objectIds, string $verb, int $offset, int $limit = 50): array {
  514. $query = $this->dbConn->getQueryBuilder();
  515. $query->select('*')
  516. ->from('comments')
  517. ->orderBy('creation_timestamp', 'DESC')
  518. ->addOrderBy('id', 'DESC')
  519. ->setMaxResults($limit);
  520. if ($search !== '') {
  521. $query->where($query->expr()->iLike('message', $query->createNamedParameter(
  522. '%' . $this->dbConn->escapeLikeParameter($search). '%'
  523. )));
  524. }
  525. if ($objectType !== '') {
  526. $query->andWhere($query->expr()->eq('object_type', $query->createNamedParameter($objectType)));
  527. }
  528. if (!empty($objectIds)) {
  529. $query->andWhere($query->expr()->in('object_id', $query->createNamedParameter($objectIds, IQueryBuilder::PARAM_STR_ARRAY)));
  530. }
  531. if ($verb !== '') {
  532. $query->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)));
  533. }
  534. if ($offset !== 0) {
  535. $query->setFirstResult($offset);
  536. }
  537. $comments = [];
  538. $result = $query->execute();
  539. while ($data = $result->fetch()) {
  540. $comment = $this->getCommentFromData($data);
  541. $this->cache($comment);
  542. $comments[] = $comment;
  543. }
  544. $result->closeCursor();
  545. return $comments;
  546. }
  547. /**
  548. * @param $objectType string the object type, e.g. 'files'
  549. * @param $objectId string the id of the object
  550. * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
  551. * that may be returned
  552. * @param string $verb Limit the verb of the comment - Added in 14.0.0
  553. * @return Int
  554. * @since 9.0.0
  555. */
  556. public function getNumberOfCommentsForObject($objectType, $objectId, ?\DateTime $notOlderThan = null, $verb = '') {
  557. $qb = $this->dbConn->getQueryBuilder();
  558. $query = $qb->select($qb->func()->count('id'))
  559. ->from('comments')
  560. ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
  561. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
  562. ->setParameter('type', $objectType)
  563. ->setParameter('id', $objectId);
  564. if (!is_null($notOlderThan)) {
  565. $query
  566. ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
  567. ->setParameter('notOlderThan', $notOlderThan, 'datetime');
  568. }
  569. if ($verb !== '') {
  570. $query->andWhere($qb->expr()->eq('verb', $qb->createNamedParameter($verb)));
  571. }
  572. $resultStatement = $query->execute();
  573. $data = $resultStatement->fetch(\PDO::FETCH_NUM);
  574. $resultStatement->closeCursor();
  575. return (int)$data[0];
  576. }
  577. /**
  578. * @param string $objectType the object type, e.g. 'files'
  579. * @param string[] $objectIds the id of the object
  580. * @param IUser $user
  581. * @param string $verb Limit the verb of the comment - Added in 14.0.0
  582. * @return array Map with object id => # of unread comments
  583. * @psalm-return array<string, int>
  584. * @since 21.0.0
  585. */
  586. public function getNumberOfUnreadCommentsForObjects(string $objectType, array $objectIds, IUser $user, $verb = ''): array {
  587. $unreadComments = [];
  588. $query = $this->dbConn->getQueryBuilder();
  589. $query->select('c.object_id', $query->func()->count('c.id', 'num_comments'))
  590. ->from('comments', 'c')
  591. ->leftJoin('c', 'comments_read_markers', 'm', $query->expr()->andX(
  592. $query->expr()->eq('m.user_id', $query->createNamedParameter($user->getUID())),
  593. $query->expr()->eq('c.object_type', 'm.object_type'),
  594. $query->expr()->eq('c.object_id', 'm.object_id')
  595. ))
  596. ->where($query->expr()->eq('c.object_type', $query->createNamedParameter($objectType)))
  597. ->andWhere($query->expr()->in('c.object_id', $query->createParameter('ids')))
  598. ->andWhere($query->expr()->orX(
  599. $query->expr()->gt('c.creation_timestamp', 'm.marker_datetime'),
  600. $query->expr()->isNull('m.marker_datetime')
  601. ))
  602. ->groupBy('c.object_id');
  603. if ($verb !== '') {
  604. $query->andWhere($query->expr()->eq('c.verb', $query->createNamedParameter($verb)));
  605. }
  606. $unreadComments = array_fill_keys($objectIds, 0);
  607. foreach (array_chunk($objectIds, 1000) as $chunk) {
  608. $query->setParameter('ids', $chunk, IQueryBuilder::PARAM_STR_ARRAY);
  609. $result = $query->executeQuery();
  610. while ($row = $result->fetch()) {
  611. $unreadComments[$row['object_id']] = (int) $row['num_comments'];
  612. }
  613. $result->closeCursor();
  614. }
  615. return $unreadComments;
  616. }
  617. /**
  618. * @param string $objectType
  619. * @param string $objectId
  620. * @param int $lastRead
  621. * @param string $verb
  622. * @return int
  623. * @since 21.0.0
  624. */
  625. public function getNumberOfCommentsForObjectSinceComment(string $objectType, string $objectId, int $lastRead, string $verb = ''): int {
  626. if ($verb !== '') {
  627. return $this->getNumberOfCommentsWithVerbsForObjectSinceComment($objectType, $objectId, $lastRead, [$verb]);
  628. }
  629. return $this->getNumberOfCommentsWithVerbsForObjectSinceComment($objectType, $objectId, $lastRead, []);
  630. }
  631. /**
  632. * @param string $objectType
  633. * @param string $objectId
  634. * @param int $lastRead
  635. * @param string[] $verbs
  636. * @return int
  637. * @since 24.0.0
  638. */
  639. public function getNumberOfCommentsWithVerbsForObjectSinceComment(string $objectType, string $objectId, int $lastRead, array $verbs): int {
  640. $query = $this->dbConn->getQueryBuilder();
  641. $query->select($query->func()->count('id', 'num_messages'))
  642. ->from('comments')
  643. ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
  644. ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
  645. ->andWhere($query->expr()->gt('id', $query->createNamedParameter($lastRead)));
  646. if (!empty($verbs)) {
  647. $query->andWhere($query->expr()->in('verb', $query->createNamedParameter($verbs, IQueryBuilder::PARAM_STR_ARRAY)));
  648. }
  649. $result = $query->executeQuery();
  650. $data = $result->fetch();
  651. $result->closeCursor();
  652. return (int) ($data['num_messages'] ?? 0);
  653. }
  654. /**
  655. * @param string $objectType
  656. * @param string $objectId
  657. * @param \DateTime $beforeDate
  658. * @param string $verb
  659. * @return int
  660. * @since 21.0.0
  661. */
  662. public function getLastCommentBeforeDate(string $objectType, string $objectId, \DateTime $beforeDate, string $verb = ''): int {
  663. $query = $this->dbConn->getQueryBuilder();
  664. $query->select('id')
  665. ->from('comments')
  666. ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
  667. ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
  668. ->andWhere($query->expr()->lt('creation_timestamp', $query->createNamedParameter($beforeDate, IQueryBuilder::PARAM_DATE)))
  669. ->orderBy('creation_timestamp', 'desc');
  670. if ($verb !== '') {
  671. $query->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)));
  672. }
  673. $result = $query->execute();
  674. $data = $result->fetch();
  675. $result->closeCursor();
  676. return (int) ($data['id'] ?? 0);
  677. }
  678. /**
  679. * @param string $objectType
  680. * @param string $objectId
  681. * @param string $verb
  682. * @param string $actorType
  683. * @param string[] $actors
  684. * @return \DateTime[] Map of "string actor" => "\DateTime most recent comment date"
  685. * @psalm-return array<string, \DateTime>
  686. * @since 21.0.0
  687. */
  688. public function getLastCommentDateByActor(
  689. string $objectType,
  690. string $objectId,
  691. string $verb,
  692. string $actorType,
  693. array $actors
  694. ): array {
  695. $lastComments = [];
  696. $query = $this->dbConn->getQueryBuilder();
  697. $query->select('actor_id')
  698. ->selectAlias($query->createFunction('MAX(' . $query->getColumnName('creation_timestamp') . ')'), 'last_comment')
  699. ->from('comments')
  700. ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
  701. ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
  702. ->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)))
  703. ->andWhere($query->expr()->eq('actor_type', $query->createNamedParameter($actorType)))
  704. ->andWhere($query->expr()->in('actor_id', $query->createNamedParameter($actors, IQueryBuilder::PARAM_STR_ARRAY)))
  705. ->groupBy('actor_id');
  706. $result = $query->execute();
  707. while ($row = $result->fetch()) {
  708. $lastComments[$row['actor_id']] = $this->timeFactory->getDateTime($row['last_comment']);
  709. }
  710. $result->closeCursor();
  711. return $lastComments;
  712. }
  713. /**
  714. * Get the number of unread comments for all files in a folder
  715. *
  716. * This is unused since 8bd39fccf411195839f2dadee085fad18ec52c23
  717. *
  718. * @param int $folderId
  719. * @param IUser $user
  720. * @return array [$fileId => $unreadCount]
  721. */
  722. public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
  723. $directory = $this->rootFolder->getFirstNodeById($folderId);
  724. if (!$directory instanceof Folder) {
  725. return [];
  726. }
  727. $children = $directory->getDirectoryListing();
  728. $ids = array_map(fn (FileInfo $child) => (string) $child->getId(), $children);
  729. $ids[] = (string) $directory->getId();
  730. $counts = $this->getNumberOfUnreadCommentsForObjects('files', $ids, $user);
  731. return array_filter($counts, function (int $count) {
  732. return $count > 0;
  733. });
  734. }
  735. /**
  736. * creates a new comment and returns it. At this point of time, it is not
  737. * saved in the used data storage. Use save() after setting other fields
  738. * of the comment (e.g. message or verb).
  739. *
  740. * @param string $actorType the actor type (e.g. 'users')
  741. * @param string $actorId a user id
  742. * @param string $objectType the object type the comment is attached to
  743. * @param string $objectId the object id the comment is attached to
  744. * @return IComment
  745. * @since 9.0.0
  746. */
  747. public function create($actorType, $actorId, $objectType, $objectId) {
  748. $comment = new Comment();
  749. $comment
  750. ->setActor($actorType, $actorId)
  751. ->setObject($objectType, $objectId);
  752. return $comment;
  753. }
  754. /**
  755. * permanently deletes the comment specified by the ID
  756. *
  757. * When the comment has child comments, their parent ID will be changed to
  758. * the parent ID of the item that is to be deleted.
  759. *
  760. * @param string $id
  761. * @return bool
  762. * @throws \InvalidArgumentException
  763. * @since 9.0.0
  764. */
  765. public function delete($id) {
  766. if (!is_string($id)) {
  767. throw new \InvalidArgumentException('Parameter must be string');
  768. }
  769. try {
  770. $comment = $this->get($id);
  771. } catch (\Exception $e) {
  772. // Ignore exceptions, we just don't fire a hook then
  773. $comment = null;
  774. }
  775. $qb = $this->dbConn->getQueryBuilder();
  776. $query = $qb->delete('comments')
  777. ->where($qb->expr()->eq('id', $qb->createParameter('id')))
  778. ->setParameter('id', $id);
  779. try {
  780. $affectedRows = $query->execute();
  781. $this->uncache($id);
  782. } catch (DriverException $e) {
  783. $this->logger->error($e->getMessage(), [
  784. 'exception' => $e,
  785. 'app' => 'core_comments',
  786. ]);
  787. return false;
  788. }
  789. if ($affectedRows > 0 && $comment instanceof IComment) {
  790. if ($comment->getVerb() === 'reaction_deleted') {
  791. $this->deleteReaction($comment);
  792. }
  793. $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
  794. }
  795. return ($affectedRows > 0);
  796. }
  797. private function deleteReaction(IComment $reaction): void {
  798. $qb = $this->dbConn->getQueryBuilder();
  799. $qb->delete('reactions')
  800. ->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($reaction->getParentId())))
  801. ->andWhere($qb->expr()->eq('message_id', $qb->createNamedParameter($reaction->getId())))
  802. ->executeStatement();
  803. $this->sumReactions($reaction->getParentId());
  804. }
  805. /**
  806. * Get comment related with user reaction
  807. *
  808. * Throws PreConditionNotMetException when the system haven't the minimum requirements to
  809. * use reactions
  810. *
  811. * @param int $parentId
  812. * @param string $actorType
  813. * @param string $actorId
  814. * @param string $reaction
  815. * @return IComment
  816. * @throws NotFoundException
  817. * @throws PreConditionNotMetException
  818. * @since 24.0.0
  819. */
  820. public function getReactionComment(int $parentId, string $actorType, string $actorId, string $reaction): IComment {
  821. $this->throwIfNotSupportReactions();
  822. $qb = $this->dbConn->getQueryBuilder();
  823. $messageId = $qb
  824. ->select('message_id')
  825. ->from('reactions')
  826. ->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($parentId)))
  827. ->andWhere($qb->expr()->eq('actor_type', $qb->createNamedParameter($actorType)))
  828. ->andWhere($qb->expr()->eq('actor_id', $qb->createNamedParameter($actorId)))
  829. ->andWhere($qb->expr()->eq('reaction', $qb->createNamedParameter($reaction)))
  830. ->executeQuery()
  831. ->fetchOne();
  832. if (!$messageId) {
  833. throw new NotFoundException('Comment related with reaction not found');
  834. }
  835. return $this->get($messageId);
  836. }
  837. /**
  838. * Retrieve all reactions of a message
  839. *
  840. * Throws PreConditionNotMetException when the system haven't the minimum requirements to
  841. * use reactions
  842. *
  843. * @param int $parentId
  844. * @return IComment[]
  845. * @throws PreConditionNotMetException
  846. * @since 24.0.0
  847. */
  848. public function retrieveAllReactions(int $parentId): array {
  849. $this->throwIfNotSupportReactions();
  850. $qb = $this->dbConn->getQueryBuilder();
  851. $result = $qb
  852. ->select('message_id')
  853. ->from('reactions')
  854. ->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($parentId)))
  855. ->orderBy('message_id', 'DESC')
  856. ->executeQuery();
  857. $commentIds = [];
  858. while ($data = $result->fetch()) {
  859. $commentIds[] = $data['message_id'];
  860. }
  861. return $this->getCommentsById($commentIds);
  862. }
  863. /**
  864. * Retrieve all reactions with specific reaction of a message
  865. *
  866. * Throws PreConditionNotMetException when the system haven't the minimum requirements to
  867. * use reactions
  868. *
  869. * @param int $parentId
  870. * @param string $reaction
  871. * @return IComment[]
  872. * @throws PreConditionNotMetException
  873. * @since 24.0.0
  874. */
  875. public function retrieveAllReactionsWithSpecificReaction(int $parentId, string $reaction): array {
  876. $this->throwIfNotSupportReactions();
  877. $qb = $this->dbConn->getQueryBuilder();
  878. $result = $qb
  879. ->select('message_id')
  880. ->from('reactions')
  881. ->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($parentId)))
  882. ->andWhere($qb->expr()->eq('reaction', $qb->createNamedParameter($reaction)))
  883. ->executeQuery();
  884. $commentIds = [];
  885. while ($data = $result->fetch()) {
  886. $commentIds[] = $data['message_id'];
  887. }
  888. $comments = [];
  889. if ($commentIds) {
  890. $comments = $this->getCommentsById($commentIds);
  891. }
  892. return $comments;
  893. }
  894. /**
  895. * Support reactions
  896. *
  897. * @return bool
  898. * @since 24.0.0
  899. */
  900. public function supportReactions(): bool {
  901. return $this->emojiHelper->doesPlatformSupportEmoji();
  902. }
  903. /**
  904. * @throws PreConditionNotMetException
  905. * @since 24.0.0
  906. */
  907. private function throwIfNotSupportReactions() {
  908. if (!$this->supportReactions()) {
  909. throw new PreConditionNotMetException('The database does not support reactions');
  910. }
  911. }
  912. /**
  913. * Get all comments on list
  914. *
  915. * @param int[] $commentIds
  916. * @return IComment[]
  917. * @since 24.0.0
  918. */
  919. private function getCommentsById(array $commentIds): array {
  920. if (!$commentIds) {
  921. return [];
  922. }
  923. $chunks = array_chunk($commentIds, 500);
  924. $query = $this->dbConn->getQueryBuilder();
  925. $query->select('*')
  926. ->from('comments')
  927. ->where($query->expr()->in('id', $query->createParameter('ids')))
  928. ->orderBy('creation_timestamp', 'DESC')
  929. ->addOrderBy('id', 'DESC');
  930. $comments = [];
  931. foreach ($chunks as $ids) {
  932. $query->setParameter('ids', $ids, IQueryBuilder::PARAM_STR_ARRAY);
  933. $result = $query->executeQuery();
  934. while ($data = $result->fetch()) {
  935. $comment = $this->getCommentFromData($data);
  936. $this->cache($comment);
  937. $comments[] = $comment;
  938. }
  939. $result->closeCursor();
  940. }
  941. return $comments;
  942. }
  943. /**
  944. * saves the comment permanently
  945. *
  946. * if the supplied comment has an empty ID, a new entry comment will be
  947. * saved and the instance updated with the new ID.
  948. *
  949. * Otherwise, an existing comment will be updated.
  950. *
  951. * Throws NotFoundException when a comment that is to be updated does not
  952. * exist anymore at this point of time.
  953. *
  954. * Throws PreConditionNotMetException when the system haven't the minimum requirements to
  955. * use reactions
  956. *
  957. * @param IComment $comment
  958. * @return bool
  959. * @throws NotFoundException
  960. * @throws PreConditionNotMetException
  961. * @since 9.0.0
  962. */
  963. public function save(IComment $comment) {
  964. if ($comment->getVerb() === 'reaction') {
  965. $this->throwIfNotSupportReactions();
  966. }
  967. if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
  968. $result = $this->insert($comment);
  969. } else {
  970. $result = $this->update($comment);
  971. }
  972. if ($result && !!$comment->getParentId()) {
  973. $this->updateChildrenInformation(
  974. $comment->getParentId(),
  975. $comment->getCreationDateTime()
  976. );
  977. $this->cache($comment);
  978. }
  979. return $result;
  980. }
  981. /**
  982. * inserts the provided comment in the database
  983. *
  984. * @param IComment $comment
  985. * @return bool
  986. */
  987. protected function insert(IComment $comment): bool {
  988. $qb = $this->dbConn->getQueryBuilder();
  989. $values = [
  990. 'parent_id' => $qb->createNamedParameter($comment->getParentId()),
  991. 'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
  992. 'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
  993. 'actor_type' => $qb->createNamedParameter($comment->getActorType()),
  994. 'actor_id' => $qb->createNamedParameter($comment->getActorId()),
  995. 'message' => $qb->createNamedParameter($comment->getMessage()),
  996. 'verb' => $qb->createNamedParameter($comment->getVerb()),
  997. 'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
  998. 'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
  999. 'object_type' => $qb->createNamedParameter($comment->getObjectType()),
  1000. 'object_id' => $qb->createNamedParameter($comment->getObjectId()),
  1001. 'expire_date' => $qb->createNamedParameter($comment->getExpireDate(), 'datetime'),
  1002. 'reference_id' => $qb->createNamedParameter($comment->getReferenceId()),
  1003. 'meta_data' => $qb->createNamedParameter(json_encode($comment->getMetaData())),
  1004. ];
  1005. $affectedRows = $qb->insert('comments')
  1006. ->values($values)
  1007. ->execute();
  1008. if ($affectedRows > 0) {
  1009. $comment->setId((string)$qb->getLastInsertId());
  1010. if ($comment->getVerb() === 'reaction') {
  1011. $this->addReaction($comment);
  1012. }
  1013. $this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
  1014. }
  1015. return $affectedRows > 0;
  1016. }
  1017. private function addReaction(IComment $reaction): void {
  1018. // Prevent violate constraint
  1019. $qb = $this->dbConn->getQueryBuilder();
  1020. $qb->select($qb->func()->count('*'))
  1021. ->from('reactions')
  1022. ->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($reaction->getParentId())))
  1023. ->andWhere($qb->expr()->eq('actor_type', $qb->createNamedParameter($reaction->getActorType())))
  1024. ->andWhere($qb->expr()->eq('actor_id', $qb->createNamedParameter($reaction->getActorId())))
  1025. ->andWhere($qb->expr()->eq('reaction', $qb->createNamedParameter($reaction->getMessage())));
  1026. $result = $qb->executeQuery();
  1027. $exists = (int) $result->fetchOne();
  1028. if (!$exists) {
  1029. $qb = $this->dbConn->getQueryBuilder();
  1030. try {
  1031. $qb->insert('reactions')
  1032. ->values([
  1033. 'parent_id' => $qb->createNamedParameter($reaction->getParentId()),
  1034. 'message_id' => $qb->createNamedParameter($reaction->getId()),
  1035. 'actor_type' => $qb->createNamedParameter($reaction->getActorType()),
  1036. 'actor_id' => $qb->createNamedParameter($reaction->getActorId()),
  1037. 'reaction' => $qb->createNamedParameter($reaction->getMessage()),
  1038. ])
  1039. ->executeStatement();
  1040. } catch (\Exception $e) {
  1041. $this->logger->error($e->getMessage(), [
  1042. 'exception' => $e,
  1043. 'app' => 'core_comments',
  1044. ]);
  1045. }
  1046. }
  1047. $this->sumReactions($reaction->getParentId());
  1048. }
  1049. private function sumReactions(string $parentId): void {
  1050. $totalQuery = $this->dbConn->getQueryBuilder();
  1051. $totalQuery
  1052. ->selectAlias(
  1053. $totalQuery->func()->concat(
  1054. $totalQuery->expr()->literal('"'),
  1055. 'reaction',
  1056. $totalQuery->expr()->literal('":'),
  1057. $totalQuery->func()->count('id')
  1058. ),
  1059. 'colonseparatedvalue'
  1060. )
  1061. ->selectAlias($totalQuery->func()->count('id'), 'total')
  1062. ->from('reactions', 'r')
  1063. ->where($totalQuery->expr()->eq('r.parent_id', $totalQuery->createNamedParameter($parentId)))
  1064. ->groupBy('r.reaction')
  1065. ->orderBy('total', 'DESC')
  1066. ->addOrderBy('r.reaction', 'ASC')
  1067. ->setMaxResults(20);
  1068. $jsonQuery = $this->dbConn->getQueryBuilder();
  1069. $jsonQuery
  1070. ->selectAlias(
  1071. $jsonQuery->func()->concat(
  1072. $jsonQuery->expr()->literal('{'),
  1073. $jsonQuery->func()->groupConcat('colonseparatedvalue'),
  1074. $jsonQuery->expr()->literal('}')
  1075. ),
  1076. 'json'
  1077. )
  1078. ->from($jsonQuery->createFunction('(' . $totalQuery->getSQL() . ')'), 'json');
  1079. $qb = $this->dbConn->getQueryBuilder();
  1080. $qb
  1081. ->update('comments')
  1082. ->set('reactions', $qb->createFunction('(' . $jsonQuery->getSQL() . ')'))
  1083. ->where($qb->expr()->eq('id', $qb->createNamedParameter($parentId)))
  1084. ->executeStatement();
  1085. }
  1086. /**
  1087. * updates a Comment data row
  1088. *
  1089. * @param IComment $comment
  1090. * @return bool
  1091. * @throws NotFoundException
  1092. */
  1093. protected function update(IComment $comment) {
  1094. // for properly working preUpdate Events we need the old comments as is
  1095. // in the DB and overcome caching. Also avoid that outdated information stays.
  1096. $this->uncache($comment->getId());
  1097. $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
  1098. $this->uncache($comment->getId());
  1099. $result = $this->updateQuery($comment);
  1100. if ($comment->getVerb() === 'reaction_deleted') {
  1101. $this->deleteReaction($comment);
  1102. }
  1103. $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
  1104. return $result;
  1105. }
  1106. protected function updateQuery(IComment $comment): bool {
  1107. $qb = $this->dbConn->getQueryBuilder();
  1108. $qb
  1109. ->update('comments')
  1110. ->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
  1111. ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
  1112. ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
  1113. ->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
  1114. ->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
  1115. ->set('message', $qb->createNamedParameter($comment->getMessage()))
  1116. ->set('verb', $qb->createNamedParameter($comment->getVerb()))
  1117. ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
  1118. ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
  1119. ->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
  1120. ->set('object_id', $qb->createNamedParameter($comment->getObjectId()))
  1121. ->set('expire_date', $qb->createNamedParameter($comment->getExpireDate(), 'datetime'))
  1122. ->set('reference_id', $qb->createNamedParameter($comment->getReferenceId()))
  1123. ->set('meta_data', $qb->createNamedParameter(json_encode($comment->getMetaData())))
  1124. ->where($qb->expr()->eq('id', $qb->createNamedParameter($comment->getId())));
  1125. $affectedRows = $qb->executeStatement();
  1126. if ($affectedRows === 0) {
  1127. throw new NotFoundException('Comment to update does ceased to exist');
  1128. }
  1129. return $affectedRows > 0;
  1130. }
  1131. /**
  1132. * removes references to specific actor (e.g. on user delete) of a comment.
  1133. * The comment itself must not get lost/deleted.
  1134. *
  1135. * @param string $actorType the actor type (e.g. 'users')
  1136. * @param string $actorId a user id
  1137. * @return boolean
  1138. * @since 9.0.0
  1139. */
  1140. public function deleteReferencesOfActor($actorType, $actorId) {
  1141. $this->checkRoleParameters('Actor', $actorType, $actorId);
  1142. $qb = $this->dbConn->getQueryBuilder();
  1143. $affectedRows = $qb
  1144. ->update('comments')
  1145. ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
  1146. ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
  1147. ->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
  1148. ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
  1149. ->setParameter('type', $actorType)
  1150. ->setParameter('id', $actorId)
  1151. ->execute();
  1152. $this->commentsCache = [];
  1153. return is_int($affectedRows);
  1154. }
  1155. /**
  1156. * deletes all comments made of a specific object (e.g. on file delete)
  1157. *
  1158. * @param string $objectType the object type (e.g. 'files')
  1159. * @param string $objectId e.g. the file id
  1160. * @return boolean
  1161. * @since 9.0.0
  1162. */
  1163. public function deleteCommentsAtObject($objectType, $objectId) {
  1164. $this->checkRoleParameters('Object', $objectType, $objectId);
  1165. $qb = $this->dbConn->getQueryBuilder();
  1166. $affectedRows = $qb
  1167. ->delete('comments')
  1168. ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
  1169. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
  1170. ->setParameter('type', $objectType)
  1171. ->setParameter('id', $objectId)
  1172. ->execute();
  1173. $this->commentsCache = [];
  1174. return is_int($affectedRows);
  1175. }
  1176. /**
  1177. * deletes the read markers for the specified user
  1178. *
  1179. * @param \OCP\IUser $user
  1180. * @return bool
  1181. * @since 9.0.0
  1182. */
  1183. public function deleteReadMarksFromUser(IUser $user) {
  1184. $qb = $this->dbConn->getQueryBuilder();
  1185. $query = $qb->delete('comments_read_markers')
  1186. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  1187. ->setParameter('user_id', $user->getUID());
  1188. try {
  1189. $affectedRows = $query->execute();
  1190. } catch (DriverException $e) {
  1191. $this->logger->error($e->getMessage(), [
  1192. 'exception' => $e,
  1193. 'app' => 'core_comments',
  1194. ]);
  1195. return false;
  1196. }
  1197. return ($affectedRows > 0);
  1198. }
  1199. /**
  1200. * sets the read marker for a given file to the specified date for the
  1201. * provided user
  1202. *
  1203. * @param string $objectType
  1204. * @param string $objectId
  1205. * @param \DateTime $dateTime
  1206. * @param IUser $user
  1207. * @since 9.0.0
  1208. */
  1209. public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
  1210. $this->checkRoleParameters('Object', $objectType, $objectId);
  1211. $qb = $this->dbConn->getQueryBuilder();
  1212. $values = [
  1213. 'user_id' => $qb->createNamedParameter($user->getUID()),
  1214. 'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
  1215. 'object_type' => $qb->createNamedParameter($objectType),
  1216. 'object_id' => $qb->createNamedParameter($objectId),
  1217. ];
  1218. // Strategy: try to update, if this does not return affected rows, do an insert.
  1219. $affectedRows = $qb
  1220. ->update('comments_read_markers')
  1221. ->set('user_id', $values['user_id'])
  1222. ->set('marker_datetime', $values['marker_datetime'])
  1223. ->set('object_type', $values['object_type'])
  1224. ->set('object_id', $values['object_id'])
  1225. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  1226. ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  1227. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  1228. ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
  1229. ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
  1230. ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
  1231. ->execute();
  1232. if ($affectedRows > 0) {
  1233. return;
  1234. }
  1235. $qb->insert('comments_read_markers')
  1236. ->values($values)
  1237. ->execute();
  1238. }
  1239. /**
  1240. * returns the read marker for a given file to the specified date for the
  1241. * provided user. It returns null, when the marker is not present, i.e.
  1242. * no comments were marked as read.
  1243. *
  1244. * @param string $objectType
  1245. * @param string $objectId
  1246. * @param IUser $user
  1247. * @return \DateTime|null
  1248. * @since 9.0.0
  1249. */
  1250. public function getReadMark($objectType, $objectId, IUser $user) {
  1251. $qb = $this->dbConn->getQueryBuilder();
  1252. $resultStatement = $qb->select('marker_datetime')
  1253. ->from('comments_read_markers')
  1254. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  1255. ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  1256. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  1257. ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
  1258. ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
  1259. ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
  1260. ->execute();
  1261. $data = $resultStatement->fetch();
  1262. $resultStatement->closeCursor();
  1263. if (!$data || is_null($data['marker_datetime'])) {
  1264. return null;
  1265. }
  1266. return new \DateTime($data['marker_datetime']);
  1267. }
  1268. /**
  1269. * deletes the read markers on the specified object
  1270. *
  1271. * @param string $objectType
  1272. * @param string $objectId
  1273. * @return bool
  1274. * @since 9.0.0
  1275. */
  1276. public function deleteReadMarksOnObject($objectType, $objectId) {
  1277. $this->checkRoleParameters('Object', $objectType, $objectId);
  1278. $qb = $this->dbConn->getQueryBuilder();
  1279. $query = $qb->delete('comments_read_markers')
  1280. ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  1281. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  1282. ->setParameter('object_type', $objectType)
  1283. ->setParameter('object_id', $objectId);
  1284. try {
  1285. $affectedRows = $query->execute();
  1286. } catch (DriverException $e) {
  1287. $this->logger->error($e->getMessage(), [
  1288. 'exception' => $e,
  1289. 'app' => 'core_comments',
  1290. ]);
  1291. return false;
  1292. }
  1293. return ($affectedRows > 0);
  1294. }
  1295. /**
  1296. * registers an Entity to the manager, so event notifications can be send
  1297. * to consumers of the comments infrastructure
  1298. *
  1299. * @param \Closure $closure
  1300. */
  1301. public function registerEventHandler(\Closure $closure) {
  1302. $this->eventHandlerClosures[] = $closure;
  1303. $this->eventHandlers = [];
  1304. }
  1305. /**
  1306. * registers a method that resolves an ID to a display name for a given type
  1307. *
  1308. * @param string $type
  1309. * @param \Closure $closure
  1310. * @throws \OutOfBoundsException
  1311. * @since 11.0.0
  1312. *
  1313. * Only one resolver shall be registered per type. Otherwise a
  1314. * \OutOfBoundsException has to thrown.
  1315. */
  1316. public function registerDisplayNameResolver($type, \Closure $closure) {
  1317. if (!is_string($type)) {
  1318. throw new \InvalidArgumentException('String expected.');
  1319. }
  1320. if (isset($this->displayNameResolvers[$type])) {
  1321. throw new \OutOfBoundsException('Displayname resolver for this type already registered');
  1322. }
  1323. $this->displayNameResolvers[$type] = $closure;
  1324. }
  1325. /**
  1326. * resolves a given ID of a given Type to a display name.
  1327. *
  1328. * @param string $type
  1329. * @param string $id
  1330. * @return string
  1331. * @throws \OutOfBoundsException
  1332. * @since 11.0.0
  1333. *
  1334. * If a provided type was not registered, an \OutOfBoundsException shall
  1335. * be thrown. It is upon the resolver discretion what to return of the
  1336. * provided ID is unknown. It must be ensured that a string is returned.
  1337. */
  1338. public function resolveDisplayName($type, $id) {
  1339. if (!is_string($type)) {
  1340. throw new \InvalidArgumentException('String expected.');
  1341. }
  1342. if (!isset($this->displayNameResolvers[$type])) {
  1343. throw new \OutOfBoundsException('No Displayname resolver for this type registered');
  1344. }
  1345. return (string)$this->displayNameResolvers[$type]($id);
  1346. }
  1347. /**
  1348. * returns valid, registered entities
  1349. *
  1350. * @return \OCP\Comments\ICommentsEventHandler[]
  1351. */
  1352. private function getEventHandlers() {
  1353. if (!empty($this->eventHandlers)) {
  1354. return $this->eventHandlers;
  1355. }
  1356. $this->eventHandlers = [];
  1357. foreach ($this->eventHandlerClosures as $name => $closure) {
  1358. $entity = $closure();
  1359. if (!($entity instanceof ICommentsEventHandler)) {
  1360. throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
  1361. }
  1362. $this->eventHandlers[$name] = $entity;
  1363. }
  1364. return $this->eventHandlers;
  1365. }
  1366. /**
  1367. * sends notifications to the registered entities
  1368. *
  1369. * @param $eventType
  1370. * @param IComment $comment
  1371. */
  1372. private function sendEvent($eventType, IComment $comment) {
  1373. $entities = $this->getEventHandlers();
  1374. $event = new CommentsEvent($eventType, $comment);
  1375. foreach ($entities as $entity) {
  1376. $entity->handle($event);
  1377. }
  1378. $this->eventDispatcher->dispatchTyped($event);
  1379. }
  1380. /**
  1381. * Load the Comments app into the page
  1382. *
  1383. * @since 21.0.0
  1384. */
  1385. public function load(): void {
  1386. $this->initialStateService->provideInitialState('comments', 'max-message-length', IComment::MAX_MESSAGE_LENGTH);
  1387. Util::addScript('comments', 'comments-app');
  1388. }
  1389. /**
  1390. * @inheritDoc
  1391. */
  1392. public function deleteCommentsExpiredAtObject(string $objectType, string $objectId = ''): bool {
  1393. $qb = $this->dbConn->getQueryBuilder();
  1394. $qb->delete('comments')
  1395. ->where($qb->expr()->lte('expire_date',
  1396. $qb->createNamedParameter($this->timeFactory->getDateTime(), IQueryBuilder::PARAM_DATE)))
  1397. ->andWhere($qb->expr()->eq('object_type', $qb->createNamedParameter($objectType)));
  1398. if ($objectId !== '') {
  1399. $qb->andWhere($qb->expr()->eq('object_id', $qb->createNamedParameter($objectId)));
  1400. }
  1401. $affectedRows = $qb->executeStatement();
  1402. $this->commentsCache = [];
  1403. return $affectedRows > 0;
  1404. }
  1405. }