123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677 |
- <?php
- /**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
- * @author Joas Schilling <coding@schilljs.com>
- * @author John Molakvoæ <skjnldsv@protonmail.com>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Simounet <contact@simounet.net>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
- */
- namespace OC\Comments;
- use Doctrine\DBAL\Exception\DriverException;
- use Doctrine\DBAL\Exception\InvalidFieldNameException;
- use OCP\AppFramework\Utility\ITimeFactory;
- use OCP\Comments\CommentsEvent;
- use OCP\Comments\IComment;
- use OCP\Comments\ICommentsEventHandler;
- use OCP\Comments\ICommentsManager;
- use OCP\Comments\NotFoundException;
- use OCP\DB\QueryBuilder\IQueryBuilder;
- use OCP\IConfig;
- use OCP\IDBConnection;
- use OCP\IEmojiHelper;
- use OCP\IUser;
- use OCP\IInitialStateService;
- use OCP\PreConditionNotMetException;
- use OCP\Util;
- use Psr\Log\LoggerInterface;
- class Manager implements ICommentsManager {
- /** @var IDBConnection */
- protected $dbConn;
- /** @var LoggerInterface */
- protected $logger;
- /** @var IConfig */
- protected $config;
- /** @var ITimeFactory */
- protected $timeFactory;
- /** @var IEmojiHelper */
- protected $emojiHelper;
- /** @var IInitialStateService */
- protected $initialStateService;
- /** @var IComment[] */
- protected $commentsCache = [];
- /** @var \Closure[] */
- protected $eventHandlerClosures = [];
- /** @var ICommentsEventHandler[] */
- protected $eventHandlers = [];
- /** @var \Closure[] */
- protected $displayNameResolvers = [];
- public function __construct(IDBConnection $dbConn,
- LoggerInterface $logger,
- IConfig $config,
- ITimeFactory $timeFactory,
- IEmojiHelper $emojiHelper,
- IInitialStateService $initialStateService) {
- $this->dbConn = $dbConn;
- $this->logger = $logger;
- $this->config = $config;
- $this->timeFactory = $timeFactory;
- $this->emojiHelper = $emojiHelper;
- $this->initialStateService = $initialStateService;
- }
- /**
- * converts data base data into PHP native, proper types as defined by
- * IComment interface.
- *
- * @param array $data
- * @return array
- */
- protected function normalizeDatabaseData(array $data) {
- $data['id'] = (string)$data['id'];
- $data['parent_id'] = (string)$data['parent_id'];
- $data['topmost_parent_id'] = (string)$data['topmost_parent_id'];
- $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
- if (!is_null($data['latest_child_timestamp'])) {
- $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
- }
- if (!is_null($data['expire_date'])) {
- $data['expire_date'] = new \DateTime($data['expire_date']);
- }
- $data['children_count'] = (int)$data['children_count'];
- $data['reference_id'] = $data['reference_id'] ?? null;
- if ($this->supportReactions()) {
- if ($data['reactions'] !== null) {
- $list = json_decode($data['reactions'], true);
- // Ordering does not work on the database with group concat and Oracle,
- // So we simply sort on the output.
- if (is_array($list)) {
- uasort($list, static function ($a, $b) {
- if ($a === $b) {
- return 0;
- }
- return ($a > $b) ? -1 : 1;
- });
- $data['reactions'] = $list;
- } else {
- $data['reactions'] = [];
- }
- } else {
- $data['reactions'] = [];
- }
- }
- return $data;
- }
- /**
- * @param array $data
- * @return IComment
- */
- public function getCommentFromData(array $data): IComment {
- return new Comment($this->normalizeDatabaseData($data));
- }
- /**
- * prepares a comment for an insert or update operation after making sure
- * all necessary fields have a value assigned.
- *
- * @param IComment $comment
- * @return IComment returns the same updated IComment instance as provided
- * by parameter for convenience
- * @throws \UnexpectedValueException
- */
- protected function prepareCommentForDatabaseWrite(IComment $comment) {
- if (!$comment->getActorType()
- || $comment->getActorId() === ''
- || !$comment->getObjectType()
- || $comment->getObjectId() === ''
- || !$comment->getVerb()
- ) {
- throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
- }
- if ($comment->getVerb() === 'reaction' && !$this->emojiHelper->isValidSingleEmoji($comment->getMessage())) {
- // 4 characters: laptop + person + gender + skin color => "🧑🏽💻" is a single emoji from the picker
- throw new \UnexpectedValueException('Reactions can only be a single emoji');
- }
- if ($comment->getId() === '') {
- $comment->setChildrenCount(0);
- $comment->setLatestChildDateTime(null);
- }
- if (is_null($comment->getCreationDateTime())) {
- $comment->setCreationDateTime(new \DateTime());
- }
- if ($comment->getParentId() !== '0') {
- $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
- } else {
- $comment->setTopmostParentId('0');
- }
- $this->cache($comment);
- return $comment;
- }
- /**
- * returns the topmost parent id of a given comment identified by ID
- *
- * @param string $id
- * @return string
- * @throws NotFoundException
- */
- protected function determineTopmostParentId($id) {
- $comment = $this->get($id);
- if ($comment->getParentId() === '0') {
- return $comment->getId();
- }
- return $this->determineTopmostParentId($comment->getParentId());
- }
- /**
- * updates child information of a comment
- *
- * @param string $id
- * @param \DateTime $cDateTime the date time of the most recent child
- * @throws NotFoundException
- */
- protected function updateChildrenInformation($id, \DateTime $cDateTime) {
- $qb = $this->dbConn->getQueryBuilder();
- $query = $qb->select($qb->func()->count('id'))
- ->from('comments')
- ->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
- ->setParameter('id', $id);
- $resultStatement = $query->execute();
- $data = $resultStatement->fetch(\PDO::FETCH_NUM);
- $resultStatement->closeCursor();
- $children = (int)$data[0];
- $comment = $this->get($id);
- $comment->setChildrenCount($children);
- $comment->setLatestChildDateTime($cDateTime);
- $this->save($comment);
- }
- /**
- * Tests whether actor or object type and id parameters are acceptable.
- * Throws exception if not.
- *
- * @param string $role
- * @param string $type
- * @param string $id
- * @throws \InvalidArgumentException
- */
- protected function checkRoleParameters($role, $type, $id) {
- if (
- !is_string($type) || empty($type)
- || !is_string($id) || empty($id)
- ) {
- throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
- }
- }
- /**
- * run-time caches a comment
- *
- * @param IComment $comment
- */
- protected function cache(IComment $comment) {
- $id = $comment->getId();
- if (empty($id)) {
- return;
- }
- $this->commentsCache[(string)$id] = $comment;
- }
- /**
- * removes an entry from the comments run time cache
- *
- * @param mixed $id the comment's id
- */
- protected function uncache($id) {
- $id = (string)$id;
- if (isset($this->commentsCache[$id])) {
- unset($this->commentsCache[$id]);
- }
- }
- /**
- * returns a comment instance
- *
- * @param string $id the ID of the comment
- * @return IComment
- * @throws NotFoundException
- * @throws \InvalidArgumentException
- * @since 9.0.0
- */
- public function get($id) {
- if ((int)$id === 0) {
- throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
- }
- if (isset($this->commentsCache[$id])) {
- return $this->commentsCache[$id];
- }
- $qb = $this->dbConn->getQueryBuilder();
- $resultStatement = $qb->select('*')
- ->from('comments')
- ->where($qb->expr()->eq('id', $qb->createParameter('id')))
- ->setParameter('id', $id, IQueryBuilder::PARAM_INT)
- ->execute();
- $data = $resultStatement->fetch();
- $resultStatement->closeCursor();
- if (!$data) {
- throw new NotFoundException();
- }
- $comment = $this->getCommentFromData($data);
- $this->cache($comment);
- return $comment;
- }
- /**
- * returns the comment specified by the id and all it's child comments.
- * At this point of time, we do only support one level depth.
- *
- * @param string $id
- * @param int $limit max number of entries to return, 0 returns all
- * @param int $offset the start entry
- * @return array
- * @since 9.0.0
- *
- * The return array looks like this
- * [
- * 'comment' => IComment, // root comment
- * 'replies' =>
- * [
- * 0 =>
- * [
- * 'comment' => IComment,
- * 'replies' => []
- * ]
- * 1 =>
- * [
- * 'comment' => IComment,
- * 'replies'=> []
- * ],
- * …
- * ]
- * ]
- */
- public function getTree($id, $limit = 0, $offset = 0) {
- $tree = [];
- $tree['comment'] = $this->get($id);
- $tree['replies'] = [];
- $qb = $this->dbConn->getQueryBuilder();
- $query = $qb->select('*')
- ->from('comments')
- ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
- ->orderBy('creation_timestamp', 'DESC')
- ->setParameter('id', $id);
- if ($limit > 0) {
- $query->setMaxResults($limit);
- }
- if ($offset > 0) {
- $query->setFirstResult($offset);
- }
- $resultStatement = $query->execute();
- while ($data = $resultStatement->fetch()) {
- $comment = $this->getCommentFromData($data);
- $this->cache($comment);
- $tree['replies'][] = [
- 'comment' => $comment,
- 'replies' => []
- ];
- }
- $resultStatement->closeCursor();
- return $tree;
- }
- /**
- * returns comments for a specific object (e.g. a file).
- *
- * The sort order is always newest to oldest.
- *
- * @param string $objectType the object type, e.g. 'files'
- * @param string $objectId the id of the object
- * @param int $limit optional, number of maximum comments to be returned. if
- * not specified, all comments are returned.
- * @param int $offset optional, starting point
- * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
- * that may be returned
- * @return IComment[]
- * @since 9.0.0
- */
- public function getForObject(
- $objectType,
- $objectId,
- $limit = 0,
- $offset = 0,
- \DateTime $notOlderThan = null
- ) {
- $comments = [];
- $qb = $this->dbConn->getQueryBuilder();
- $query = $qb->select('*')
- ->from('comments')
- ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
- ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
- ->orderBy('creation_timestamp', 'DESC')
- ->setParameter('type', $objectType)
- ->setParameter('id', $objectId);
- if ($limit > 0) {
- $query->setMaxResults($limit);
- }
- if ($offset > 0) {
- $query->setFirstResult($offset);
- }
- if (!is_null($notOlderThan)) {
- $query
- ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
- ->setParameter('notOlderThan', $notOlderThan, 'datetime');
- }
- $resultStatement = $query->execute();
- while ($data = $resultStatement->fetch()) {
- $comment = $this->getCommentFromData($data);
- $this->cache($comment);
- $comments[] = $comment;
- }
- $resultStatement->closeCursor();
- return $comments;
- }
- /**
- * @param string $objectType the object type, e.g. 'files'
- * @param string $objectId the id of the object
- * @param int $lastKnownCommentId the last known comment (will be used as offset)
- * @param string $sortDirection direction of the comments (`asc` or `desc`)
- * @param int $limit optional, number of maximum comments to be returned. if
- * set to 0, all comments are returned.
- * @param bool $includeLastKnown
- * @return IComment[]
- * @return array
- */
- public function getForObjectSince(
- string $objectType,
- string $objectId,
- int $lastKnownCommentId,
- string $sortDirection = 'asc',
- int $limit = 30,
- bool $includeLastKnown = false
- ): array {
- return $this->getCommentsWithVerbForObjectSinceComment(
- $objectType,
- $objectId,
- [],
- $lastKnownCommentId,
- $sortDirection,
- $limit,
- $includeLastKnown
- );
- }
- /**
- * @param string $objectType the object type, e.g. 'files'
- * @param string $objectId the id of the object
- * @param string[] $verbs List of verbs to filter by
- * @param int $lastKnownCommentId the last known comment (will be used as offset)
- * @param string $sortDirection direction of the comments (`asc` or `desc`)
- * @param int $limit optional, number of maximum comments to be returned. if
- * set to 0, all comments are returned.
- * @param bool $includeLastKnown
- * @return IComment[]
- */
- public function getCommentsWithVerbForObjectSinceComment(
- string $objectType,
- string $objectId,
- array $verbs,
- int $lastKnownCommentId,
- string $sortDirection = 'asc',
- int $limit = 30,
- bool $includeLastKnown = false
- ): array {
- $comments = [];
- $query = $this->dbConn->getQueryBuilder();
- $query->select('*')
- ->from('comments')
- ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
- ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
- ->orderBy('creation_timestamp', $sortDirection === 'desc' ? 'DESC' : 'ASC')
- ->addOrderBy('id', $sortDirection === 'desc' ? 'DESC' : 'ASC');
- if ($limit > 0) {
- $query->setMaxResults($limit);
- }
- if (!empty($verbs)) {
- $query->andWhere($query->expr()->in('verb', $query->createNamedParameter($verbs, IQueryBuilder::PARAM_STR_ARRAY)));
- }
- $lastKnownComment = $lastKnownCommentId > 0 ? $this->getLastKnownComment(
- $objectType,
- $objectId,
- $lastKnownCommentId
- ) : null;
- if ($lastKnownComment instanceof IComment) {
- $lastKnownCommentDateTime = $lastKnownComment->getCreationDateTime();
- if ($sortDirection === 'desc') {
- if ($includeLastKnown) {
- $idComparison = $query->expr()->lte('id', $query->createNamedParameter($lastKnownCommentId));
- } else {
- $idComparison = $query->expr()->lt('id', $query->createNamedParameter($lastKnownCommentId));
- }
- $query->andWhere(
- $query->expr()->orX(
- $query->expr()->lt(
- 'creation_timestamp',
- $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
- IQueryBuilder::PARAM_DATE
- ),
- $query->expr()->andX(
- $query->expr()->eq(
- 'creation_timestamp',
- $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
- IQueryBuilder::PARAM_DATE
- ),
- $idComparison
- )
- )
- );
- } else {
- if ($includeLastKnown) {
- $idComparison = $query->expr()->gte('id', $query->createNamedParameter($lastKnownCommentId));
- } else {
- $idComparison = $query->expr()->gt('id', $query->createNamedParameter($lastKnownCommentId));
- }
- $query->andWhere(
- $query->expr()->orX(
- $query->expr()->gt(
- 'creation_timestamp',
- $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
- IQueryBuilder::PARAM_DATE
- ),
- $query->expr()->andX(
- $query->expr()->eq(
- 'creation_timestamp',
- $query->createNamedParameter($lastKnownCommentDateTime, IQueryBuilder::PARAM_DATE),
- IQueryBuilder::PARAM_DATE
- ),
- $idComparison
- )
- )
- );
- }
- }
- $resultStatement = $query->execute();
- while ($data = $resultStatement->fetch()) {
- $comment = $this->getCommentFromData($data);
- $this->cache($comment);
- $comments[] = $comment;
- }
- $resultStatement->closeCursor();
- return $comments;
- }
- /**
- * @param string $objectType the object type, e.g. 'files'
- * @param string $objectId the id of the object
- * @param int $id the comment to look for
- * @return Comment|null
- */
- protected function getLastKnownComment(string $objectType,
- string $objectId,
- int $id) {
- $query = $this->dbConn->getQueryBuilder();
- $query->select('*')
- ->from('comments')
- ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
- ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
- ->andWhere($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
- $result = $query->execute();
- $row = $result->fetch();
- $result->closeCursor();
- if ($row) {
- $comment = $this->getCommentFromData($row);
- $this->cache($comment);
- return $comment;
- }
- return null;
- }
- /**
- * Search for comments with a given content
- *
- * @param string $search content to search for
- * @param string $objectType Limit the search by object type
- * @param string $objectId Limit the search by object id
- * @param string $verb Limit the verb of the comment
- * @param int $offset
- * @param int $limit
- * @return IComment[]
- */
- public function search(string $search, string $objectType, string $objectId, string $verb, int $offset, int $limit = 50): array {
- $objectIds = [];
- if ($objectId) {
- $objectIds[] = $objectId;
- }
- return $this->searchForObjects($search, $objectType, $objectIds, $verb, $offset, $limit);
- }
- /**
- * Search for comments on one or more objects with a given content
- *
- * @param string $search content to search for
- * @param string $objectType Limit the search by object type
- * @param array $objectIds Limit the search by object ids
- * @param string $verb Limit the verb of the comment
- * @param int $offset
- * @param int $limit
- * @return IComment[]
- */
- public function searchForObjects(string $search, string $objectType, array $objectIds, string $verb, int $offset, int $limit = 50): array {
- $query = $this->dbConn->getQueryBuilder();
- $query->select('*')
- ->from('comments')
- ->orderBy('creation_timestamp', 'DESC')
- ->addOrderBy('id', 'DESC')
- ->setMaxResults($limit);
- if ($search !== '') {
- $query->where($query->expr()->iLike('message', $query->createNamedParameter(
- '%' . $this->dbConn->escapeLikeParameter($search). '%'
- )));
- }
- if ($objectType !== '') {
- $query->andWhere($query->expr()->eq('object_type', $query->createNamedParameter($objectType)));
- }
- if (!empty($objectIds)) {
- $query->andWhere($query->expr()->in('object_id', $query->createNamedParameter($objectIds, IQueryBuilder::PARAM_STR_ARRAY)));
- }
- if ($verb !== '') {
- $query->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)));
- }
- if ($offset !== 0) {
- $query->setFirstResult($offset);
- }
- $comments = [];
- $result = $query->execute();
- while ($data = $result->fetch()) {
- $comment = $this->getCommentFromData($data);
- $this->cache($comment);
- $comments[] = $comment;
- }
- $result->closeCursor();
- return $comments;
- }
- /**
- * @param $objectType string the object type, e.g. 'files'
- * @param $objectId string the id of the object
- * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
- * that may be returned
- * @param string $verb Limit the verb of the comment - Added in 14.0.0
- * @return Int
- * @since 9.0.0
- */
- public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null, $verb = '') {
- $qb = $this->dbConn->getQueryBuilder();
- $query = $qb->select($qb->func()->count('id'))
- ->from('comments')
- ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
- ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
- ->setParameter('type', $objectType)
- ->setParameter('id', $objectId);
- if (!is_null($notOlderThan)) {
- $query
- ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
- ->setParameter('notOlderThan', $notOlderThan, 'datetime');
- }
- if ($verb !== '') {
- $query->andWhere($qb->expr()->eq('verb', $qb->createNamedParameter($verb)));
- }
- $resultStatement = $query->execute();
- $data = $resultStatement->fetch(\PDO::FETCH_NUM);
- $resultStatement->closeCursor();
- return (int)$data[0];
- }
- /**
- * @param string $objectType the object type, e.g. 'files'
- * @param string[] $objectIds the id of the object
- * @param IUser $user
- * @param string $verb Limit the verb of the comment - Added in 14.0.0
- * @return array Map with object id => # of unread comments
- * @psalm-return array<string, int>
- * @since 21.0.0
- */
- public function getNumberOfUnreadCommentsForObjects(string $objectType, array $objectIds, IUser $user, $verb = ''): array {
- $unreadComments = [];
- $query = $this->dbConn->getQueryBuilder();
- $query->select('c.object_id', $query->func()->count('c.id', 'num_comments'))
- ->from('comments', 'c')
- ->leftJoin('c', 'comments_read_markers', 'm', $query->expr()->andX(
- $query->expr()->eq('m.user_id', $query->createNamedParameter($user->getUID())),
- $query->expr()->eq('c.object_type', 'm.object_type'),
- $query->expr()->eq('c.object_id', 'm.object_id')
- ))
- ->where($query->expr()->eq('c.object_type', $query->createNamedParameter($objectType)))
- ->andWhere($query->expr()->in('c.object_id', $query->createParameter('ids')))
- ->andWhere($query->expr()->orX(
- $query->expr()->gt('c.creation_timestamp', 'm.marker_datetime'),
- $query->expr()->isNull('m.marker_datetime')
- ))
- ->groupBy('c.object_id');
- if ($verb !== '') {
- $query->andWhere($query->expr()->eq('c.verb', $query->createNamedParameter($verb)));
- }
- $unreadComments = array_fill_keys($objectIds, 0);
- foreach (array_chunk($objectIds, 1000) as $chunk) {
- $query->setParameter('ids', $chunk, IQueryBuilder::PARAM_STR_ARRAY);
- $result = $query->executeQuery();
- while ($row = $result->fetch()) {
- $unreadComments[$row['object_id']] = (int) $row['num_comments'];
- }
- $result->closeCursor();
- }
- return $unreadComments;
- }
- /**
- * @param string $objectType
- * @param string $objectId
- * @param int $lastRead
- * @param string $verb
- * @return int
- * @since 21.0.0
- */
- public function getNumberOfCommentsForObjectSinceComment(string $objectType, string $objectId, int $lastRead, string $verb = ''): int {
- if ($verb !== '') {
- return $this->getNumberOfCommentsWithVerbsForObjectSinceComment($objectType, $objectId, $lastRead, [$verb]);
- }
- return $this->getNumberOfCommentsWithVerbsForObjectSinceComment($objectType, $objectId, $lastRead, []);
- }
- /**
- * @param string $objectType
- * @param string $objectId
- * @param int $lastRead
- * @param string[] $verbs
- * @return int
- * @since 24.0.0
- */
- public function getNumberOfCommentsWithVerbsForObjectSinceComment(string $objectType, string $objectId, int $lastRead, array $verbs): int {
- $query = $this->dbConn->getQueryBuilder();
- $query->select($query->func()->count('id', 'num_messages'))
- ->from('comments')
- ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
- ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
- ->andWhere($query->expr()->gt('id', $query->createNamedParameter($lastRead)));
- if (!empty($verbs)) {
- $query->andWhere($query->expr()->in('verb', $query->createNamedParameter($verbs, IQueryBuilder::PARAM_STR_ARRAY)));
- }
- $result = $query->executeQuery();
- $data = $result->fetch();
- $result->closeCursor();
- return (int) ($data['num_messages'] ?? 0);
- }
- /**
- * @param string $objectType
- * @param string $objectId
- * @param \DateTime $beforeDate
- * @param string $verb
- * @return int
- * @since 21.0.0
- */
- public function getLastCommentBeforeDate(string $objectType, string $objectId, \DateTime $beforeDate, string $verb = ''): int {
- $query = $this->dbConn->getQueryBuilder();
- $query->select('id')
- ->from('comments')
- ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
- ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
- ->andWhere($query->expr()->lt('creation_timestamp', $query->createNamedParameter($beforeDate, IQueryBuilder::PARAM_DATE)))
- ->orderBy('creation_timestamp', 'desc');
- if ($verb !== '') {
- $query->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)));
- }
- $result = $query->execute();
- $data = $result->fetch();
- $result->closeCursor();
- return (int) ($data['id'] ?? 0);
- }
- /**
- * @param string $objectType
- * @param string $objectId
- * @param string $verb
- * @param string $actorType
- * @param string[] $actors
- * @return \DateTime[] Map of "string actor" => "\DateTime most recent comment date"
- * @psalm-return array<string, \DateTime>
- * @since 21.0.0
- */
- public function getLastCommentDateByActor(
- string $objectType,
- string $objectId,
- string $verb,
- string $actorType,
- array $actors
- ): array {
- $lastComments = [];
- $query = $this->dbConn->getQueryBuilder();
- $query->select('actor_id')
- ->selectAlias($query->createFunction('MAX(' . $query->getColumnName('creation_timestamp') . ')'), 'last_comment')
- ->from('comments')
- ->where($query->expr()->eq('object_type', $query->createNamedParameter($objectType)))
- ->andWhere($query->expr()->eq('object_id', $query->createNamedParameter($objectId)))
- ->andWhere($query->expr()->eq('verb', $query->createNamedParameter($verb)))
- ->andWhere($query->expr()->eq('actor_type', $query->createNamedParameter($actorType)))
- ->andWhere($query->expr()->in('actor_id', $query->createNamedParameter($actors, IQueryBuilder::PARAM_STR_ARRAY)))
- ->groupBy('actor_id');
- $result = $query->execute();
- while ($row = $result->fetch()) {
- $lastComments[$row['actor_id']] = $this->timeFactory->getDateTime($row['last_comment']);
- }
- $result->closeCursor();
- return $lastComments;
- }
- /**
- * Get the number of unread comments for all files in a folder
- *
- * @param int $folderId
- * @param IUser $user
- * @return array [$fileId => $unreadCount]
- */
- public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
- $qb = $this->dbConn->getQueryBuilder();
- $query = $qb->select('f.fileid')
- ->addSelect($qb->func()->count('c.id', 'num_ids'))
- ->from('filecache', 'f')
- ->leftJoin('f', 'comments', 'c', $qb->expr()->andX(
- $qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT)),
- $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files'))
- ))
- ->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX(
- $qb->expr()->eq('c.object_id', 'm.object_id'),
- $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files'))
- ))
- ->where(
- $qb->expr()->andX(
- $qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId)),
- $qb->expr()->orX(
- $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
- $qb->expr()->isNull('c.object_type')
- ),
- $qb->expr()->orX(
- $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')),
- $qb->expr()->isNull('m.object_type')
- ),
- $qb->expr()->orX(
- $qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID())),
- $qb->expr()->isNull('m.user_id')
- ),
- $qb->expr()->orX(
- $qb->expr()->gt('c.creation_timestamp', 'm.marker_datetime'),
- $qb->expr()->isNull('m.marker_datetime')
- )
- )
- )->groupBy('f.fileid');
- $resultStatement = $query->execute();
- $results = [];
- while ($row = $resultStatement->fetch()) {
- $results[$row['fileid']] = (int) $row['num_ids'];
- }
- $resultStatement->closeCursor();
- return $results;
- }
- /**
- * creates a new comment and returns it. At this point of time, it is not
- * saved in the used data storage. Use save() after setting other fields
- * of the comment (e.g. message or verb).
- *
- * @param string $actorType the actor type (e.g. 'users')
- * @param string $actorId a user id
- * @param string $objectType the object type the comment is attached to
- * @param string $objectId the object id the comment is attached to
- * @return IComment
- * @since 9.0.0
- */
- public function create($actorType, $actorId, $objectType, $objectId) {
- $comment = new Comment();
- $comment
- ->setActor($actorType, $actorId)
- ->setObject($objectType, $objectId);
- return $comment;
- }
- /**
- * permanently deletes the comment specified by the ID
- *
- * When the comment has child comments, their parent ID will be changed to
- * the parent ID of the item that is to be deleted.
- *
- * @param string $id
- * @return bool
- * @throws \InvalidArgumentException
- * @since 9.0.0
- */
- public function delete($id) {
- if (!is_string($id)) {
- throw new \InvalidArgumentException('Parameter must be string');
- }
- try {
- $comment = $this->get($id);
- } catch (\Exception $e) {
- // Ignore exceptions, we just don't fire a hook then
- $comment = null;
- }
- $qb = $this->dbConn->getQueryBuilder();
- $query = $qb->delete('comments')
- ->where($qb->expr()->eq('id', $qb->createParameter('id')))
- ->setParameter('id', $id);
- try {
- $affectedRows = $query->execute();
- $this->uncache($id);
- } catch (DriverException $e) {
- $this->logger->error($e->getMessage(), [
- 'exception' => $e,
- 'app' => 'core_comments',
- ]);
- return false;
- }
- if ($affectedRows > 0 && $comment instanceof IComment) {
- if ($comment->getVerb() === 'reaction_deleted') {
- $this->deleteReaction($comment);
- }
- $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
- }
- return ($affectedRows > 0);
- }
- private function deleteReaction(IComment $reaction): void {
- $qb = $this->dbConn->getQueryBuilder();
- $qb->delete('reactions')
- ->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($reaction->getParentId())))
- ->andWhere($qb->expr()->eq('message_id', $qb->createNamedParameter($reaction->getId())))
- ->executeStatement();
- $this->sumReactions($reaction->getParentId());
- }
- /**
- * Get comment related with user reaction
- *
- * Throws PreConditionNotMetException when the system haven't the minimum requirements to
- * use reactions
- *
- * @param int $parentId
- * @param string $actorType
- * @param string $actorId
- * @param string $reaction
- * @return IComment
- * @throws NotFoundException
- * @throws PreConditionNotMetException
- * @since 24.0.0
- */
- public function getReactionComment(int $parentId, string $actorType, string $actorId, string $reaction): IComment {
- $this->throwIfNotSupportReactions();
- $qb = $this->dbConn->getQueryBuilder();
- $messageId = $qb
- ->select('message_id')
- ->from('reactions')
- ->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($parentId)))
- ->andWhere($qb->expr()->eq('actor_type', $qb->createNamedParameter($actorType)))
- ->andWhere($qb->expr()->eq('actor_id', $qb->createNamedParameter($actorId)))
- ->andWhere($qb->expr()->eq('reaction', $qb->createNamedParameter($reaction)))
- ->executeQuery()
- ->fetchOne();
- if (!$messageId) {
- throw new NotFoundException('Comment related with reaction not found');
- }
- return $this->get($messageId);
- }
- /**
- * Retrieve all reactions of a message
- *
- * Throws PreConditionNotMetException when the system haven't the minimum requirements to
- * use reactions
- *
- * @param int $parentId
- * @return IComment[]
- * @throws PreConditionNotMetException
- * @since 24.0.0
- */
- public function retrieveAllReactions(int $parentId): array {
- $this->throwIfNotSupportReactions();
- $qb = $this->dbConn->getQueryBuilder();
- $result = $qb
- ->select('message_id')
- ->from('reactions')
- ->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($parentId)))
- ->orderBy('message_id', 'DESC')
- ->executeQuery();
- $commentIds = [];
- while ($data = $result->fetch()) {
- $commentIds[] = $data['message_id'];
- }
- return $this->getCommentsById($commentIds);
- }
- /**
- * Retrieve all reactions with specific reaction of a message
- *
- * Throws PreConditionNotMetException when the system haven't the minimum requirements to
- * use reactions
- *
- * @param int $parentId
- * @param string $reaction
- * @return IComment[]
- * @throws PreConditionNotMetException
- * @since 24.0.0
- */
- public function retrieveAllReactionsWithSpecificReaction(int $parentId, string $reaction): array {
- $this->throwIfNotSupportReactions();
- $qb = $this->dbConn->getQueryBuilder();
- $result = $qb
- ->select('message_id')
- ->from('reactions')
- ->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($parentId)))
- ->andWhere($qb->expr()->eq('reaction', $qb->createNamedParameter($reaction)))
- ->executeQuery();
- $commentIds = [];
- while ($data = $result->fetch()) {
- $commentIds[] = $data['message_id'];
- }
- $comments = [];
- if ($commentIds) {
- $comments = $this->getCommentsById($commentIds);
- }
- return $comments;
- }
- /**
- * Support reactions
- *
- * @return bool
- * @since 24.0.0
- */
- public function supportReactions(): bool {
- return $this->emojiHelper->doesPlatformSupportEmoji();
- }
- /**
- * @throws PreConditionNotMetException
- * @since 24.0.0
- */
- private function throwIfNotSupportReactions() {
- if (!$this->supportReactions()) {
- throw new PreConditionNotMetException('The database does not support reactions');
- }
- }
- /**
- * Get all comments on list
- *
- * @param int[] $commentIds
- * @return IComment[]
- * @since 24.0.0
- */
- private function getCommentsById(array $commentIds): array {
- if (!$commentIds) {
- return [];
- }
- $chunks = array_chunk($commentIds, 500);
- $query = $this->dbConn->getQueryBuilder();
- $query->select('*')
- ->from('comments')
- ->where($query->expr()->in('id', $query->createParameter('ids')))
- ->orderBy('creation_timestamp', 'DESC')
- ->addOrderBy('id', 'DESC');
- $comments = [];
- foreach ($chunks as $ids) {
- $query->setParameter('ids', $ids, IQueryBuilder::PARAM_STR_ARRAY);
- $result = $query->executeQuery();
- while ($data = $result->fetch()) {
- $comment = $this->getCommentFromData($data);
- $this->cache($comment);
- $comments[] = $comment;
- }
- $result->closeCursor();
- }
- return $comments;
- }
- /**
- * saves the comment permanently
- *
- * if the supplied comment has an empty ID, a new entry comment will be
- * saved and the instance updated with the new ID.
- *
- * Otherwise, an existing comment will be updated.
- *
- * Throws NotFoundException when a comment that is to be updated does not
- * exist anymore at this point of time.
- *
- * Throws PreConditionNotMetException when the system haven't the minimum requirements to
- * use reactions
- *
- * @param IComment $comment
- * @return bool
- * @throws NotFoundException
- * @throws PreConditionNotMetException
- * @since 9.0.0
- */
- public function save(IComment $comment) {
- if ($comment->getVerb() === 'reaction') {
- $this->throwIfNotSupportReactions();
- }
- if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
- $result = $this->insert($comment);
- } else {
- $result = $this->update($comment);
- }
- if ($result && !!$comment->getParentId()) {
- $this->updateChildrenInformation(
- $comment->getParentId(),
- $comment->getCreationDateTime()
- );
- $this->cache($comment);
- }
- return $result;
- }
- /**
- * inserts the provided comment in the database
- *
- * @param IComment $comment
- * @return bool
- */
- protected function insert(IComment $comment): bool {
- try {
- $result = $this->insertQuery($comment, true);
- } catch (InvalidFieldNameException $e) {
- // The reference id field was only added in Nextcloud 19.
- // In order to not cause too long waiting times on the update,
- // it was decided to only add it lazy, as it is also not a critical
- // feature, but only helps to have a better experience while commenting.
- // So in case the reference_id field is missing,
- // we simply save the comment without that field.
- $result = $this->insertQuery($comment, false);
- }
- return $result;
- }
- protected function insertQuery(IComment $comment, bool $tryWritingReferenceId): bool {
- $qb = $this->dbConn->getQueryBuilder();
- $values = [
- 'parent_id' => $qb->createNamedParameter($comment->getParentId()),
- 'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
- 'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
- 'actor_type' => $qb->createNamedParameter($comment->getActorType()),
- 'actor_id' => $qb->createNamedParameter($comment->getActorId()),
- 'message' => $qb->createNamedParameter($comment->getMessage()),
- 'verb' => $qb->createNamedParameter($comment->getVerb()),
- 'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
- 'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
- 'object_type' => $qb->createNamedParameter($comment->getObjectType()),
- 'object_id' => $qb->createNamedParameter($comment->getObjectId()),
- 'expire_date' => $qb->createNamedParameter($comment->getExpireDate(), 'datetime'),
- ];
- if ($tryWritingReferenceId) {
- $values['reference_id'] = $qb->createNamedParameter($comment->getReferenceId());
- }
- $affectedRows = $qb->insert('comments')
- ->values($values)
- ->execute();
- if ($affectedRows > 0) {
- $comment->setId((string)$qb->getLastInsertId());
- if ($comment->getVerb() === 'reaction') {
- $this->addReaction($comment);
- }
- $this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
- }
- return $affectedRows > 0;
- }
- private function addReaction(IComment $reaction): void {
- // Prevent violate constraint
- $qb = $this->dbConn->getQueryBuilder();
- $qb->select($qb->func()->count('*'))
- ->from('reactions')
- ->where($qb->expr()->eq('parent_id', $qb->createNamedParameter($reaction->getParentId())))
- ->andWhere($qb->expr()->eq('actor_type', $qb->createNamedParameter($reaction->getActorType())))
- ->andWhere($qb->expr()->eq('actor_id', $qb->createNamedParameter($reaction->getActorId())))
- ->andWhere($qb->expr()->eq('reaction', $qb->createNamedParameter($reaction->getMessage())));
- $result = $qb->executeQuery();
- $exists = (int) $result->fetchOne();
- if (!$exists) {
- $qb = $this->dbConn->getQueryBuilder();
- try {
- $qb->insert('reactions')
- ->values([
- 'parent_id' => $qb->createNamedParameter($reaction->getParentId()),
- 'message_id' => $qb->createNamedParameter($reaction->getId()),
- 'actor_type' => $qb->createNamedParameter($reaction->getActorType()),
- 'actor_id' => $qb->createNamedParameter($reaction->getActorId()),
- 'reaction' => $qb->createNamedParameter($reaction->getMessage()),
- ])
- ->executeStatement();
- } catch (\Exception $e) {
- $this->logger->error($e->getMessage(), [
- 'exception' => $e,
- 'app' => 'core_comments',
- ]);
- }
- }
- $this->sumReactions($reaction->getParentId());
- }
- private function sumReactions(string $parentId): void {
- $totalQuery = $this->dbConn->getQueryBuilder();
- $totalQuery
- ->selectAlias(
- $totalQuery->func()->concat(
- $totalQuery->expr()->literal('"'),
- 'reaction',
- $totalQuery->expr()->literal('":'),
- $totalQuery->func()->count('id')
- ),
- 'colonseparatedvalue'
- )
- ->selectAlias($totalQuery->func()->count('id'), 'total')
- ->from('reactions', 'r')
- ->where($totalQuery->expr()->eq('r.parent_id', $totalQuery->createNamedParameter($parentId)))
- ->groupBy('r.reaction')
- ->orderBy('total', 'DESC')
- ->addOrderBy('r.reaction', 'ASC')
- ->setMaxResults(20);
- $jsonQuery = $this->dbConn->getQueryBuilder();
- $jsonQuery
- ->selectAlias(
- $jsonQuery->func()->concat(
- $jsonQuery->expr()->literal('{'),
- $jsonQuery->func()->groupConcat('colonseparatedvalue'),
- $jsonQuery->expr()->literal('}')
- ),
- 'json'
- )
- ->from($jsonQuery->createFunction('(' . $totalQuery->getSQL() . ')'), 'json');
- $qb = $this->dbConn->getQueryBuilder();
- $qb
- ->update('comments')
- ->set('reactions', $qb->createFunction('(' . $jsonQuery->getSQL() . ')'))
- ->where($qb->expr()->eq('id', $qb->createNamedParameter($parentId)))
- ->executeStatement();
- }
- /**
- * updates a Comment data row
- *
- * @param IComment $comment
- * @return bool
- * @throws NotFoundException
- */
- protected function update(IComment $comment) {
- // for properly working preUpdate Events we need the old comments as is
- // in the DB and overcome caching. Also avoid that outdated information stays.
- $this->uncache($comment->getId());
- $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
- $this->uncache($comment->getId());
- try {
- $result = $this->updateQuery($comment, true);
- } catch (InvalidFieldNameException $e) {
- // See function insert() for explanation
- $result = $this->updateQuery($comment, false);
- }
- if ($comment->getVerb() === 'reaction_deleted') {
- $this->deleteReaction($comment);
- }
- $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
- return $result;
- }
- protected function updateQuery(IComment $comment, bool $tryWritingReferenceId): bool {
- $qb = $this->dbConn->getQueryBuilder();
- $qb
- ->update('comments')
- ->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
- ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
- ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
- ->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
- ->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
- ->set('message', $qb->createNamedParameter($comment->getMessage()))
- ->set('verb', $qb->createNamedParameter($comment->getVerb()))
- ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
- ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
- ->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
- ->set('object_id', $qb->createNamedParameter($comment->getObjectId()))
- ->set('expire_date', $qb->createNamedParameter($comment->getExpireDate(), 'datetime'));
- if ($tryWritingReferenceId) {
- $qb->set('reference_id', $qb->createNamedParameter($comment->getReferenceId()));
- }
- $affectedRows = $qb->where($qb->expr()->eq('id', $qb->createNamedParameter($comment->getId())))
- ->execute();
- if ($affectedRows === 0) {
- throw new NotFoundException('Comment to update does ceased to exist');
- }
- return $affectedRows > 0;
- }
- /**
- * removes references to specific actor (e.g. on user delete) of a comment.
- * The comment itself must not get lost/deleted.
- *
- * @param string $actorType the actor type (e.g. 'users')
- * @param string $actorId a user id
- * @return boolean
- * @since 9.0.0
- */
- public function deleteReferencesOfActor($actorType, $actorId) {
- $this->checkRoleParameters('Actor', $actorType, $actorId);
- $qb = $this->dbConn->getQueryBuilder();
- $affectedRows = $qb
- ->update('comments')
- ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
- ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
- ->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
- ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
- ->setParameter('type', $actorType)
- ->setParameter('id', $actorId)
- ->execute();
- $this->commentsCache = [];
- return is_int($affectedRows);
- }
- /**
- * deletes all comments made of a specific object (e.g. on file delete)
- *
- * @param string $objectType the object type (e.g. 'files')
- * @param string $objectId e.g. the file id
- * @return boolean
- * @since 9.0.0
- */
- public function deleteCommentsAtObject($objectType, $objectId) {
- $this->checkRoleParameters('Object', $objectType, $objectId);
- $qb = $this->dbConn->getQueryBuilder();
- $affectedRows = $qb
- ->delete('comments')
- ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
- ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
- ->setParameter('type', $objectType)
- ->setParameter('id', $objectId)
- ->execute();
- $this->commentsCache = [];
- return is_int($affectedRows);
- }
- /**
- * deletes the read markers for the specified user
- *
- * @param \OCP\IUser $user
- * @return bool
- * @since 9.0.0
- */
- public function deleteReadMarksFromUser(IUser $user) {
- $qb = $this->dbConn->getQueryBuilder();
- $query = $qb->delete('comments_read_markers')
- ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
- ->setParameter('user_id', $user->getUID());
- try {
- $affectedRows = $query->execute();
- } catch (DriverException $e) {
- $this->logger->error($e->getMessage(), [
- 'exception' => $e,
- 'app' => 'core_comments',
- ]);
- return false;
- }
- return ($affectedRows > 0);
- }
- /**
- * sets the read marker for a given file to the specified date for the
- * provided user
- *
- * @param string $objectType
- * @param string $objectId
- * @param \DateTime $dateTime
- * @param IUser $user
- * @since 9.0.0
- */
- public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
- $this->checkRoleParameters('Object', $objectType, $objectId);
- $qb = $this->dbConn->getQueryBuilder();
- $values = [
- 'user_id' => $qb->createNamedParameter($user->getUID()),
- 'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
- 'object_type' => $qb->createNamedParameter($objectType),
- 'object_id' => $qb->createNamedParameter($objectId),
- ];
- // Strategy: try to update, if this does not return affected rows, do an insert.
- $affectedRows = $qb
- ->update('comments_read_markers')
- ->set('user_id', $values['user_id'])
- ->set('marker_datetime', $values['marker_datetime'])
- ->set('object_type', $values['object_type'])
- ->set('object_id', $values['object_id'])
- ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
- ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
- ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
- ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
- ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
- ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
- ->execute();
- if ($affectedRows > 0) {
- return;
- }
- $qb->insert('comments_read_markers')
- ->values($values)
- ->execute();
- }
- /**
- * returns the read marker for a given file to the specified date for the
- * provided user. It returns null, when the marker is not present, i.e.
- * no comments were marked as read.
- *
- * @param string $objectType
- * @param string $objectId
- * @param IUser $user
- * @return \DateTime|null
- * @since 9.0.0
- */
- public function getReadMark($objectType, $objectId, IUser $user) {
- $qb = $this->dbConn->getQueryBuilder();
- $resultStatement = $qb->select('marker_datetime')
- ->from('comments_read_markers')
- ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
- ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
- ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
- ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
- ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
- ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
- ->execute();
- $data = $resultStatement->fetch();
- $resultStatement->closeCursor();
- if (!$data || is_null($data['marker_datetime'])) {
- return null;
- }
- return new \DateTime($data['marker_datetime']);
- }
- /**
- * deletes the read markers on the specified object
- *
- * @param string $objectType
- * @param string $objectId
- * @return bool
- * @since 9.0.0
- */
- public function deleteReadMarksOnObject($objectType, $objectId) {
- $this->checkRoleParameters('Object', $objectType, $objectId);
- $qb = $this->dbConn->getQueryBuilder();
- $query = $qb->delete('comments_read_markers')
- ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
- ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
- ->setParameter('object_type', $objectType)
- ->setParameter('object_id', $objectId);
- try {
- $affectedRows = $query->execute();
- } catch (DriverException $e) {
- $this->logger->error($e->getMessage(), [
- 'exception' => $e,
- 'app' => 'core_comments',
- ]);
- return false;
- }
- return ($affectedRows > 0);
- }
- /**
- * registers an Entity to the manager, so event notifications can be send
- * to consumers of the comments infrastructure
- *
- * @param \Closure $closure
- */
- public function registerEventHandler(\Closure $closure) {
- $this->eventHandlerClosures[] = $closure;
- $this->eventHandlers = [];
- }
- /**
- * registers a method that resolves an ID to a display name for a given type
- *
- * @param string $type
- * @param \Closure $closure
- * @throws \OutOfBoundsException
- * @since 11.0.0
- *
- * Only one resolver shall be registered per type. Otherwise a
- * \OutOfBoundsException has to thrown.
- */
- public function registerDisplayNameResolver($type, \Closure $closure) {
- if (!is_string($type)) {
- throw new \InvalidArgumentException('String expected.');
- }
- if (isset($this->displayNameResolvers[$type])) {
- throw new \OutOfBoundsException('Displayname resolver for this type already registered');
- }
- $this->displayNameResolvers[$type] = $closure;
- }
- /**
- * resolves a given ID of a given Type to a display name.
- *
- * @param string $type
- * @param string $id
- * @return string
- * @throws \OutOfBoundsException
- * @since 11.0.0
- *
- * If a provided type was not registered, an \OutOfBoundsException shall
- * be thrown. It is upon the resolver discretion what to return of the
- * provided ID is unknown. It must be ensured that a string is returned.
- */
- public function resolveDisplayName($type, $id) {
- if (!is_string($type)) {
- throw new \InvalidArgumentException('String expected.');
- }
- if (!isset($this->displayNameResolvers[$type])) {
- throw new \OutOfBoundsException('No Displayname resolver for this type registered');
- }
- return (string)$this->displayNameResolvers[$type]($id);
- }
- /**
- * returns valid, registered entities
- *
- * @return \OCP\Comments\ICommentsEventHandler[]
- */
- private function getEventHandlers() {
- if (!empty($this->eventHandlers)) {
- return $this->eventHandlers;
- }
- $this->eventHandlers = [];
- foreach ($this->eventHandlerClosures as $name => $closure) {
- $entity = $closure();
- if (!($entity instanceof ICommentsEventHandler)) {
- throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
- }
- $this->eventHandlers[$name] = $entity;
- }
- return $this->eventHandlers;
- }
- /**
- * sends notifications to the registered entities
- *
- * @param $eventType
- * @param IComment $comment
- */
- private function sendEvent($eventType, IComment $comment) {
- $entities = $this->getEventHandlers();
- $event = new CommentsEvent($eventType, $comment);
- foreach ($entities as $entity) {
- $entity->handle($event);
- }
- }
- /**
- * Load the Comments app into the page
- *
- * @since 21.0.0
- */
- public function load(): void {
- $this->initialStateService->provideInitialState('comments', 'max-message-length', IComment::MAX_MESSAGE_LENGTH);
- Util::addScript('comments', 'comments-app');
- }
- /**
- * @inheritDoc
- */
- public function deleteCommentsExpiredAtObject(string $objectType, string $objectId = ''): bool {
- $qb = $this->dbConn->getQueryBuilder();
- $qb->delete('comments')
- ->where($qb->expr()->lte('expire_date',
- $qb->createNamedParameter($this->timeFactory->getDateTime(), IQueryBuilder::PARAM_DATE)))
- ->andWhere($qb->expr()->eq('object_type', $qb->createNamedParameter($objectType)));
- if ($objectId !== '') {
- $qb->andWhere($qb->expr()->eq('object_id', $qb->createNamedParameter($objectId)));
- }
- $affectedRows = $qb->executeStatement();
- $this->commentsCache = [];
- return $affectedRows > 0;
- }
- }
|