3 namespace BookStack\Activity;
5 use BookStack\Activity\Models\Comment;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Exceptions\NotifyException;
8 use BookStack\Exceptions\PrettyException;
9 use BookStack\Facades\Activity as ActivityService;
10 use BookStack\Util\HtmlDescriptionFilter;
15 * Get a comment by ID.
17 public function getById(int $id): Comment
19 return Comment::query()->findOrFail($id);
23 * Create a new comment on an entity.
25 public function create(Entity $entity, string $html, ?int $parent_id, string $content_ref): Comment
28 $comment = new Comment();
30 $comment->html = HtmlDescriptionFilter::filterFromString($html);
31 $comment->created_by = $userId;
32 $comment->updated_by = $userId;
33 $comment->local_id = $this->getNextLocalId($entity);
34 $comment->parent_id = $parent_id;
35 $comment->content_ref = preg_match('/^bkmrk-(.*?):\d+:(\d*-\d*)?$/', $content_ref) === 1 ? $content_ref : '';
37 $entity->comments()->save($comment);
38 ActivityService::add(ActivityType::COMMENT_CREATE, $comment);
39 ActivityService::add(ActivityType::COMMENTED_ON, $entity);
45 * Update an existing comment.
47 public function update(Comment $comment, string $html): Comment
49 $comment->updated_by = user()->id;
50 $comment->html = HtmlDescriptionFilter::filterFromString($html);
53 ActivityService::add(ActivityType::COMMENT_UPDATE, $comment);
60 * Archive an existing comment.
62 public function archive(Comment $comment): Comment
64 if ($comment->parent_id) {
65 throw new NotifyException('Only top-level comments can be archived.');
68 $comment->archived = true;
71 ActivityService::add(ActivityType::COMMENT_UPDATE, $comment);
77 * Un-archive an existing comment.
79 public function unarchive(Comment $comment): Comment
81 if ($comment->parent_id) {
82 throw new NotifyException('Only top-level comments can be un-archived.');
85 $comment->archived = false;
88 ActivityService::add(ActivityType::COMMENT_UPDATE, $comment);
94 * Delete a comment from the system.
96 public function delete(Comment $comment): void
100 ActivityService::add(ActivityType::COMMENT_DELETE, $comment);
104 * Get the next local ID relative to the linked entity.
106 protected function getNextLocalId(Entity $entity): int
108 $currentMaxId = $entity->comments()->max('local_id');
110 return $currentMaxId + 1;