3 namespace BookStack\Activity;
5 use BookStack\Activity\Models\Comment;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Exceptions\NotifyException;
8 use BookStack\Facades\Activity as ActivityService;
9 use BookStack\Util\HtmlDescriptionFilter;
10 use Illuminate\Database\Eloquent\Builder;
15 * Get a comment by ID.
17 public function getById(int $id): Comment
19 return Comment::query()->findOrFail($id);
23 * Start a query for comments visible to the user.
25 public function getQueryForVisible(): Builder
27 return Comment::query()->scopes('visible');
31 * Create a new comment on an entity.
33 public function create(Entity $entity, string $html, ?int $parentId, string $contentRef): Comment
36 $comment = new Comment();
38 $comment->html = HtmlDescriptionFilter::filterFromString($html);
39 $comment->created_by = $userId;
40 $comment->updated_by = $userId;
41 $comment->local_id = $this->getNextLocalId($entity);
42 $comment->parent_id = $parentId;
43 $comment->content_ref = preg_match('/^bkmrk-(.*?):\d+:(\d*-\d*)?$/', $contentRef) === 1 ? $contentRef : '';
45 $entity->comments()->save($comment);
46 ActivityService::add(ActivityType::COMMENT_CREATE, $comment);
47 ActivityService::add(ActivityType::COMMENTED_ON, $entity);
53 * Update an existing comment.
55 public function update(Comment $comment, string $html): Comment
57 $comment->updated_by = user()->id;
58 $comment->html = HtmlDescriptionFilter::filterFromString($html);
61 ActivityService::add(ActivityType::COMMENT_UPDATE, $comment);
68 * Archive an existing comment.
70 public function archive(Comment $comment): Comment
72 if ($comment->parent_id) {
73 throw new NotifyException('Only top-level comments can be archived.', '/', 400);
76 $comment->archived = true;
79 ActivityService::add(ActivityType::COMMENT_UPDATE, $comment);
85 * Un-archive an existing comment.
87 public function unarchive(Comment $comment): Comment
89 if ($comment->parent_id) {
90 throw new NotifyException('Only top-level comments can be un-archived.', '/', 400);
93 $comment->archived = false;
96 ActivityService::add(ActivityType::COMMENT_UPDATE, $comment);
102 * Delete a comment from the system.
104 public function delete(Comment $comment): void
108 ActivityService::add(ActivityType::COMMENT_DELETE, $comment);
112 * Get the next local ID relative to the linked entity.
114 protected function getNextLocalId(Entity $entity): int
116 $currentMaxId = $entity->comments()->max('local_id');
118 return $currentMaxId + 1;