Manager.php 51 KB

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