Manager.php 50 KB

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