]> BookStack Code Mirror - bookstack/blob - app/Activity/CommentRepo.php
WYSIWYG: Updated TinyMCE from 6.5.1 to 6.7.2
[bookstack] / app / Activity / CommentRepo.php
1 <?php
2
3 namespace BookStack\Activity;
4
5 use BookStack\Activity\Models\Comment;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Facades\Activity as ActivityService;
8 use League\CommonMark\CommonMarkConverter;
9
10 class CommentRepo
11 {
12     /**
13      * Get a comment by ID.
14      */
15     public function getById(int $id): Comment
16     {
17         return Comment::query()->findOrFail($id);
18     }
19
20     /**
21      * Create a new comment on an entity.
22      */
23     public function create(Entity $entity, string $text, ?int $parent_id): Comment
24     {
25         $userId = user()->id;
26         $comment = new Comment();
27
28         $comment->text = $text;
29         $comment->html = $this->commentToHtml($text);
30         $comment->created_by = $userId;
31         $comment->updated_by = $userId;
32         $comment->local_id = $this->getNextLocalId($entity);
33         $comment->parent_id = $parent_id;
34
35         $entity->comments()->save($comment);
36         ActivityService::add(ActivityType::COMMENT_CREATE, $comment);
37         ActivityService::add(ActivityType::COMMENTED_ON, $entity);
38
39         return $comment;
40     }
41
42     /**
43      * Update an existing comment.
44      */
45     public function update(Comment $comment, string $text): Comment
46     {
47         $comment->updated_by = user()->id;
48         $comment->text = $text;
49         $comment->html = $this->commentToHtml($text);
50         $comment->save();
51
52         ActivityService::add(ActivityType::COMMENT_UPDATE, $comment);
53
54         return $comment;
55     }
56
57     /**
58      * Delete a comment from the system.
59      */
60     public function delete(Comment $comment): void
61     {
62         $comment->delete();
63
64         ActivityService::add(ActivityType::COMMENT_DELETE, $comment);
65     }
66
67     /**
68      * Convert the given comment Markdown to HTML.
69      */
70     public function commentToHtml(string $commentText): string
71     {
72         $converter = new CommonMarkConverter([
73             'html_input'         => 'strip',
74             'max_nesting_level'  => 10,
75             'allow_unsafe_links' => false,
76         ]);
77
78         return $converter->convert($commentText);
79     }
80
81     /**
82      * Get the next local ID relative to the linked entity.
83      */
84     protected function getNextLocalId(Entity $entity): int
85     {
86         $currentMaxId = $entity->comments()->max('local_id');
87
88         return $currentMaxId + 1;
89     }
90 }