Manager.php 50 KB

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