1 <?php namespace BookStack\Http\Controllers;
3 use BookStack\Repos\CommentRepo;
4 use BookStack\Repos\EntityRepo;
6 use Illuminate\Http\Request;
8 class CommentController extends Controller
10 protected $entityRepo;
12 public function __construct(EntityRepo $entityRepo, CommentRepo $commentRepo, Comment $comment)
14 $this->entityRepo = $entityRepo;
15 $this->commentRepo = $commentRepo;
16 $this->comment = $comment;
17 parent::__construct();
20 public function save(Request $request, $pageId, $commentId = null)
22 $this->validate($request, [
23 'text' => 'required|string',
24 'html' => 'required|string',
28 $page = $this->entityRepo->getById('page', $pageId, true);
29 } catch (ModelNotFoundException $e) {
30 return response('Not found', 404);
34 // cannot add comments to drafts.
35 return response()->json([
37 'message' => trans('errors.cannot_add_comment_to_draft'),
41 $this->checkOwnablePermission('page-view', $page);
42 if (empty($commentId)) {
43 // create a new comment.
44 $this->checkPermission('comment-create-all');
45 $comment = $this->commentRepo->create($page, $request->only(['text', 'html', 'parent_id']));
46 $respMsg = trans('entities.comment_created');
48 // update existing comment
49 // get comment by ID and check if this user has permission to update.
50 $comment = $this->comment->findOrFail($commentId);
51 $this->checkOwnablePermission('comment-update', $comment);
52 $this->commentRepo->update($comment, $request->all());
53 $respMsg = trans('entities.comment_updated');
56 $comment = $this->commentRepo->getCommentById($comment->id);
58 return response()->json([
59 'status' => 'success',
60 'message' => $respMsg,
66 public function destroy($id) {
67 $comment = $this->comment->findOrFail($id);
68 $this->checkOwnablePermission('comment-delete', $comment);
69 $this->commentRepo->delete($comment);
70 $updatedComment = $this->commentRepo->getCommentById($comment->id);
72 return response()->json([
73 'status' => 'success',
74 'message' => trans('entities.comment_deleted'),
75 'comment' => $updatedComment
80 public function getPageComments($pageId) {
82 $page = $this->entityRepo->getById('page', $pageId, true);
83 } catch (ModelNotFoundException $e) {
84 return response('Not found', 404);
87 $this->checkOwnablePermission('page-view', $page);
89 $comments = $this->commentRepo->getPageComments($pageId);
90 return response()->json(['status' => 'success', 'comments'=> $comments['comments'],
91 'total' => $comments['total'], 'permissions' => [
92 'comment_create' => $this->currentUser->can('comment-create-all'),
93 'comment_update_own' => $this->currentUser->can('comment-update-own'),
94 'comment_update_all' => $this->currentUser->can('comment-update-all'),
95 'comment_delete_all' => $this->currentUser->can('comment-delete-all'),
96 'comment_delete_own' => $this->currentUser->can('comment-delete-own'),
97 ], 'user_id' => $this->currentUser->id]);