Manager.php 51 KB

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