Manager.php 49 KB

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