]> BookStack Code Mirror - bookstack/blob - app/Activity/Controllers/CommentController.php
Merge pull request #4286 from BookStackApp/comment_threads
[bookstack] / app / Activity / Controllers / CommentController.php
1 <?php
2
3 namespace BookStack\Activity\Controllers;
4
5 use BookStack\Activity\CommentRepo;
6 use BookStack\Entities\Models\Page;
7 use BookStack\Http\Controller;
8 use Illuminate\Http\Request;
9 use Illuminate\Validation\ValidationException;
10
11 class CommentController extends Controller
12 {
13     public function __construct(
14         protected CommentRepo $commentRepo
15     ) {
16     }
17
18     /**
19      * Save a new comment for a Page.
20      *
21      * @throws ValidationException
22      */
23     public function savePageComment(Request $request, int $pageId)
24     {
25         $this->validate($request, [
26             'text'      => ['required', 'string'],
27             'parent_id' => ['nullable', 'integer'],
28         ]);
29
30         $page = Page::visible()->find($pageId);
31         if ($page === null) {
32             return response('Not found', 404);
33         }
34
35         // Prevent adding comments to draft pages
36         if ($page->draft) {
37             return $this->jsonError(trans('errors.cannot_add_comment_to_draft'), 400);
38         }
39
40         // Create a new comment.
41         $this->checkPermission('comment-create-all');
42         $comment = $this->commentRepo->create($page, $request->get('text'), $request->get('parent_id'));
43
44         return view('comments.comment-branch', [
45             'branch' => [
46                 'comment' => $comment,
47                 'children' => [],
48             ]
49         ]);
50     }
51
52     /**
53      * Update an existing comment.
54      *
55      * @throws ValidationException
56      */
57     public function update(Request $request, int $commentId)
58     {
59         $this->validate($request, [
60             'text' => ['required', 'string'],
61         ]);
62
63         $comment = $this->commentRepo->getById($commentId);
64         $this->checkOwnablePermission('page-view', $comment->entity);
65         $this->checkOwnablePermission('comment-update', $comment);
66
67         $comment = $this->commentRepo->update($comment, $request->get('text'));
68
69         return view('comments.comment', ['comment' => $comment]);
70     }
71
72     /**
73      * Delete a comment from the system.
74      */
75     public function destroy(int $id)
76     {
77         $comment = $this->commentRepo->getById($id);
78         $this->checkOwnablePermission('comment-delete', $comment);
79
80         $this->commentRepo->delete($comment);
81
82         return response()->json(['message' => trans('entities.comment_deleted')]);
83     }
84 }