]> BookStack Code Mirror - bookstack/blob - app/Activity/Controllers/CommentController.php
Comments: Added back-end HTML support, fixed editor focus
[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         $input = $this->validate($request, [
26             'html'      => ['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, $input['html'], $input['parent_id'] ?? null);
43
44         return view('comments.comment-branch', [
45             'readOnly' => false,
46             'branch' => [
47                 'comment' => $comment,
48                 'children' => [],
49             ]
50         ]);
51     }
52
53     /**
54      * Update an existing comment.
55      *
56      * @throws ValidationException
57      */
58     public function update(Request $request, int $commentId)
59     {
60         $input = $this->validate($request, [
61             'html' => ['required', 'string'],
62         ]);
63
64         $comment = $this->commentRepo->getById($commentId);
65         $this->checkOwnablePermission('page-view', $comment->entity);
66         $this->checkOwnablePermission('comment-update', $comment);
67
68         $comment = $this->commentRepo->update($comment, $input['html']);
69
70         return view('comments.comment', [
71             'comment' => $comment,
72             'readOnly' => false,
73         ]);
74     }
75
76     /**
77      * Delete a comment from the system.
78      */
79     public function destroy(int $id)
80     {
81         $comment = $this->commentRepo->getById($id);
82         $this->checkOwnablePermission('comment-delete', $comment);
83
84         $this->commentRepo->delete($comment);
85
86         return response()->json(['message' => trans('entities.comment_deleted')]);
87     }
88 }