]> BookStack Code Mirror - bookstack/blob - app/Http/Controllers/CommentController.php
Merge pull request #1 from BookStackApp/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     public function __construct(CommentRepo $commentRepo)
14     {
15         $this->commentRepo = $commentRepo;
16         parent::__construct();
17     }
18
19     /**
20      * Save a new comment for a Page
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         Activity::add($page, 'commented_on', $page->book->id);
44         return view('comments.comment', ['comment' => $comment]);
45     }
46
47     /**
48      * Update an existing comment.
49      * @throws ValidationException
50      */
51     public function update(Request $request, int $commentId)
52     {
53         $this->validate($request, [
54             'text' => 'required|string',
55         ]);
56
57         $comment = $this->commentRepo->getById($commentId);
58         $this->checkOwnablePermission('page-view', $comment->entity);
59         $this->checkOwnablePermission('comment-update', $comment);
60
61         $comment = $this->commentRepo->update($comment, $request->get('text'));
62         return view('comments.comment', ['comment' => $comment]);
63     }
64
65     /**
66      * Delete a comment from the system.
67      */
68     public function destroy(int $id)
69     {
70         $comment = $this->commentRepo->getById($id);
71         $this->checkOwnablePermission('comment-delete', $comment);
72
73         $this->commentRepo->delete($comment);
74         return response()->json(['message' => trans('entities.comment_deleted')]);
75     }
76 }