]> BookStack Code Mirror - bookstack/blob - app/Activity/Controllers/CommentController.php
Merge pull request #4320 from devdot/improve-api-auth-exception
[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             '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         $this->validate($request, [
61             'text' => ['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, $request->get('text'));
69
70         return view('comments.comment', ['comment' => $comment, 'readOnly' => false]);
71     }
72
73     /**
74      * Delete a comment from the system.
75      */
76     public function destroy(int $id)
77     {
78         $comment = $this->commentRepo->getById($id);
79         $this->checkOwnablePermission('comment-delete', $comment);
80
81         $this->commentRepo->delete($comment);
82
83         return response()->json(['message' => trans('entities.comment_deleted')]);
84     }
85 }