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