Manager.php 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  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. ->orderBy('message_id', 'DESC')
  933. ->executeQuery();
  934. $commentIds = [];
  935. while ($data = $result->fetch()) {
  936. $commentIds[] = $data['message_id'];
  937. }
  938. return $this->getCommentsById($commentIds);
  939. }
  940. /**
  941. * Retrieve all reactions with specific reaction of a message
  942. *
  943. * Throws PreConditionNotMetException when the system haven't the minimum requirements to
  944. * use reactions
  945. *
  946. * @param int $parentId
  947. * @param string $reaction
  948. * @return IComment[]
  949. * @throws PreConditionNotMetException
  950. * @since 24.0.0
  951. */
  952. public function retrieveAllReactionsWithSpecificReaction(int $parentId, string $reaction): array {
  953. $this->throwIfNotSupportReactions();
  954. $qb = $this->dbConn->getQueryBuilder();
  955. $result = $qb
  956. ->select('message_id')
  957. ->from('reactions')
  958. ->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($parentId)))
  959. ->andWhere($qb->expr()->eq('reaction', $qb->createNamedParameter($reaction)))
  960. ->executeQuery();
  961. $commentIds = [];
  962. while ($data = $result->fetch()) {
  963. $commentIds[] = $data['message_id'];
  964. }
  965. $comments = [];
  966. if ($commentIds) {
  967. $comments = $this->getCommentsById($commentIds);
  968. }
  969. return $comments;
  970. }
  971. /**
  972. * Support reactions
  973. *
  974. * @return bool
  975. * @since 24.0.0
  976. */
  977. public function supportReactions(): bool {
  978. return $this->emojiHelper->doesPlatformSupportEmoji();
  979. }
  980. /**
  981. * @throws PreConditionNotMetException
  982. * @since 24.0.0
  983. */
  984. private function throwIfNotSupportReactions() {
  985. if (!$this->supportReactions()) {
  986. throw new PreConditionNotMetException('The database does not support reactions');
  987. }
  988. }
  989. /**
  990. * Get all comments on list
  991. *
  992. * @param int[] $commentIds
  993. * @return IComment[]
  994. * @since 24.0.0
  995. */
  996. private function getCommentsById(array $commentIds): array {
  997. if (!$commentIds) {
  998. return [];
  999. }
  1000. $chunks = array_chunk($commentIds, 500);
  1001. $query = $this->dbConn->getQueryBuilder();
  1002. $query->select('*')
  1003. ->from('comments')
  1004. ->where($query->expr()->in('id', $query->createParameter('ids')))
  1005. ->orderBy('creation_timestamp', 'DESC')
  1006. ->addOrderBy('id', 'DESC');
  1007. $comments = [];
  1008. foreach ($chunks as $ids) {
  1009. $query->setParameter('ids', $ids, IQueryBuilder::PARAM_STR_ARRAY);
  1010. $result = $query->executeQuery();
  1011. while ($data = $result->fetch()) {
  1012. $comment = $this->getCommentFromData($data);
  1013. $this->cache($comment);
  1014. $comments[] = $comment;
  1015. }
  1016. $result->closeCursor();
  1017. }
  1018. return $comments;
  1019. }
  1020. /**
  1021. * saves the comment permanently
  1022. *
  1023. * if the supplied comment has an empty ID, a new entry comment will be
  1024. * saved and the instance updated with the new ID.
  1025. *
  1026. * Otherwise, an existing comment will be updated.
  1027. *
  1028. * Throws NotFoundException when a comment that is to be updated does not
  1029. * exist anymore at this point of time.
  1030. *
  1031. * Throws PreConditionNotMetException when the system haven't the minimum requirements to
  1032. * use reactions
  1033. *
  1034. * @param IComment $comment
  1035. * @return bool
  1036. * @throws NotFoundException
  1037. * @throws PreConditionNotMetException
  1038. * @since 9.0.0
  1039. */
  1040. public function save(IComment $comment) {
  1041. if ($comment->getVerb() === 'reaction') {
  1042. $this->throwIfNotSupportReactions();
  1043. }
  1044. if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
  1045. $result = $this->insert($comment);
  1046. } else {
  1047. $result = $this->update($comment);
  1048. }
  1049. if ($result && !!$comment->getParentId()) {
  1050. $this->updateChildrenInformation(
  1051. $comment->getParentId(),
  1052. $comment->getCreationDateTime()
  1053. );
  1054. $this->cache($comment);
  1055. }
  1056. return $result;
  1057. }
  1058. /**
  1059. * inserts the provided comment in the database
  1060. *
  1061. * @param IComment $comment
  1062. * @return bool
  1063. */
  1064. protected function insert(IComment $comment): bool {
  1065. try {
  1066. $result = $this->insertQuery($comment, true);
  1067. } catch (InvalidFieldNameException $e) {
  1068. // The reference id field was only added in Nextcloud 19.
  1069. // In order to not cause too long waiting times on the update,
  1070. // it was decided to only add it lazy, as it is also not a critical
  1071. // feature, but only helps to have a better experience while commenting.
  1072. // So in case the reference_id field is missing,
  1073. // we simply save the comment without that field.
  1074. $result = $this->insertQuery($comment, false);
  1075. }
  1076. return $result;
  1077. }
  1078. protected function insertQuery(IComment $comment, bool $tryWritingReferenceId): bool {
  1079. $qb = $this->dbConn->getQueryBuilder();
  1080. $values = [
  1081. 'parent_id' => $qb->createNamedParameter($comment->getParentId()),
  1082. 'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
  1083. 'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
  1084. 'actor_type' => $qb->createNamedParameter($comment->getActorType()),
  1085. 'actor_id' => $qb->createNamedParameter($comment->getActorId()),
  1086. 'message' => $qb->createNamedParameter($comment->getMessage()),
  1087. 'verb' => $qb->createNamedParameter($comment->getVerb()),
  1088. 'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
  1089. 'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
  1090. 'object_type' => $qb->createNamedParameter($comment->getObjectType()),
  1091. 'object_id' => $qb->createNamedParameter($comment->getObjectId()),
  1092. 'expire_date' => $qb->createNamedParameter($comment->getExpireDate(), 'datetime'),
  1093. ];
  1094. if ($tryWritingReferenceId) {
  1095. $values['reference_id'] = $qb->createNamedParameter($comment->getReferenceId());
  1096. }
  1097. $affectedRows = $qb->insert('comments')
  1098. ->values($values)
  1099. ->execute();
  1100. if ($affectedRows > 0) {
  1101. $comment->setId((string)$qb->getLastInsertId());
  1102. if ($comment->getVerb() === 'reaction') {
  1103. $this->addReaction($comment);
  1104. }
  1105. $this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
  1106. }
  1107. return $affectedRows > 0;
  1108. }
  1109. private function addReaction(IComment $reaction): void {
  1110. // Prevent violate constraint
  1111. $qb = $this->dbConn->getQueryBuilder();
  1112. $qb->select($qb->func()->count('*'))
  1113. ->from('reactions')
  1114. ->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($reaction->getParentId())))
  1115. ->andWhere($qb->expr()->eq('actor_type', $qb->createNamedParameter($reaction->getActorType())))
  1116. ->andWhere($qb->expr()->eq('actor_id', $qb->createNamedParameter($reaction->getActorId())))
  1117. ->andWhere($qb->expr()->eq('reaction', $qb->createNamedParameter($reaction->getMessage())));
  1118. $result = $qb->executeQuery();
  1119. $exists = (int) $result->fetchOne();
  1120. if (!$exists) {
  1121. $qb = $this->dbConn->getQueryBuilder();
  1122. try {
  1123. $qb->insert('reactions')
  1124. ->values([
  1125. 'parent_id' => $qb->createNamedParameter($reaction->getParentId()),
  1126. 'message_id' => $qb->createNamedParameter($reaction->getId()),
  1127. 'actor_type' => $qb->createNamedParameter($reaction->getActorType()),
  1128. 'actor_id' => $qb->createNamedParameter($reaction->getActorId()),
  1129. 'reaction' => $qb->createNamedParameter($reaction->getMessage()),
  1130. ])
  1131. ->executeStatement();
  1132. } catch (\Exception $e) {
  1133. $this->logger->error($e->getMessage(), [
  1134. 'exception' => $e,
  1135. 'app' => 'core_comments',
  1136. ]);
  1137. }
  1138. }
  1139. $this->sumReactions($reaction->getParentId());
  1140. }
  1141. private function sumReactions(string $parentId): void {
  1142. $totalQuery = $this->dbConn->getQueryBuilder();
  1143. $totalQuery
  1144. ->selectAlias(
  1145. $totalQuery->func()->concat(
  1146. $totalQuery->expr()->literal('"'),
  1147. 'reaction',
  1148. $totalQuery->expr()->literal('":'),
  1149. $totalQuery->func()->count('id')
  1150. ),
  1151. 'colonseparatedvalue'
  1152. )
  1153. ->selectAlias($totalQuery->func()->count('id'), 'total')
  1154. ->from('reactions', 'r')
  1155. ->where($totalQuery->expr()->eq('r.parent_id', $totalQuery->createNamedParameter($parentId)))
  1156. ->groupBy('r.reaction')
  1157. ->orderBy('total', 'DESC')
  1158. ->addOrderBy('r.reaction', 'ASC')
  1159. ->setMaxResults(20);
  1160. $jsonQuery = $this->dbConn->getQueryBuilder();
  1161. $jsonQuery
  1162. ->selectAlias(
  1163. $jsonQuery->func()->concat(
  1164. $jsonQuery->expr()->literal('{'),
  1165. $jsonQuery->func()->groupConcat('colonseparatedvalue'),
  1166. $jsonQuery->expr()->literal('}')
  1167. ),
  1168. 'json'
  1169. )
  1170. ->from($jsonQuery->createFunction('(' . $totalQuery->getSQL() . ')'), 'json');
  1171. $qb = $this->dbConn->getQueryBuilder();
  1172. $qb
  1173. ->update('comments')
  1174. ->set('reactions', $qb->createFunction('(' . $jsonQuery->getSQL() . ')'))
  1175. ->where($qb->expr()->eq('id', $qb->createNamedParameter($parentId)))
  1176. ->executeStatement();
  1177. }
  1178. /**
  1179. * updates a Comment data row
  1180. *
  1181. * @param IComment $comment
  1182. * @return bool
  1183. * @throws NotFoundException
  1184. */
  1185. protected function update(IComment $comment) {
  1186. // for properly working preUpdate Events we need the old comments as is
  1187. // in the DB and overcome caching. Also avoid that outdated information stays.
  1188. $this->uncache($comment->getId());
  1189. $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
  1190. $this->uncache($comment->getId());
  1191. try {
  1192. $result = $this->updateQuery($comment, true);
  1193. } catch (InvalidFieldNameException $e) {
  1194. // See function insert() for explanation
  1195. $result = $this->updateQuery($comment, false);
  1196. }
  1197. if ($comment->getVerb() === 'reaction_deleted') {
  1198. $this->deleteReaction($comment);
  1199. }
  1200. $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
  1201. return $result;
  1202. }
  1203. protected function updateQuery(IComment $comment, bool $tryWritingReferenceId): bool {
  1204. $qb = $this->dbConn->getQueryBuilder();
  1205. $qb
  1206. ->update('comments')
  1207. ->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
  1208. ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
  1209. ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
  1210. ->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
  1211. ->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
  1212. ->set('message', $qb->createNamedParameter($comment->getMessage()))
  1213. ->set('verb', $qb->createNamedParameter($comment->getVerb()))
  1214. ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
  1215. ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
  1216. ->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
  1217. ->set('object_id', $qb->createNamedParameter($comment->getObjectId()))
  1218. ->set('expire_date', $qb->createNamedParameter($comment->getExpireDate(), 'datetime'));
  1219. if ($tryWritingReferenceId) {
  1220. $qb->set('reference_id', $qb->createNamedParameter($comment->getReferenceId()));
  1221. }
  1222. $affectedRows = $qb->where($qb->expr()->eq('id', $qb->createNamedParameter($comment->getId())))
  1223. ->execute();
  1224. if ($affectedRows === 0) {
  1225. throw new NotFoundException('Comment to update does ceased to exist');
  1226. }
  1227. return $affectedRows > 0;
  1228. }
  1229. /**
  1230. * removes references to specific actor (e.g. on user delete) of a comment.
  1231. * The comment itself must not get lost/deleted.
  1232. *
  1233. * @param string $actorType the actor type (e.g. 'users')
  1234. * @param string $actorId a user id
  1235. * @return boolean
  1236. * @since 9.0.0
  1237. */
  1238. public function deleteReferencesOfActor($actorType, $actorId) {
  1239. $this->checkRoleParameters('Actor', $actorType, $actorId);
  1240. $qb = $this->dbConn->getQueryBuilder();
  1241. $affectedRows = $qb
  1242. ->update('comments')
  1243. ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
  1244. ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
  1245. ->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
  1246. ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
  1247. ->setParameter('type', $actorType)
  1248. ->setParameter('id', $actorId)
  1249. ->execute();
  1250. $this->commentsCache = [];
  1251. return is_int($affectedRows);
  1252. }
  1253. /**
  1254. * deletes all comments made of a specific object (e.g. on file delete)
  1255. *
  1256. * @param string $objectType the object type (e.g. 'files')
  1257. * @param string $objectId e.g. the file id
  1258. * @return boolean
  1259. * @since 9.0.0
  1260. */
  1261. public function deleteCommentsAtObject($objectType, $objectId) {
  1262. $this->checkRoleParameters('Object', $objectType, $objectId);
  1263. $qb = $this->dbConn->getQueryBuilder();
  1264. $affectedRows = $qb
  1265. ->delete('comments')
  1266. ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
  1267. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
  1268. ->setParameter('type', $objectType)
  1269. ->setParameter('id', $objectId)
  1270. ->execute();
  1271. $this->commentsCache = [];
  1272. return is_int($affectedRows);
  1273. }
  1274. /**
  1275. * deletes the read markers for the specified user
  1276. *
  1277. * @param \OCP\IUser $user
  1278. * @return bool
  1279. * @since 9.0.0
  1280. */
  1281. public function deleteReadMarksFromUser(IUser $user) {
  1282. $qb = $this->dbConn->getQueryBuilder();
  1283. $query = $qb->delete('comments_read_markers')
  1284. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  1285. ->setParameter('user_id', $user->getUID());
  1286. try {
  1287. $affectedRows = $query->execute();
  1288. } catch (DriverException $e) {
  1289. $this->logger->error($e->getMessage(), [
  1290. 'exception' => $e,
  1291. 'app' => 'core_comments',
  1292. ]);
  1293. return false;
  1294. }
  1295. return ($affectedRows > 0);
  1296. }
  1297. /**
  1298. * sets the read marker for a given file to the specified date for the
  1299. * provided user
  1300. *
  1301. * @param string $objectType
  1302. * @param string $objectId
  1303. * @param \DateTime $dateTime
  1304. * @param IUser $user
  1305. * @since 9.0.0
  1306. */
  1307. public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
  1308. $this->checkRoleParameters('Object', $objectType, $objectId);
  1309. $qb = $this->dbConn->getQueryBuilder();
  1310. $values = [
  1311. 'user_id' => $qb->createNamedParameter($user->getUID()),
  1312. 'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
  1313. 'object_type' => $qb->createNamedParameter($objectType),
  1314. 'object_id' => $qb->createNamedParameter($objectId),
  1315. ];
  1316. // Strategy: try to update, if this does not return affected rows, do an insert.
  1317. $affectedRows = $qb
  1318. ->update('comments_read_markers')
  1319. ->set('user_id', $values['user_id'])
  1320. ->set('marker_datetime', $values['marker_datetime'])
  1321. ->set('object_type', $values['object_type'])
  1322. ->set('object_id', $values['object_id'])
  1323. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  1324. ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  1325. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  1326. ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
  1327. ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
  1328. ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
  1329. ->execute();
  1330. if ($affectedRows > 0) {
  1331. return;
  1332. }
  1333. $qb->insert('comments_read_markers')
  1334. ->values($values)
  1335. ->execute();
  1336. }
  1337. /**
  1338. * returns the read marker for a given file to the specified date for the
  1339. * provided user. It returns null, when the marker is not present, i.e.
  1340. * no comments were marked as read.
  1341. *
  1342. * @param string $objectType
  1343. * @param string $objectId
  1344. * @param IUser $user
  1345. * @return \DateTime|null
  1346. * @since 9.0.0
  1347. */
  1348. public function getReadMark($objectType, $objectId, IUser $user) {
  1349. $qb = $this->dbConn->getQueryBuilder();
  1350. $resultStatement = $qb->select('marker_datetime')
  1351. ->from('comments_read_markers')
  1352. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  1353. ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  1354. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  1355. ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
  1356. ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
  1357. ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
  1358. ->execute();
  1359. $data = $resultStatement->fetch();
  1360. $resultStatement->closeCursor();
  1361. if (!$data || is_null($data['marker_datetime'])) {
  1362. return null;
  1363. }
  1364. return new \DateTime($data['marker_datetime']);
  1365. }
  1366. /**
  1367. * deletes the read markers on the specified object
  1368. *
  1369. * @param string $objectType
  1370. * @param string $objectId
  1371. * @return bool
  1372. * @since 9.0.0
  1373. */
  1374. public function deleteReadMarksOnObject($objectType, $objectId) {
  1375. $this->checkRoleParameters('Object', $objectType, $objectId);
  1376. $qb = $this->dbConn->getQueryBuilder();
  1377. $query = $qb->delete('comments_read_markers')
  1378. ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  1379. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  1380. ->setParameter('object_type', $objectType)
  1381. ->setParameter('object_id', $objectId);
  1382. try {
  1383. $affectedRows = $query->execute();
  1384. } catch (DriverException $e) {
  1385. $this->logger->error($e->getMessage(), [
  1386. 'exception' => $e,
  1387. 'app' => 'core_comments',
  1388. ]);
  1389. return false;
  1390. }
  1391. return ($affectedRows > 0);
  1392. }
  1393. /**
  1394. * registers an Entity to the manager, so event notifications can be send
  1395. * to consumers of the comments infrastructure
  1396. *
  1397. * @param \Closure $closure
  1398. */
  1399. public function registerEventHandler(\Closure $closure) {
  1400. $this->eventHandlerClosures[] = $closure;
  1401. $this->eventHandlers = [];
  1402. }
  1403. /**
  1404. * registers a method that resolves an ID to a display name for a given type
  1405. *
  1406. * @param string $type
  1407. * @param \Closure $closure
  1408. * @throws \OutOfBoundsException
  1409. * @since 11.0.0
  1410. *
  1411. * Only one resolver shall be registered per type. Otherwise a
  1412. * \OutOfBoundsException has to thrown.
  1413. */
  1414. public function registerDisplayNameResolver($type, \Closure $closure) {
  1415. if (!is_string($type)) {
  1416. throw new \InvalidArgumentException('String expected.');
  1417. }
  1418. if (isset($this->displayNameResolvers[$type])) {
  1419. throw new \OutOfBoundsException('Displayname resolver for this type already registered');
  1420. }
  1421. $this->displayNameResolvers[$type] = $closure;
  1422. }
  1423. /**
  1424. * resolves a given ID of a given Type to a display name.
  1425. *
  1426. * @param string $type
  1427. * @param string $id
  1428. * @return string
  1429. * @throws \OutOfBoundsException
  1430. * @since 11.0.0
  1431. *
  1432. * If a provided type was not registered, an \OutOfBoundsException shall
  1433. * be thrown. It is upon the resolver discretion what to return of the
  1434. * provided ID is unknown. It must be ensured that a string is returned.
  1435. */
  1436. public function resolveDisplayName($type, $id) {
  1437. if (!is_string($type)) {
  1438. throw new \InvalidArgumentException('String expected.');
  1439. }
  1440. if (!isset($this->displayNameResolvers[$type])) {
  1441. throw new \OutOfBoundsException('No Displayname resolver for this type registered');
  1442. }
  1443. return (string)$this->displayNameResolvers[$type]($id);
  1444. }
  1445. /**
  1446. * returns valid, registered entities
  1447. *
  1448. * @return \OCP\Comments\ICommentsEventHandler[]
  1449. */
  1450. private function getEventHandlers() {
  1451. if (!empty($this->eventHandlers)) {
  1452. return $this->eventHandlers;
  1453. }
  1454. $this->eventHandlers = [];
  1455. foreach ($this->eventHandlerClosures as $name => $closure) {
  1456. $entity = $closure();
  1457. if (!($entity instanceof ICommentsEventHandler)) {
  1458. throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
  1459. }
  1460. $this->eventHandlers[$name] = $entity;
  1461. }
  1462. return $this->eventHandlers;
  1463. }
  1464. /**
  1465. * sends notifications to the registered entities
  1466. *
  1467. * @param $eventType
  1468. * @param IComment $comment
  1469. */
  1470. private function sendEvent($eventType, IComment $comment) {
  1471. $entities = $this->getEventHandlers();
  1472. $event = new CommentsEvent($eventType, $comment);
  1473. foreach ($entities as $entity) {
  1474. $entity->handle($event);
  1475. }
  1476. }
  1477. /**
  1478. * Load the Comments app into the page
  1479. *
  1480. * @since 21.0.0
  1481. */
  1482. public function load(): void {
  1483. $this->initialStateService->provideInitialState('comments', 'max-message-length', IComment::MAX_MESSAGE_LENGTH);
  1484. Util::addScript('comments', 'comments-app');
  1485. }
  1486. /**
  1487. * @inheritDoc
  1488. */
  1489. public function deleteCommentsExpiredAtObject(string $objectType, string $objectId = ''): bool {
  1490. $qb = $this->dbConn->getQueryBuilder();
  1491. $qb->delete('comments')
  1492. ->where($qb->expr()->lte('expire_date',
  1493. $qb->createNamedParameter($this->timeFactory->getDateTime(), IQueryBuilder::PARAM_DATE)))
  1494. ->andWhere($qb->expr()->eq('object_type', $qb->createNamedParameter($objectType)));
  1495. if ($objectId !== '') {
  1496. $qb->andWhere($qb->expr()->eq('object_id', $qb->createNamedParameter($objectId)));
  1497. }
  1498. $affectedRows = $qb->executeStatement();
  1499. $this->commentsCache = [];
  1500. return $affectedRows > 0;
  1501. }
  1502. }