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