Manager.php 51 KB

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