1
0

Manager.php 48 KB

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