1
0
mirror of https://github.com/BookStackApp/BookStack.git synced 2025-07-28 17:02:04 +03:00

Made some changes to the comment system

Changed to be rendered server side along with page content.
Changed deletion to fully delete comments from the database.
Added 'local_id' to comments for referencing.
Updated reply system to be non-nested (Incomplete)
Made database comment format entity-agnostic to be more future proof.
Updated designs of comment sections.
This commit is contained in:
Dan Brown
2017-09-03 16:37:51 +01:00
parent e3f2bde26d
commit fea5630ea4
24 changed files with 478 additions and 731 deletions

View File

@ -1,12 +1,10 @@
<?php
namespace BookStack;
<?php namespace BookStack;
class Comment extends Ownable
{
public $sub_comments = [];
protected $fillable = ['text', 'html', 'parent_id'];
protected $appends = ['created', 'updated', 'sub_comments'];
protected $appends = ['created', 'updated'];
/**
* Get the entity that this comment belongs to
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
@ -17,80 +15,29 @@ class Comment extends Ownable
}
/**
* Get the page that this comment is in.
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
* Check if a comment has been updated since creation.
* @return bool
*/
public function page()
public function isUpdated()
{
return $this->belongsTo(Page::class);
return $this->updated_at->timestamp > $this->created_at->timestamp;
}
/**
* Get the owner of this comment.
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
* Get created date as a relative diff.
* @return mixed
*/
public function user()
public function getCreatedAttribute()
{
return $this->belongsTo(User::class);
return $this->created_at->diffForHumans();
}
/*
* Not being used, but left here because might be used in the future for performance reasons.
/**
* Get updated date as a relative diff.
* @return mixed
*/
public function getPageComments($pageId) {
$query = static::newQuery();
$query->join('users AS u', 'comments.created_by', '=', 'u.id');
$query->leftJoin('users AS u1', 'comments.updated_by', '=', 'u1.id');
$query->leftJoin('images AS i', 'i.id', '=', 'u.image_id');
$query->selectRaw('comments.id, text, html, comments.created_by, comments.updated_by, '
. 'comments.created_at, comments.updated_at, comments.parent_id, '
. 'u.name AS created_by_name, u1.name AS updated_by_name, '
. 'i.url AS avatar ');
$query->whereRaw('page_id = ?', [$pageId]);
$query->orderBy('created_at');
return $query->get();
}
public function getAllPageComments($pageId) {
return self::where('page_id', '=', $pageId)->with(['createdBy' => function($query) {
$query->select('id', 'name', 'image_id');
}, 'updatedBy' => function($query) {
$query->select('id', 'name');
}, 'createdBy.avatar' => function ($query) {
$query->select('id', 'path', 'url');
}])->get();
}
public function getCommentById($commentId) {
return self::where('id', '=', $commentId)->with(['createdBy' => function($query) {
$query->select('id', 'name', 'image_id');
}, 'updatedBy' => function($query) {
$query->select('id', 'name');
}, 'createdBy.avatar' => function ($query) {
$query->select('id', 'path', 'url');
}])->first();
}
public function getCreatedAttribute() {
$created = [
'day_time_str' => $this->created_at->toDayDateTimeString(),
'diff' => $this->created_at->diffForHumans()
];
return $created;
}
public function getUpdatedAttribute() {
if (empty($this->updated_at)) {
return null;
}
$updated = [
'day_time_str' => $this->updated_at->toDayDateTimeString(),
'diff' => $this->updated_at->diffForHumans()
];
return $updated;
}
public function getSubCommentsAttribute() {
return $this->sub_comments;
public function getUpdatedAttribute()
{
return $this->updated_at->diffForHumans();
}
}

View File

@ -1,6 +1,8 @@
<?php namespace BookStack;
use Illuminate\Database\Eloquent\Relations\MorphMany;
class Entity extends Ownable
{
@ -65,6 +67,16 @@ class Entity extends Ownable
return $this->morphMany(Tag::class, 'entity')->orderBy('order', 'asc');
}
/**
* Get the comments for an entity
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function comments()
{
return $this->morphMany(Comment::class, 'entity')->orderBy('created_at', 'asc');
}
/**
* Get the related search terms.
* @return \Illuminate\Database\Eloquent\Relations\MorphMany

View File

@ -2,22 +2,34 @@
use BookStack\Repos\CommentRepo;
use BookStack\Repos\EntityRepo;
use BookStack\Comment;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
class CommentController extends Controller
{
protected $entityRepo;
protected $commentRepo;
public function __construct(EntityRepo $entityRepo, CommentRepo $commentRepo, Comment $comment)
/**
* CommentController constructor.
* @param EntityRepo $entityRepo
* @param CommentRepo $commentRepo
*/
public function __construct(EntityRepo $entityRepo, CommentRepo $commentRepo)
{
$this->entityRepo = $entityRepo;
$this->commentRepo = $commentRepo;
$this->comment = $comment;
parent::__construct();
}
public function save(Request $request, $pageId, $commentId = null)
/**
* Save a new comment for a Page
* @param Request $request
* @param integer $pageId
* @param null|integer $commentId
* @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
*/
public function savePageComment(Request $request, $pageId, $commentId = null)
{
$this->validate($request, [
'text' => 'required|string',
@ -30,70 +42,50 @@ class CommentController extends Controller
return response('Not found', 404);
}
if($page->draft) {
// cannot add comments to drafts.
return response()->json([
'status' => 'error',
'message' => trans('errors.cannot_add_comment_to_draft'),
], 400);
}
$this->checkOwnablePermission('page-view', $page);
if (empty($commentId)) {
// create a new comment.
$this->checkPermission('comment-create-all');
$comment = $this->commentRepo->create($page, $request->only(['text', 'html', 'parent_id']));
$respMsg = trans('entities.comment_created');
} else {
// update existing comment
// get comment by ID and check if this user has permission to update.
$comment = $this->comment->findOrFail($commentId);
$this->checkOwnablePermission('comment-update', $comment);
$this->commentRepo->update($comment, $request->all());
$respMsg = trans('entities.comment_updated');
// Prevent adding comments to draft pages
if ($page->draft) {
return $this->jsonError(trans('errors.cannot_add_comment_to_draft'), 400);
}
$comment = $this->commentRepo->getCommentById($comment->id);
return response()->json([
'status' => 'success',
'message' => $respMsg,
'comment' => $comment
]);
// Create a new comment.
$this->checkPermission('comment-create-all');
$comment = $this->commentRepo->create($page, $request->all());
return view('comments/comment', ['comment' => $comment]);
}
public function destroy($id) {
$comment = $this->comment->findOrFail($id);
/**
* Update an existing comment.
* @param Request $request
* @param integer $commentId
* @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function update(Request $request, $commentId)
{
$this->validate($request, [
'text' => 'required|string',
'html' => 'required|string',
]);
$comment = $this->commentRepo->getById($commentId);
$this->checkOwnablePermission('page-view', $comment->entity);
$this->checkOwnablePermission('comment-update', $comment);
$comment = $this->commentRepo->update($comment, $request->all());
return view('comments/comment', ['comment' => $comment]);
}
/**
* Delete a comment from the system.
* @param integer $id
* @return \Illuminate\Http\JsonResponse
*/
public function destroy($id)
{
$comment = $this->commentRepo->getById($id);
$this->checkOwnablePermission('comment-delete', $comment);
$this->commentRepo->delete($comment);
$updatedComment = $this->commentRepo->getCommentById($comment->id);
return response()->json([
'status' => 'success',
'message' => trans('entities.comment_deleted'),
'comment' => $updatedComment
]);
}
public function getPageComments($pageId) {
try {
$page = $this->entityRepo->getById('page', $pageId, true);
} catch (ModelNotFoundException $e) {
return response('Not found', 404);
}
$this->checkOwnablePermission('page-view', $page);
$comments = $this->commentRepo->getPageComments($pageId);
return response()->json(['status' => 'success', 'comments'=> $comments['comments'],
'total' => $comments['total'], 'permissions' => [
'comment_create' => $this->currentUser->can('comment-create-all'),
'comment_update_own' => $this->currentUser->can('comment-update-own'),
'comment_update_all' => $this->currentUser->can('comment-update-all'),
'comment_delete_all' => $this->currentUser->can('comment-delete-all'),
'comment_delete_own' => $this->currentUser->can('comment-delete-own'),
], 'user_id' => $this->currentUser->id]);
return response()->json(['message' => trans('entities.comment_deleted')]);
}
}

View File

@ -161,6 +161,7 @@ class PageController extends Controller
$pageContent = $this->entityRepo->renderPage($page);
$sidebarTree = $this->entityRepo->getBookChildren($page->book);
$pageNav = $this->entityRepo->getPageNav($pageContent);
$page->load(['comments.createdBy']);
Views::add($page);
$this->setPageTitle($page->getShortName());

View File

@ -66,10 +66,6 @@ class Page extends Entity
return $this->hasMany(Attachment::class, 'uploaded_to')->orderBy('order', 'asc');
}
public function comments() {
return $this->hasMany(Comment::class, 'page_id')->orderBy('created_on', 'asc');
}
/**
* Get the url for this page.
* @param string|bool $path

View File

@ -1,105 +1,87 @@
<?php namespace BookStack\Repos;
use BookStack\Comment;
use BookStack\Page;
use BookStack\Entity;
/**
* Class TagRepo
* Class CommentRepo
* @package BookStack\Repos
*/
class CommentRepo {
/**
*
* @var Comment $comment
*/
protected $comment;
/**
* CommentRepo constructor.
* @param Comment $comment
*/
public function __construct(Comment $comment)
{
$this->comment = $comment;
}
public function create (Page $page, $data = []) {
/**
* Get a comment by ID.
* @param $id
* @return Comment|\Illuminate\Database\Eloquent\Model
*/
public function getById($id)
{
return $this->comment->newQuery()->findOrFail($id);
}
/**
* Create a new comment on an entity.
* @param Entity $entity
* @param array $data
* @return Comment
*/
public function create (Entity $entity, $data = [])
{
$userId = user()->id;
$comment = $this->comment->newInstance();
$comment->fill($data);
// new comment
$comment->page_id = $page->id;
$comment = $this->comment->newInstance($data);
$comment->created_by = $userId;
$comment->updated_at = null;
$comment->save();
return $comment;
}
public function update($comment, $input, $activeOnly = true) {
$userId = user()->id;
$comment->updated_by = $userId;
$comment->fill($input);
// only update active comments by default.
$whereClause = ['active' => 1];
if (!$activeOnly) {
$whereClause = [];
}
$comment->update($whereClause);
$comment->local_id = $this->getNextLocalId($entity);
$entity->comments()->save($comment);
return $comment;
}
public function delete($comment) {
$comment->text = trans('entities.comment_deleted');
$comment->html = trans('entities.comment_deleted');
$comment->active = false;
$userId = user()->id;
$comment->updated_by = $userId;
$comment->save();
/**
* Update an existing comment.
* @param Comment $comment
* @param array $input
* @return mixed
*/
public function update($comment, $input)
{
$comment->updated_by = user()->id;
$comment->update($input);
return $comment;
}
public function getPageComments($pageId) {
$comments = $this->comment->getAllPageComments($pageId);
$index = [];
$totalComments = count($comments);
$finalCommentList = [];
// normalizing the response.
for ($i = 0; $i < count($comments); ++$i) {
$comment = $this->normalizeComment($comments[$i]);
$parentId = $comment->parent_id;
if (empty($parentId)) {
$finalCommentList[] = $comment;
$index[$comment->id] = $comment;
continue;
}
if (empty($index[$parentId])) {
// weird condition should not happen.
continue;
}
if (empty($index[$parentId]->sub_comments)) {
$index[$parentId]->sub_comments = [];
}
array_push($index[$parentId]->sub_comments, $comment);
$index[$comment->id] = $comment;
}
return [
'comments' => $finalCommentList,
'total' => $totalComments
];
/**
* Delete a comment from the system.
* @param Comment $comment
* @return mixed
*/
public function delete($comment)
{
return $comment->delete();
}
public function getCommentById($commentId) {
return $this->normalizeComment($this->comment->getCommentById($commentId));
}
private function normalizeComment($comment) {
if (empty($comment)) {
return;
}
$comment->createdBy->avatar_url = $comment->createdBy->getAvatar(50);
$comment->createdBy->profile_url = $comment->createdBy->getProfileUrl();
if (!empty($comment->updatedBy)) {
$comment->updatedBy->profile_url = $comment->updatedBy->getProfileUrl();
}
return $comment;
/**
* Get the next local ID relative to the linked entity.
* @param Entity $entity
* @return int
*/
protected function getNextLocalId(Entity $entity)
{
$comments = $entity->comments()->orderBy('local_id', 'desc')->first();
if ($comments === null) return 1;
return $comments->local_id + 1;
}
}

View File

@ -33,6 +33,7 @@ class TagRepo
* @param $entityType
* @param $entityId
* @param string $action
* @return \Illuminate\Database\Eloquent\Model|null|static
*/
public function getEntity($entityType, $entityId, $action = 'view')
{