Manager.php 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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 Lukas Reschke <lukas@statuscode.ch>
  8. * @author Robin Appelman <robin@icewind.nl>
  9. * @author Roeland Jago Douma <roeland@famdouma.nl>
  10. * @author Thomas Müller <thomas.mueller@tmit.eu>
  11. *
  12. * @license AGPL-3.0
  13. *
  14. * This code is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Affero General Public License, version 3,
  16. * as published by the Free Software Foundation.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Affero General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Affero General Public License, version 3,
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>
  25. *
  26. */
  27. namespace OC\Comments;
  28. use Doctrine\DBAL\Exception\DriverException;
  29. use OCP\Comments\CommentsEvent;
  30. use OCP\Comments\IComment;
  31. use OCP\Comments\ICommentsEventHandler;
  32. use OCP\Comments\ICommentsManager;
  33. use OCP\Comments\NotFoundException;
  34. use OCP\DB\QueryBuilder\IQueryBuilder;
  35. use OCP\IDBConnection;
  36. use OCP\IConfig;
  37. use OCP\ILogger;
  38. use OCP\IUser;
  39. class Manager implements ICommentsManager {
  40. /** @var IDBConnection */
  41. protected $dbConn;
  42. /** @var ILogger */
  43. protected $logger;
  44. /** @var IConfig */
  45. protected $config;
  46. /** @var IComment[] */
  47. protected $commentsCache = [];
  48. /** @var \Closure[] */
  49. protected $eventHandlerClosures = [];
  50. /** @var ICommentsEventHandler[] */
  51. protected $eventHandlers = [];
  52. /** @var \Closure[] */
  53. protected $displayNameResolvers = [];
  54. /**
  55. * Manager constructor.
  56. *
  57. * @param IDBConnection $dbConn
  58. * @param ILogger $logger
  59. * @param IConfig $config
  60. */
  61. public function __construct(
  62. IDBConnection $dbConn,
  63. ILogger $logger,
  64. IConfig $config
  65. ) {
  66. $this->dbConn = $dbConn;
  67. $this->logger = $logger;
  68. $this->config = $config;
  69. }
  70. /**
  71. * converts data base data into PHP native, proper types as defined by
  72. * IComment interface.
  73. *
  74. * @param array $data
  75. * @return array
  76. */
  77. protected function normalizeDatabaseData(array $data) {
  78. $data['id'] = (string)$data['id'];
  79. $data['parent_id'] = (string)$data['parent_id'];
  80. $data['topmost_parent_id'] = (string)$data['topmost_parent_id'];
  81. $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
  82. if (!is_null($data['latest_child_timestamp'])) {
  83. $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
  84. }
  85. $data['children_count'] = (int)$data['children_count'];
  86. return $data;
  87. }
  88. /**
  89. * prepares a comment for an insert or update operation after making sure
  90. * all necessary fields have a value assigned.
  91. *
  92. * @param IComment $comment
  93. * @return IComment returns the same updated IComment instance as provided
  94. * by parameter for convenience
  95. * @throws \UnexpectedValueException
  96. */
  97. protected function prepareCommentForDatabaseWrite(IComment $comment) {
  98. if (!$comment->getActorType()
  99. || !$comment->getActorId()
  100. || !$comment->getObjectType()
  101. || !$comment->getObjectId()
  102. || !$comment->getVerb()
  103. ) {
  104. throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
  105. }
  106. if ($comment->getId() === '') {
  107. $comment->setChildrenCount(0);
  108. $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
  109. $comment->setLatestChildDateTime(null);
  110. }
  111. if (is_null($comment->getCreationDateTime())) {
  112. $comment->setCreationDateTime(new \DateTime());
  113. }
  114. if ($comment->getParentId() !== '0') {
  115. $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
  116. } else {
  117. $comment->setTopmostParentId('0');
  118. }
  119. $this->cache($comment);
  120. return $comment;
  121. }
  122. /**
  123. * returns the topmost parent id of a given comment identified by ID
  124. *
  125. * @param string $id
  126. * @return string
  127. * @throws NotFoundException
  128. */
  129. protected function determineTopmostParentId($id) {
  130. $comment = $this->get($id);
  131. if ($comment->getParentId() === '0') {
  132. return $comment->getId();
  133. } else {
  134. return $this->determineTopmostParentId($comment->getId());
  135. }
  136. }
  137. /**
  138. * updates child information of a comment
  139. *
  140. * @param string $id
  141. * @param \DateTime $cDateTime the date time of the most recent child
  142. * @throws NotFoundException
  143. */
  144. protected function updateChildrenInformation($id, \DateTime $cDateTime) {
  145. $qb = $this->dbConn->getQueryBuilder();
  146. $query = $qb->select($qb->createFunction('COUNT(`id`)'))
  147. ->from('comments')
  148. ->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
  149. ->setParameter('id', $id);
  150. $resultStatement = $query->execute();
  151. $data = $resultStatement->fetch(\PDO::FETCH_NUM);
  152. $resultStatement->closeCursor();
  153. $children = (int)$data[0];
  154. $comment = $this->get($id);
  155. $comment->setChildrenCount($children);
  156. $comment->setLatestChildDateTime($cDateTime);
  157. $this->save($comment);
  158. }
  159. /**
  160. * Tests whether actor or object type and id parameters are acceptable.
  161. * Throws exception if not.
  162. *
  163. * @param string $role
  164. * @param string $type
  165. * @param string $id
  166. * @throws \InvalidArgumentException
  167. */
  168. protected function checkRoleParameters($role, $type, $id) {
  169. if (
  170. !is_string($type) || empty($type)
  171. || !is_string($id) || empty($id)
  172. ) {
  173. throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
  174. }
  175. }
  176. /**
  177. * run-time caches a comment
  178. *
  179. * @param IComment $comment
  180. */
  181. protected function cache(IComment $comment) {
  182. $id = $comment->getId();
  183. if (empty($id)) {
  184. return;
  185. }
  186. $this->commentsCache[(string)$id] = $comment;
  187. }
  188. /**
  189. * removes an entry from the comments run time cache
  190. *
  191. * @param mixed $id the comment's id
  192. */
  193. protected function uncache($id) {
  194. $id = (string)$id;
  195. if (isset($this->commentsCache[$id])) {
  196. unset($this->commentsCache[$id]);
  197. }
  198. }
  199. /**
  200. * returns a comment instance
  201. *
  202. * @param string $id the ID of the comment
  203. * @return IComment
  204. * @throws NotFoundException
  205. * @throws \InvalidArgumentException
  206. * @since 9.0.0
  207. */
  208. public function get($id) {
  209. if ((int)$id === 0) {
  210. throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
  211. }
  212. if (isset($this->commentsCache[$id])) {
  213. return $this->commentsCache[$id];
  214. }
  215. $qb = $this->dbConn->getQueryBuilder();
  216. $resultStatement = $qb->select('*')
  217. ->from('comments')
  218. ->where($qb->expr()->eq('id', $qb->createParameter('id')))
  219. ->setParameter('id', $id, IQueryBuilder::PARAM_INT)
  220. ->execute();
  221. $data = $resultStatement->fetch();
  222. $resultStatement->closeCursor();
  223. if (!$data) {
  224. throw new NotFoundException();
  225. }
  226. $comment = new Comment($this->normalizeDatabaseData($data));
  227. $this->cache($comment);
  228. return $comment;
  229. }
  230. /**
  231. * returns the comment specified by the id and all it's child comments.
  232. * At this point of time, we do only support one level depth.
  233. *
  234. * @param string $id
  235. * @param int $limit max number of entries to return, 0 returns all
  236. * @param int $offset the start entry
  237. * @return array
  238. * @since 9.0.0
  239. *
  240. * The return array looks like this
  241. * [
  242. * 'comment' => IComment, // root comment
  243. * 'replies' =>
  244. * [
  245. * 0 =>
  246. * [
  247. * 'comment' => IComment,
  248. * 'replies' => []
  249. * ]
  250. * 1 =>
  251. * [
  252. * 'comment' => IComment,
  253. * 'replies'=> []
  254. * ],
  255. * …
  256. * ]
  257. * ]
  258. */
  259. public function getTree($id, $limit = 0, $offset = 0) {
  260. $tree = [];
  261. $tree['comment'] = $this->get($id);
  262. $tree['replies'] = [];
  263. $qb = $this->dbConn->getQueryBuilder();
  264. $query = $qb->select('*')
  265. ->from('comments')
  266. ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
  267. ->orderBy('creation_timestamp', 'DESC')
  268. ->setParameter('id', $id);
  269. if ($limit > 0) {
  270. $query->setMaxResults($limit);
  271. }
  272. if ($offset > 0) {
  273. $query->setFirstResult($offset);
  274. }
  275. $resultStatement = $query->execute();
  276. while ($data = $resultStatement->fetch()) {
  277. $comment = new Comment($this->normalizeDatabaseData($data));
  278. $this->cache($comment);
  279. $tree['replies'][] = [
  280. 'comment' => $comment,
  281. 'replies' => []
  282. ];
  283. }
  284. $resultStatement->closeCursor();
  285. return $tree;
  286. }
  287. /**
  288. * returns comments for a specific object (e.g. a file).
  289. *
  290. * The sort order is always newest to oldest.
  291. *
  292. * @param string $objectType the object type, e.g. 'files'
  293. * @param string $objectId the id of the object
  294. * @param int $limit optional, number of maximum comments to be returned. if
  295. * not specified, all comments are returned.
  296. * @param int $offset optional, starting point
  297. * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
  298. * that may be returned
  299. * @return IComment[]
  300. * @since 9.0.0
  301. */
  302. public function getForObject(
  303. $objectType,
  304. $objectId,
  305. $limit = 0,
  306. $offset = 0,
  307. \DateTime $notOlderThan = null
  308. ) {
  309. $comments = [];
  310. $qb = $this->dbConn->getQueryBuilder();
  311. $query = $qb->select('*')
  312. ->from('comments')
  313. ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
  314. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
  315. ->orderBy('creation_timestamp', 'DESC')
  316. ->setParameter('type', $objectType)
  317. ->setParameter('id', $objectId);
  318. if ($limit > 0) {
  319. $query->setMaxResults($limit);
  320. }
  321. if ($offset > 0) {
  322. $query->setFirstResult($offset);
  323. }
  324. if (!is_null($notOlderThan)) {
  325. $query
  326. ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
  327. ->setParameter('notOlderThan', $notOlderThan, 'datetime');
  328. }
  329. $resultStatement = $query->execute();
  330. while ($data = $resultStatement->fetch()) {
  331. $comment = new Comment($this->normalizeDatabaseData($data));
  332. $this->cache($comment);
  333. $comments[] = $comment;
  334. }
  335. $resultStatement->closeCursor();
  336. return $comments;
  337. }
  338. /**
  339. * @param string $objectType the object type, e.g. 'files'
  340. * @param string $objectId the id of the object
  341. * @param int $lastKnownCommentId the last known comment (will be used as offset)
  342. * @param string $sortDirection direction of the comments (`asc` or `desc`)
  343. * @param int $limit optional, number of maximum comments to be returned. if
  344. * set to 0, all comments are returned.
  345. * @return IComment[]
  346. * @return array
  347. */
  348. public function getForObjectSince(
  349. string $objectType,
  350. string $objectId,
  351. int $lastKnownCommentId,
  352. string $sortDirection = 'asc',
  353. int $limit = 30
  354. ): array {
  355. $comments = [];
  356. $query = $this->dbConn->getQueryBuilder();
  357. $query->select('*')
  358. ->from('comments')
  359. ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
  360. ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
  361. ->orderBy('creation_timestamp', $sortDirection === 'desc' ? 'DESC' : 'ASC')
  362. ->addOrderBy('id', $sortDirection === 'desc' ? 'DESC' : 'ASC');
  363. if ($limit > 0) {
  364. $query->setMaxResults($limit);
  365. }
  366. $lastKnownComment = $lastKnownCommentId > 0 ? $this->getLastKnownComment(
  367. $objectType,
  368. $objectId,
  369. $lastKnownCommentId
  370. ) : null;
  371. if ($lastKnownComment instanceof IComment) {
  372. $lastKnownCommentDateTime = $lastKnownComment->getCreationDateTime();
  373. if ($sortDirection === 'desc') {
  374. $query->andWhere(
  375. $query->expr()->orX(
  376. $query->expr()->lt(
  377. 'creation_timestamp',
  378. $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
  379. IQueryBuilder::PARAM_DATE
  380. ),
  381. $query->expr()->andX(
  382. $query->expr()->eq(
  383. 'creation_timestamp',
  384. $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
  385. IQueryBuilder::PARAM_DATE
  386. ),
  387. $query->expr()->lt('id', $query->createNamedParameter($lastKnownCommentId))
  388. )
  389. )
  390. );
  391. } else {
  392. $query->andWhere(
  393. $query->expr()->orX(
  394. $query->expr()->gt(
  395. 'creation_timestamp',
  396. $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
  397. IQueryBuilder::PARAM_DATE
  398. ),
  399. $query->expr()->andX(
  400. $query->expr()->eq(
  401. 'creation_timestamp',
  402. $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
  403. IQueryBuilder::PARAM_DATE
  404. ),
  405. $query->expr()->gt('id', $query->createNamedParameter($lastKnownCommentId))
  406. )
  407. )
  408. );
  409. }
  410. }
  411. $resultStatement = $query->execute();
  412. while ($data = $resultStatement->fetch()) {
  413. $comment = new Comment($this->normalizeDatabaseData($data));
  414. $this->cache($comment);
  415. $comments[] = $comment;
  416. }
  417. $resultStatement->closeCursor();
  418. return $comments;
  419. }
  420. /**
  421. * @param string $objectType the object type, e.g. 'files'
  422. * @param string $objectId the id of the object
  423. * @param int $id the comment to look for
  424. * @return Comment|null
  425. */
  426. protected function getLastKnownComment(string $objectType,
  427. string $objectId,
  428. int $id) {
  429. $query = $this->dbConn->getQueryBuilder();
  430. $query->select('*')
  431. ->from('comments')
  432. ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
  433. ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
  434. ->andWhere($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
  435. $result = $query->execute();
  436. $row = $result->fetch();
  437. $result->closeCursor();
  438. if ($row) {
  439. $comment = new Comment($this->normalizeDatabaseData($row));
  440. $this->cache($comment);
  441. return $comment;
  442. }
  443. return null;
  444. }
  445. /**
  446. * @param $objectType string the object type, e.g. 'files'
  447. * @param $objectId string the id of the object
  448. * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
  449. * that may be returned
  450. * @return Int
  451. * @since 9.0.0
  452. */
  453. public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null) {
  454. $qb = $this->dbConn->getQueryBuilder();
  455. $query = $qb->select($qb->createFunction('COUNT(`id`)'))
  456. ->from('comments')
  457. ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
  458. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
  459. ->setParameter('type', $objectType)
  460. ->setParameter('id', $objectId);
  461. if (!is_null($notOlderThan)) {
  462. $query
  463. ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
  464. ->setParameter('notOlderThan', $notOlderThan, 'datetime');
  465. }
  466. $resultStatement = $query->execute();
  467. $data = $resultStatement->fetch(\PDO::FETCH_NUM);
  468. $resultStatement->closeCursor();
  469. return (int)$data[0];
  470. }
  471. /**
  472. * Get the number of unread comments for all files in a folder
  473. *
  474. * @param int $folderId
  475. * @param IUser $user
  476. * @return array [$fileId => $unreadCount]
  477. */
  478. public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
  479. $qb = $this->dbConn->getQueryBuilder();
  480. $query = $qb->select('f.fileid')
  481. ->selectAlias(
  482. $qb->createFunction('COUNT(' . $qb->getColumnName('c.id') . ')'),
  483. 'num_ids'
  484. )
  485. ->from('comments', 'c')
  486. ->innerJoin('c', 'filecache', 'f', $qb->expr()->andX(
  487. $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
  488. $qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT))
  489. ))
  490. ->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX(
  491. $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')),
  492. $qb->expr()->eq('m.object_id', 'c.object_id'),
  493. $qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID()))
  494. ))
  495. ->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId)))
  496. ->andWhere($qb->expr()->orX(
  497. $qb->expr()->gt('c.creation_timestamp', 'marker_datetime'),
  498. $qb->expr()->isNull('marker_datetime')
  499. ))
  500. ->groupBy('f.fileid');
  501. $resultStatement = $query->execute();
  502. $results = [];
  503. while ($row = $resultStatement->fetch()) {
  504. $results[$row['fileid']] = (int) $row['num_ids'];
  505. }
  506. $resultStatement->closeCursor();
  507. return $results;
  508. }
  509. /**
  510. * creates a new comment and returns it. At this point of time, it is not
  511. * saved in the used data storage. Use save() after setting other fields
  512. * of the comment (e.g. message or verb).
  513. *
  514. * @param string $actorType the actor type (e.g. 'users')
  515. * @param string $actorId a user id
  516. * @param string $objectType the object type the comment is attached to
  517. * @param string $objectId the object id the comment is attached to
  518. * @return IComment
  519. * @since 9.0.0
  520. */
  521. public function create($actorType, $actorId, $objectType, $objectId) {
  522. $comment = new Comment();
  523. $comment
  524. ->setActor($actorType, $actorId)
  525. ->setObject($objectType, $objectId);
  526. return $comment;
  527. }
  528. /**
  529. * permanently deletes the comment specified by the ID
  530. *
  531. * When the comment has child comments, their parent ID will be changed to
  532. * the parent ID of the item that is to be deleted.
  533. *
  534. * @param string $id
  535. * @return bool
  536. * @throws \InvalidArgumentException
  537. * @since 9.0.0
  538. */
  539. public function delete($id) {
  540. if (!is_string($id)) {
  541. throw new \InvalidArgumentException('Parameter must be string');
  542. }
  543. try {
  544. $comment = $this->get($id);
  545. } catch (\Exception $e) {
  546. // Ignore exceptions, we just don't fire a hook then
  547. $comment = null;
  548. }
  549. $qb = $this->dbConn->getQueryBuilder();
  550. $query = $qb->delete('comments')
  551. ->where($qb->expr()->eq('id', $qb->createParameter('id')))
  552. ->setParameter('id', $id);
  553. try {
  554. $affectedRows = $query->execute();
  555. $this->uncache($id);
  556. } catch (DriverException $e) {
  557. $this->logger->logException($e, ['app' => 'core_comments']);
  558. return false;
  559. }
  560. if ($affectedRows > 0 && $comment instanceof IComment) {
  561. $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
  562. }
  563. return ($affectedRows > 0);
  564. }
  565. /**
  566. * saves the comment permanently
  567. *
  568. * if the supplied comment has an empty ID, a new entry comment will be
  569. * saved and the instance updated with the new ID.
  570. *
  571. * Otherwise, an existing comment will be updated.
  572. *
  573. * Throws NotFoundException when a comment that is to be updated does not
  574. * exist anymore at this point of time.
  575. *
  576. * @param IComment $comment
  577. * @return bool
  578. * @throws NotFoundException
  579. * @since 9.0.0
  580. */
  581. public function save(IComment $comment) {
  582. if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
  583. $result = $this->insert($comment);
  584. } else {
  585. $result = $this->update($comment);
  586. }
  587. if ($result && !!$comment->getParentId()) {
  588. $this->updateChildrenInformation(
  589. $comment->getParentId(),
  590. $comment->getCreationDateTime()
  591. );
  592. $this->cache($comment);
  593. }
  594. return $result;
  595. }
  596. /**
  597. * inserts the provided comment in the database
  598. *
  599. * @param IComment $comment
  600. * @return bool
  601. */
  602. protected function insert(IComment &$comment) {
  603. $qb = $this->dbConn->getQueryBuilder();
  604. $affectedRows = $qb
  605. ->insert('comments')
  606. ->values([
  607. 'parent_id' => $qb->createNamedParameter($comment->getParentId()),
  608. 'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
  609. 'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
  610. 'actor_type' => $qb->createNamedParameter($comment->getActorType()),
  611. 'actor_id' => $qb->createNamedParameter($comment->getActorId()),
  612. 'message' => $qb->createNamedParameter($comment->getMessage()),
  613. 'verb' => $qb->createNamedParameter($comment->getVerb()),
  614. 'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
  615. 'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
  616. 'object_type' => $qb->createNamedParameter($comment->getObjectType()),
  617. 'object_id' => $qb->createNamedParameter($comment->getObjectId()),
  618. ])
  619. ->execute();
  620. if ($affectedRows > 0) {
  621. $comment->setId((string)$qb->getLastInsertId());
  622. $this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
  623. }
  624. return $affectedRows > 0;
  625. }
  626. /**
  627. * updates a Comment data row
  628. *
  629. * @param IComment $comment
  630. * @return bool
  631. * @throws NotFoundException
  632. */
  633. protected function update(IComment $comment) {
  634. // for properly working preUpdate Events we need the old comments as is
  635. // in the DB and overcome caching. Also avoid that outdated information stays.
  636. $this->uncache($comment->getId());
  637. $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
  638. $this->uncache($comment->getId());
  639. $qb = $this->dbConn->getQueryBuilder();
  640. $affectedRows = $qb
  641. ->update('comments')
  642. ->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
  643. ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
  644. ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
  645. ->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
  646. ->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
  647. ->set('message', $qb->createNamedParameter($comment->getMessage()))
  648. ->set('verb', $qb->createNamedParameter($comment->getVerb()))
  649. ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
  650. ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
  651. ->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
  652. ->set('object_id', $qb->createNamedParameter($comment->getObjectId()))
  653. ->where($qb->expr()->eq('id', $qb->createParameter('id')))
  654. ->setParameter('id', $comment->getId())
  655. ->execute();
  656. if ($affectedRows === 0) {
  657. throw new NotFoundException('Comment to update does ceased to exist');
  658. }
  659. $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
  660. return $affectedRows > 0;
  661. }
  662. /**
  663. * removes references to specific actor (e.g. on user delete) of a comment.
  664. * The comment itself must not get lost/deleted.
  665. *
  666. * @param string $actorType the actor type (e.g. 'users')
  667. * @param string $actorId a user id
  668. * @return boolean
  669. * @since 9.0.0
  670. */
  671. public function deleteReferencesOfActor($actorType, $actorId) {
  672. $this->checkRoleParameters('Actor', $actorType, $actorId);
  673. $qb = $this->dbConn->getQueryBuilder();
  674. $affectedRows = $qb
  675. ->update('comments')
  676. ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
  677. ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
  678. ->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
  679. ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
  680. ->setParameter('type', $actorType)
  681. ->setParameter('id', $actorId)
  682. ->execute();
  683. $this->commentsCache = [];
  684. return is_int($affectedRows);
  685. }
  686. /**
  687. * deletes all comments made of a specific object (e.g. on file delete)
  688. *
  689. * @param string $objectType the object type (e.g. 'files')
  690. * @param string $objectId e.g. the file id
  691. * @return boolean
  692. * @since 9.0.0
  693. */
  694. public function deleteCommentsAtObject($objectType, $objectId) {
  695. $this->checkRoleParameters('Object', $objectType, $objectId);
  696. $qb = $this->dbConn->getQueryBuilder();
  697. $affectedRows = $qb
  698. ->delete('comments')
  699. ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
  700. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
  701. ->setParameter('type', $objectType)
  702. ->setParameter('id', $objectId)
  703. ->execute();
  704. $this->commentsCache = [];
  705. return is_int($affectedRows);
  706. }
  707. /**
  708. * deletes the read markers for the specified user
  709. *
  710. * @param \OCP\IUser $user
  711. * @return bool
  712. * @since 9.0.0
  713. */
  714. public function deleteReadMarksFromUser(IUser $user) {
  715. $qb = $this->dbConn->getQueryBuilder();
  716. $query = $qb->delete('comments_read_markers')
  717. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  718. ->setParameter('user_id', $user->getUID());
  719. try {
  720. $affectedRows = $query->execute();
  721. } catch (DriverException $e) {
  722. $this->logger->logException($e, ['app' => 'core_comments']);
  723. return false;
  724. }
  725. return ($affectedRows > 0);
  726. }
  727. /**
  728. * sets the read marker for a given file to the specified date for the
  729. * provided user
  730. *
  731. * @param string $objectType
  732. * @param string $objectId
  733. * @param \DateTime $dateTime
  734. * @param IUser $user
  735. * @since 9.0.0
  736. * @suppress SqlInjectionChecker
  737. */
  738. public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
  739. $this->checkRoleParameters('Object', $objectType, $objectId);
  740. $qb = $this->dbConn->getQueryBuilder();
  741. $values = [
  742. 'user_id' => $qb->createNamedParameter($user->getUID()),
  743. 'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
  744. 'object_type' => $qb->createNamedParameter($objectType),
  745. 'object_id' => $qb->createNamedParameter($objectId),
  746. ];
  747. // Strategy: try to update, if this does not return affected rows, do an insert.
  748. $affectedRows = $qb
  749. ->update('comments_read_markers')
  750. ->set('user_id', $values['user_id'])
  751. ->set('marker_datetime', $values['marker_datetime'])
  752. ->set('object_type', $values['object_type'])
  753. ->set('object_id', $values['object_id'])
  754. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  755. ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  756. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  757. ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
  758. ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
  759. ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
  760. ->execute();
  761. if ($affectedRows > 0) {
  762. return;
  763. }
  764. $qb->insert('comments_read_markers')
  765. ->values($values)
  766. ->execute();
  767. }
  768. /**
  769. * returns the read marker for a given file to the specified date for the
  770. * provided user. It returns null, when the marker is not present, i.e.
  771. * no comments were marked as read.
  772. *
  773. * @param string $objectType
  774. * @param string $objectId
  775. * @param IUser $user
  776. * @return \DateTime|null
  777. * @since 9.0.0
  778. */
  779. public function getReadMark($objectType, $objectId, IUser $user) {
  780. $qb = $this->dbConn->getQueryBuilder();
  781. $resultStatement = $qb->select('marker_datetime')
  782. ->from('comments_read_markers')
  783. ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
  784. ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  785. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  786. ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
  787. ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
  788. ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
  789. ->execute();
  790. $data = $resultStatement->fetch();
  791. $resultStatement->closeCursor();
  792. if (!$data || is_null($data['marker_datetime'])) {
  793. return null;
  794. }
  795. return new \DateTime($data['marker_datetime']);
  796. }
  797. /**
  798. * deletes the read markers on the specified object
  799. *
  800. * @param string $objectType
  801. * @param string $objectId
  802. * @return bool
  803. * @since 9.0.0
  804. */
  805. public function deleteReadMarksOnObject($objectType, $objectId) {
  806. $this->checkRoleParameters('Object', $objectType, $objectId);
  807. $qb = $this->dbConn->getQueryBuilder();
  808. $query = $qb->delete('comments_read_markers')
  809. ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
  810. ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
  811. ->setParameter('object_type', $objectType)
  812. ->setParameter('object_id', $objectId);
  813. try {
  814. $affectedRows = $query->execute();
  815. } catch (DriverException $e) {
  816. $this->logger->logException($e, ['app' => 'core_comments']);
  817. return false;
  818. }
  819. return ($affectedRows > 0);
  820. }
  821. /**
  822. * registers an Entity to the manager, so event notifications can be send
  823. * to consumers of the comments infrastructure
  824. *
  825. * @param \Closure $closure
  826. */
  827. public function registerEventHandler(\Closure $closure) {
  828. $this->eventHandlerClosures[] = $closure;
  829. $this->eventHandlers = [];
  830. }
  831. /**
  832. * registers a method that resolves an ID to a display name for a given type
  833. *
  834. * @param string $type
  835. * @param \Closure $closure
  836. * @throws \OutOfBoundsException
  837. * @since 11.0.0
  838. *
  839. * Only one resolver shall be registered per type. Otherwise a
  840. * \OutOfBoundsException has to thrown.
  841. */
  842. public function registerDisplayNameResolver($type, \Closure $closure) {
  843. if (!is_string($type)) {
  844. throw new \InvalidArgumentException('String expected.');
  845. }
  846. if (isset($this->displayNameResolvers[$type])) {
  847. throw new \OutOfBoundsException('Displayname resolver for this type already registered');
  848. }
  849. $this->displayNameResolvers[$type] = $closure;
  850. }
  851. /**
  852. * resolves a given ID of a given Type to a display name.
  853. *
  854. * @param string $type
  855. * @param string $id
  856. * @return string
  857. * @throws \OutOfBoundsException
  858. * @since 11.0.0
  859. *
  860. * If a provided type was not registered, an \OutOfBoundsException shall
  861. * be thrown. It is upon the resolver discretion what to return of the
  862. * provided ID is unknown. It must be ensured that a string is returned.
  863. */
  864. public function resolveDisplayName($type, $id) {
  865. if (!is_string($type)) {
  866. throw new \InvalidArgumentException('String expected.');
  867. }
  868. if (!isset($this->displayNameResolvers[$type])) {
  869. throw new \OutOfBoundsException('No Displayname resolver for this type registered');
  870. }
  871. return (string)$this->displayNameResolvers[$type]($id);
  872. }
  873. /**
  874. * returns valid, registered entities
  875. *
  876. * @return \OCP\Comments\ICommentsEventHandler[]
  877. */
  878. private function getEventHandlers() {
  879. if (!empty($this->eventHandlers)) {
  880. return $this->eventHandlers;
  881. }
  882. $this->eventHandlers = [];
  883. foreach ($this->eventHandlerClosures as $name => $closure) {
  884. $entity = $closure();
  885. if (!($entity instanceof ICommentsEventHandler)) {
  886. throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
  887. }
  888. $this->eventHandlers[$name] = $entity;
  889. }
  890. return $this->eventHandlers;
  891. }
  892. /**
  893. * sends notifications to the registered entities
  894. *
  895. * @param $eventType
  896. * @param IComment $comment
  897. */
  898. private function sendEvent($eventType, IComment $comment) {
  899. $entities = $this->getEventHandlers();
  900. $event = new CommentsEvent($eventType, $comment);
  901. foreach ($entities as $entity) {
  902. $entity->handle($event);
  903. }
  904. }
  905. }