finish nested comment implementation

This commit is contained in:
Thorsten Witteler 2017-10-24 02:57:44 +02:00
parent 0936de7c1d
commit b4ab9a5111
6 changed files with 279 additions and 254 deletions

View File

@ -9,7 +9,7 @@ Comments Plugin Styles
border-top: gray solid 2px; border-top: gray solid 2px;
} }
.comment:first-child { .comment:first-child {
margin-top: 0; margin-top: 0px;
} }
.comment, .comment,
.comment-body { .comment-body {
@ -43,7 +43,7 @@ Comments Plugin Styles
vertical-align: bottom; vertical-align: bottom;
} }
.comment-heading { .comment-heading {
margin-top: 0; margin-top: 0px;
margin-bottom: 5px; margin-bottom: 5px;
border-bottom: gray dashed 1px; border-bottom: gray dashed 1px;
} }
@ -63,6 +63,55 @@ Comments Plugin Styles
clear: both; clear: both;
} }
.comment-list { .comment-list {
padding-left: 0; padding-left: 0px;
list-style: none; list-style: none;
} }
.comment-flag-new {
background-color: lightcyan;
}
.comment-level-1 { margin-left: 20px; padding-left: 0px; border-left: gray solid 0px; }
.comment-level-2 { margin-left: 40px; padding-left: 0px; border-left: gray solid 0px; }
.comment-level-3 { margin-left: 60px; padding-left: 0px; border-left: gray solid 0px; }
.comment-level-4 { margin-left: 80px; padding-left: 0px; border-left: gray solid 0px; }
.comment-level-5 { margin-left: 100px; padding-left: 0px; border-left: gray solid 0px; }
.row.comments { position: relative; }
.comment-level-1::before {
content: "\f105";
font-family: FontAwesome;
position: absolute;
left: 0px;
font-size: 3rem;
color: lightgray;
}
.comment-level-2::before {
content: "\f105\f105";
font-family: FontAwesome;
position: absolute;
left: 0px;
font-size: 3rem;
color: lightgray;
}
.comment-level-3::before {
content: "\f105\f105\f105";
font-family: FontAwesome;
position: absolute;
left: 0px;
font-size: 3rem;
color: lightgray;
}
.comment-level-4::before {
content: "\f105\f105\f105\f105";
font-family: FontAwesome;
position: absolute;
left: 0px;
font-size: 3rem;
color: lightgray;
}
.comment-level-5::before {
content: "\f105\f105\f105\f105\f105";
font-family: FontAwesome;
position: absolute;
left: 0px;
font-size: 3rem;
color: lightgray;
}

View File

@ -1,36 +1,24 @@
function escapeRegExp(str) {
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
jQuery(document).ready(function () { jQuery(document).ready(function () {
var commentForm = $(document).find('.comments-form'); var commentForm = $(document).find('.comments-form');
var commentSection = $(document).find('.comments').first(); var commentSection = $(document).find('.comments').first();
var commentAlert = commentForm.closest('.alert'); var commentAlert = $(document).find('.alert').first();
//var newMedia;
//hide form, show link //hide form, show link
commentForm.hide(); commentForm.hide();
$(document).find('.comment-add-new').show(); $(document).find('.comment-add-new').show();
//get template for inserting new comments
/*
$.ajax({
url: '/media_template.php',
method: 'GET',
dataType: 'html',
success: function (data) {
newMedia = data;
}
});
*/
$('body').on('click', '.comment-add-new-sadf', function (e) {
e.preventDefault();
alert('asdf');
$('span').stop().css('opacity', 1).text('myName = ' + e.name).fadeIn(30).fadeOut(1000);
});
//show comment form above comments section (new comment thread) //show comment form above comments section (new comment thread)
$('body').on('click', '.comment-add-new', function (e) { $('body').on('click', '.comment-add-new', function (e) {
e.preventDefault(); e.preventDefault();
//commentForm.hide(1000); //commentForm.hide(1000);
//commentSection.before(commentForm);
$(this).before(commentForm); $(this).before(commentForm);
commentForm.show('slow'); commentForm.show('slow');
//$(this).slideUp(); commentAlert.slideUp();
}); });
//show comment form below selected comment (reply to existing comment) //show comment form below selected comment (reply to existing comment)
$('body').on('click', '.comment-add-reply', function (e) { $('body').on('click', '.comment-add-reply', function (e) {
e.preventDefault(); e.preventDefault();
@ -38,93 +26,96 @@ $.ajax({
commentForm.hide(); commentForm.hide();
media.find('>.comment-body>.comment-text').after(commentForm); media.find('>.comment-body>.comment-text').after(commentForm);
commentForm.show('slow'); commentForm.show('slow');
commentAlert.slideUp();
}); });
// Attach a submit handler to the form // Attach a submit handler to the form
$(commentForm).on('submit', function (event) { $(commentForm).on('submit', function (event) {
event.preventDefault(); event.preventDefault();
// Get some values from elements on the page: // Get form data:
//var term = $(this).find( "input[name='s']" ).val();
//var data = $(this).serializeArray();
var data = $(this).serialize(); var data = $(this).serialize();
console.log("Form Data (submit)", JSON.parse(JSON.stringify(data))); //console.log("Form Data (submit)", JSON.parse(JSON.stringify(data)));
//var url = $(this).attr( "action" ); var url = $(this).attr( "action" );
var url = '/nested-comments'; //var url = '/nested-comments';
var parentId = 0; var parentId = 0;
var ownLevel = 0;
if ($(this).parents('.comment').length > 0) { if ($(this).parents('.comment').length > 0) {
parentId = $(this).closest('.comment').attr('data-Id'); parentId = $(this).closest('.comment').attr('data-id');
ownLevel = parseInt($(this).closest('.comment').attr('data-level'), 10) + 1;
} }
// Send the data using post // Send the data using post
//var posting = $.post(url, { parentId: parentId, data: data }, null, 'json'); //var posting = $.post(url, { parentId: parentId, data: data }, null, 'json');
var posting = $.post(url, data + '&parentID=' + parentId, null, 'json'); var posting = $.post(url, data + '&parentID=' + parentId, null, 'json');
//$.post( "test.php", $( "#testform" ).serialize() );
// Put the results in a div // Register events to ajax call
posting.done(function (response) { posting.done(function (response) {
alert('success'); //alert('success');
console.log("Response Data (done)", JSON.parse(JSON.stringify(response))); //console.log("Response Data (done)", JSON.parse(JSON.stringify(response)));
//response = JSON.parse(response); //response = JSON.parse(response); //not needed, post was done using json
var message = response.status ? response.message : 'Error: ' + response.message;
commentForm.after(commentAlert); commentForm.after(commentAlert);
commentAlert.empty().append(message);
if (!response.status) { if (!response.status) {
return; //should not trigger at all, if all bad requests return the right http status code
//i.e. <> 200 success => thus triggering posting.fail()
//leave this check just in case
commentAlert.stop().css('opacity', 1).text('Error: ' + response.message).fadeIn(30).fadeOut(5000);
return;
} }
if (response.status) { if (response.status) {
var newMedia = ` commentAlert.css('color', 'green').empty().append(document.createTextNode( response.message )).fadeIn(30);
<div class='comment comment-level-{{comment.level|e}}' data-Id='{{comment.id}}' > var newMedia = "<div class='comment comment-level-{{comment.level|e}} comment-flag-new' data-level='{{comment.level}}' data-id='{{comment.id}}' >" +
<div class='comment-left'> "<div class='comment-left'>" +
<a href='#'> "<a href='#'>" +
<img class='comment-object' src='https://www.gravatar.com/avatar/{{comment.email|trim|lower|md5}}?d=identicon' alt='user icon'> "<img class='comment-object' src='https://www.gravatar.com/avatar/{{comment.email|trim|lower|md5}}?d=identicon' alt='user icon'>" +
</a> "</a>" +
</div> "</div>" +
<div class='comment-body'> "<div class='comment-body'>" +
<div class='comment-heading'> "<div class='comment-heading'>" +
<div class='comment-title'><h4>{{comment.title}}</h4></div> "<div class='comment-title'><h4>{{comment.title}}</h4></div>" +
<div class='comment-reply'><a class='comment-add-reply' href='#'>{{'PLUGIN_COMMENTS.ADD_REPLY'|t}}</a></div> "<div class='comment-reply'><a class='comment-add-reply' href='#'><i class='fa fa-reply' title='{{'PLUGIN_COMMENTS.ADD_REPLY'|t}}'></i> {{'PLUGIN_COMMENTS.ADD_REPLY'|t}}</a></div>" +
<div class='comment-meta'>{{'PLUGIN_COMMENTS.WRITTEN_ON'|t}} {{comment.date|e}} {{'PLUGIN_COMMENTS.BY'|t}} {{comment.author}}</div> "<div class='comment-meta'>{{'PLUGIN_COMMENTS.WRITTEN_ON'|t}} {{comment.date|e}} {{'PLUGIN_COMMENTS.BY'|t}} {{comment.author}}</div>" +
</div> "</div>" +
<div class='comment-text' > "<div class='comment-text' >" +
{{comment.text}} "{{comment.text}}" +
</div> "</div>" +
{{nested}} "{{nested}}" +
</div> "</div>" +
</div> "</div>";
`; newMedia = newMedia.replace(new RegExp(escapeRegExp("{{comment.id}}"), 'g'), response.data.id);
newMedia = newMedia.replace('{{comment.id}}', response.id); newMedia = newMedia.replace(new RegExp(escapeRegExp("{{comment.level|e}}"), 'g'), ownLevel);
newMedia = newMedia.replace('{{comment.level|e}}', response.level); newMedia = newMedia.replace(new RegExp(escapeRegExp("{{comment.level}}"), 'g'), ownLevel);
newMedia = newMedia.replace('{{comment.email|trim|lower|md5}}', response.hash); newMedia = newMedia.replace(new RegExp(escapeRegExp("{{comment.email|trim|lower|md5}}"), 'g'), response.data.hash);
newMedia = newMedia.replace('{{parent_id}}', response.data.parent_id); newMedia = newMedia.replace(new RegExp(escapeRegExp("{{parent_id}}"), 'g'), response.data.parent_id);
newMedia = newMedia.replace('{{comment.title}}', response.data.title); newMedia = newMedia.replace(new RegExp(escapeRegExp("{{comment.title}}"), 'g'), response.data.title);
newMedia = newMedia.replace('{{comment.text}}', response.data.text); newMedia = newMedia.replace(new RegExp(escapeRegExp("{{comment.text}}"), 'g'), response.data.text);
newMedia = newMedia.replace('{{comment.author}}', response.data.name); newMedia = newMedia.replace(new RegExp(escapeRegExp("{{comment.author}}"), 'g'), response.data.name);
//newMedia = newMedia.replace('{{comment.date|e}}', response.data.name); newMedia = newMedia.replace(new RegExp(escapeRegExp("{{comment.date|e}}"), 'g'), response.data.date);
if ($( "div[data-Id='" + response.data.parent_id + "']" ).length > 0) { newMedia = newMedia.replace(new RegExp(escapeRegExp("{{nested}}"), 'g'), '');
$( "div[data-Id='" + response.data.parent_id + "']" ).first().after(newMedia); newMedia = newMedia.replace(new RegExp(escapeRegExp("{{'PLUGIN_COMMENTS.ADD_REPLY'|t}}"), 'g'), response.data.ADD_REPLY);
} else { newMedia = newMedia.replace(new RegExp(escapeRegExp("{{'PLUGIN_COMMENTS.WRITTEN_ON'|t}}"), 'g'), response.data.WRITTEN_ON);
newMedia = newMedia.replace(new RegExp(escapeRegExp("{{'PLUGIN_COMMENTS.BY'|t}}"), 'g'), response.data.BY);
if ($( "div[data-id='" + response.data.parent_id + "']" ).length > 0) {
$( "div[data-id='" + response.data.parent_id + "']" ).first().after(newMedia);
} else {
$( "div.comments" ).last().prepend(newMedia); $( "div.comments" ).last().prepend(newMedia);
} }
//phpComment.commentForm.before(newMedia);
//phpComment.titleField.val("");
//phpComment.bodyField.val("");
} }
setTimeout(function () { setTimeout(function () {
commentForm.hide(3000); commentForm.hide(2000);
commentAlert.fadeOut(5000);
}, 5000); }, 5000);
}); });
posting.fail(function (status, error, title) { posting.fail(function (status, error, title) {
alert('error'); //alert('error');
console.log("Response Data (fail)", JSON.parse(JSON.stringify(status))); //console.log("Response Data (fail)", JSON.parse(JSON.stringify(status)));
commentForm.after(commentAlert); commentForm.after(commentAlert);
commentAlert.empty().append("<p>TEST</p>"); commentAlert.empty().append("<p>TEST</p>");
commentAlert.append("<p>" + status + "</p>"); commentAlert.append("<p>" + status + "</p>");
commentAlert.append("<p>" + error + "</p>"); commentAlert.append("<p>" + error + "</p>");
commentAlert.append("<p>" + title + "</p>"); commentAlert.append("<p>" + title + "</p>");
}); });
posting.always(function (test) { posting.always(function () {
//alert("finished, be it successful or not"); //alert("finished, be it successful or not");
//test = JSON.parse(test);
//test = test.serialize();
//alert(test);
}); });
}); });
}); });

View File

@ -28,7 +28,8 @@ class Comment
$comments[] = $this->value; $comments[] = $this->value;
foreach($this->children as $child) { foreach($this->children as $child) {
$comments[] = $child->getContent($level + 1); //$comments[] = $child->getContent($level + 1); //produces nested result array.
$comments = array_merge($comments, $child->getContent($level + 1)); //produces flat result array.
} }
return $comments; return $comments;
} }

View File

@ -182,7 +182,7 @@ class CommentsPlugin extends Plugin
// Process comment if required // Process comment if required
if ($is_ajax || $callback === $this->grav['uri']->path()) { if ($is_ajax || $callback === $this->grav['uri']->path()) {
// try to add the comment // try to add the comment
$result = $this->addComment(); $result = $this->addComment(true);
echo json_encode([ echo json_encode([
'status' => $result[0], 'status' => $result[0],
'message' => $result[1], 'message' => $result[1],
@ -196,8 +196,10 @@ class CommentsPlugin extends Plugin
} }
} }
public function addComment() public function addComment($is_ajax = false)
{ {
if($is_ajax) {
$language = $this->grav['language'];
if (!$_SERVER["REQUEST_METHOD"] == "POST") { if (!$_SERVER["REQUEST_METHOD"] == "POST") {
// Not a POST request, set a 403 (forbidden) response code. // Not a POST request, set a 403 (forbidden) response code.
http_response_code(403); http_response_code(403);
@ -220,43 +222,6 @@ class CommentsPlugin extends Plugin
$input['path'] = isset($_POST['data']['path']) ? filter_var($_POST['data']['path'], FILTER_SANITIZE_STRING) : null; $input['path'] = isset($_POST['data']['path']) ? filter_var($_POST['data']['path'], FILTER_SANITIZE_STRING) : null;
$input['form-name'] = filter_input(INPUT_POST, 'form-name', FILTER_SANITIZE_STRING); $input['form-name'] = filter_input(INPUT_POST, 'form-name', FILTER_SANITIZE_STRING);
$input['form-nonce'] = filter_input(INPUT_POST, 'form-nonce', FILTER_SANITIZE_STRING); $input['form-nonce'] = filter_input(INPUT_POST, 'form-nonce', FILTER_SANITIZE_STRING);
/*
foreach ($_POST['data'] as $field) {
if (isset($field['name']) && isset($field['value'])) {
switch ($field['name']) {
case 'data[name]':
$input['name'] = filter_var($field['value'], FILTER_SANITIZE_STRING);
break;
case 'data[email]':
$input['email'] = filter_var($field['value'], FILTER_SANITIZE_EMAIL);
break;
case 'data[text]':
$input['text'] = filter_var($field['value'], FILTER_SANITIZE_STRING);
break;
case 'data[date]':
$input['date'] = filter_var($field['value'], FILTER_SANITIZE_STRING);
break;
case 'data[title]':
$input['title'] = filter_var($field['value'], FILTER_SANITIZE_STRING);
break;
case 'data[lang]':
$input['lang'] = filter_var($field['value'], FILTER_SANITIZE_STRING);
break;
case 'data[path]':
$input['path'] = filter_var($field['value'], FILTER_SANITIZE_STRING);
break;
case '__form-name__':
$input['form-name'] = filter_var($field['value'], FILTER_SANITIZE_STRING);
break;
case 'form-nonce':
$input['form-nonce'] = filter_var($field['value'], FILTER_SANITIZE_STRING); //$this->grav['uri']->param('nonce');
break;
default:
//ignore unexpected fields.
}
}
}
*/
if (!Utils::verifyNonce($input['form-nonce'], 'comments')) { if (!Utils::verifyNonce($input['form-nonce'], 'comments')) {
http_response_code(403); http_response_code(403);
return [false, 'Invalid security nonce', [$_POST, $input['form-nonce']]]; return [false, 'Invalid security nonce', [$_POST, $input['form-nonce']]];
@ -268,31 +233,138 @@ class CommentsPlugin extends Plugin
return [false, 'missing either text or title', [0, 0]]; return [false, 'missing either text or title', [0, 0]];
//return [false, $language->translate('PLUGIN_COMMENTS.FAIL'), $data]; //return [false, $language->translate('PLUGIN_COMMENTS.FAIL'), $data];
} }
$language = $this->grav['language'];
//$data = $this->getStars($id);
$data = array(
'parent_id' => $input['parent_id'],
'email' => $input['email'],
'text' => $input['text'],
'title' => $input['title'],
'name' => $input['name'],
'id' => 99,
'level' => 0,
'hash' => md5(strtolower(trim($input['email']))),
);
// sanity checks for parents // sanity checks for parents
if ($data['parent_id'] < 0) { if ($input['parent_id'] < 0) {
$data['parent_id'] = 0; $input['parent_id'] = 0;
} elseif ($data['parent_id'] > 999 ) { //TODO: Change to 'exists in list of comment ids } elseif ($input['parent_id'] > 999 ) { //TODO: Change to 'exists in list of comment ids
$data['parent_id'] = 0; $input['parent_id'] = 0;
} }
//$this->saveVoteData($id, $rating); $lang = $this->grav['language']->getLanguage();
// Set a 500 (internal server error) response code. $path = $this->grav['page']->path();
// http_response_code(500); $route = $this->grav['page']->route();
//$data = $this->getStars($id); $comment = $this->saveComment($route, $path, $input['parent_id'], $lang, $input['text'], $input['name'], $input['email'], $input['title']);
//$comments = $this->fetchComments();
$data = array(
'parent_id' => $comment['parent'],
'id' => $comment['id'],
'text' => $comment['text'],
'title' => $comment['title'],
'name' => $comment['author'],
'date' => $comment['date'],
'level' => 0,
'hash' => md5(strtolower(trim($comment['email']))),
'ADD_REPLY' => $language->translate('PLUGIN_COMMENTS.ADD_REPLY'),
'WRITTEN_ON' => $language->translate('PLUGIN_COMMENTS.WRITTEN_ON'),
'BY' => $language->translate('PLUGIN_COMMENTS.BY'),
);
return [true, $language->translate('PLUGIN_COMMENTS.SUCCESS'), $data]; return [true, $language->translate('PLUGIN_COMMENTS.SUCCESS'), $data];
} else {
// Set a 500 (internal server error) response code.
// http_response_code(500);
}
} }
/**
* Handle form processing instructions.
*
* @param Event $event
*/
public function saveComment($route, $path, $parent_id, $lang, $text, $name, $email, $title)
{
$date = date('D, d M Y H:i:s', time());
/******************************/
/** store comments with page **/
/******************************/
$localfilename = $path . '/comments.yaml';
$localfile = CompiledYamlFile::instance($localfilename);
if (file_exists($localfilename)) {
$data = $localfile->content();
$data['autoincrement']++;
} else {
$data = array(
'autoincrement' => 1,
'comments' => array()
);
}
$localid = $data['autoincrement'];
$newComment = [
'id' => $data['autoincrement'],
'parent' => $parent_id,
'lang' => $lang,
'title' => $title,
'text' => $text,
'date' => $date,
'author' => $name,
'email' => $email
];
$data['comments'][] = $newComment;
$localfile->save($data);
/**********************************/
/** store comments in index file **/
/**********************************/
$indexfilename = DATA_DIR . 'comments/index.yaml';
$indexfile = CompiledYamlFile::instance($indexfilename);
if (file_exists($indexfilename)) {
$dataIndex = $indexfile->content();
} else {
$dataIndex = array(
'comments' => array()
);
}
$dataIndex['comments'][] = [
'page' => $route,
'id' => $localid,
'parent' => $parent_id,
'lang' => $lang,
'title' => $title,
'text' => $text,
'date' => $date,
'author' => $name,
'email' => $email
];
$indexfile->save($dataIndex);
/**************************************/
/** store comments in old data files **/
/** TODO: remove as soon as admin **/
/** panel uses new index file **/
/**************************************/
$filename = DATA_DIR . 'comments';
$filename .= ($lang ? '/' . $lang : '');
$filename .= $path . '.yaml';
$file = CompiledYamlFile::instance($filename);
if (file_exists($filename)) {
$dataLegacy = $file->content();
$dataLegacy['comments'][] = [
'text' => $text,
'date' => $date,
'author' => $name,
'email' => $email
];
} else {
$dataLegacy = array(
'title' => $title,
'lang' => $lang,
'comments' => array([
'text' => $text,
'date' => $date,
'author' => $name,
'email' => $email
])
);
}
$file->save($dataLegacy);
//clear cache
$this->grav['cache']->delete($this->comments_cache_id);
return $newComment;
}
/** /**
* Handle form processing instructions. * Handle form processing instructions.
@ -319,6 +391,7 @@ class CommentsPlugin extends Plugin
$name = filter_var(urldecode($post['name']), FILTER_SANITIZE_STRING); $name = filter_var(urldecode($post['name']), FILTER_SANITIZE_STRING);
$email = filter_var(urldecode($post['email']), FILTER_SANITIZE_STRING); $email = filter_var(urldecode($post['email']), FILTER_SANITIZE_STRING);
$title = filter_var(urldecode($post['title']), FILTER_SANITIZE_STRING); $title = filter_var(urldecode($post['title']), FILTER_SANITIZE_STRING);
$parent_id = 0;
if (isset($this->grav['user'])) { if (isset($this->grav['user'])) {
$user = $this->grav['user']; $user = $this->grav['user'];
@ -329,117 +402,12 @@ class CommentsPlugin extends Plugin
} }
/** @var Language $language */ /** @var Language $language */
$language = $this->grav['language']; $lang = $this->grav['language']->getLanguage();
$lang = $language->getLanguage();
$path = $this->grav['page']->path();
$route = $this->grav['page']->route();
/******************************/ $this->saveComment($route, $path, $parent_id, $lang, $text, $name, $email, $title);
/** store comments with page **/
/******************************/
$page = $this->grav['page'];
$localfilename = $page->path() . '/comments.yaml';
$localfile = CompiledYamlFile::instance($localfilename);
if (file_exists($localfilename)) {
$data = $localfile->content();
$data['autoincrement']++;
$data['comments'][] = [
'id' => $data['autoincrement'],
'parent' => 0,
'lang' => $lang,
'title' => $title,
'text' => $text,
'date' => date('D, d M Y H:i:s', time()),
'author' => $name,
'email' => $email
];
} else {
$data = array(
'autoincrement' => 1,
'comments' => array([
'id' => 1,
'parent' => 0,
'lang' => $lang,
'title' => $title,
'text' => $text,
'date' => date('D, d M Y H:i:s', time()),
'author' => $name,
'email' => $email
])
);
}
$localfile->save($data);
$localid = $data['autoincrement'];
$data = null;
/**********************************/
/** store comments in index file **/
/**********************************/
$indexfilename = DATA_DIR . 'comments/index.yaml';
$indexfile = CompiledYamlFile::instance($indexfilename);
if (file_exists($indexfilename)) {
$data = $indexfile->content();
$data['comments'][] = [
'page' => $page->route(),
'id' => $localid,
'parent' => 0,
'lang' => $lang,
'title' => $title,
'text' => $text,
'date' => date('D, d M Y H:i:s', time()),
'author' => $name,
'email' => $email
];
} else {
$data = array(
'comments' => array([
'page' => $page->route(),
'id' => $localid,
'parent' => 0,
'lang' => $lang,
'title' => $title,
'text' => $text,
'date' => date('D, d M Y H:i:s', time()),
'author' => $name,
'email' => $email
])
);
}
$indexfile->save($data);
$data = null;
/**************************************/
/** store comments in old data files **/
/** TODO: remove as soon as admin **/
/** panel uses new index file **/
/**************************************/
$filename = DATA_DIR . 'comments';
$filename .= ($lang ? '/' . $lang : '');
$filename .= $path . '.yaml';
$file = CompiledYamlFile::instance($filename);
if (file_exists($filename)) {
$data = $file->content();
$data['comments'][] = [
'text' => $text,
'date' => date('D, d M Y H:i:s', time()),
'author' => $name,
'email' => $email
];
} else {
$data = array(
'title' => $title,
'lang' => $lang,
'comments' => array([
'text' => $text,
'date' => date('D, d M Y H:i:s', time()),
'author' => $name,
'email' => $email
])
);
}
$file->save($data);
//clear cache
$this->grav['cache']->delete($this->comments_cache_id);
break; break;
} }
@ -580,6 +548,9 @@ class CommentsPlugin extends Plugin
$levelsflat[$parent_id]['class']->addSubComment($currentChild); $levelsflat[$parent_id]['class']->addSubComment($currentChild);
} }
} }
//youngest comments first (DESC date), only root comments. Keep replies in ASC date order.
//as long as comments are not editable, it is sufficient to reverse order from comment file
$leveltree = array_reverse($leveltree, true);
//reset comment values to nested order //reset comment values to nested order
$comments = array(); $comments = array();
foreach($leveltree as $id => $comment) { foreach($leveltree as $id => $comment) {

View File

@ -1,6 +1,10 @@
de: de:
PLUGIN_COMMENTS: PLUGIN_COMMENTS:
ADD_NEW: Kommentar hinzufügen
ADD_REPLY: Antworten
ADD_COMMENT: Kommentar hinzufügen ADD_COMMENT: Kommentar hinzufügen
DELETE_COMMENT: Kommentar löschen
SUCCESS: Der Kommentar wurde erfolgreich gespeichert.
COMMENTS: Kommentare COMMENTS: Kommentare
EMAIL_NOT_CONFIGURED: Email nicht konfiguriert EMAIL_NOT_CONFIGURED: Email nicht konfiguriert
NEW_COMMENT_EMAIL_SUBJECT: 'Neuer Kommentar für %1$s' NEW_COMMENT_EMAIL_SUBJECT: 'Neuer Kommentar für %1$s'
@ -22,7 +26,11 @@ de:
en: en:
PLUGIN_COMMENTS: PLUGIN_COMMENTS:
ADD_NEW: Add a comment
ADD_REPLY: Reply
ADD_COMMENT: Add a comment ADD_COMMENT: Add a comment
DELETE_COMMENT: Delete comment
SUCCESS: Comment has been saved successfully.
COMMENTS: Comments COMMENTS: Comments
EMAIL_NOT_CONFIGURED: Email not configured EMAIL_NOT_CONFIGURED: Email not configured
NEW_COMMENT_EMAIL_SUBJECT: 'New comment on %1$s' NEW_COMMENT_EMAIL_SUBJECT: 'New comment on %1$s'

View File

@ -6,10 +6,10 @@
{% if grav.twig.comments|length %} {% if grav.twig.comments|length %}
<h3>{{'PLUGIN_COMMENTS.COMMENTS'|t}}</h3> <h3>{{'PLUGIN_COMMENTS.COMMENTS'|t}}</h3>
<a class="comment-add-new" href="#">{{'PLUGIN_COMMENTS.ADD_NEW'|t}}</a> <a class="comment-add-new" href="#"><i class="fa fa-plus" title="{{'PLUGIN_COMMENTS.ADD_NEW'|t}}"></i> {{'PLUGIN_COMMENTS.ADD_NEW'|t}}</a>
<div class="row comments"> <div class="row comments">
{% for comment in grav.twig.comments %} {% for comment in grav.twig.comments %}
<div class="comment comment-level-{{comment.level|e}}" data-Id="{{comment.id}}" > <div class="comment comment-level-{{comment.level|e}}" data-level="{{comment.level}}" data-id="{{comment.id}}" >
<div class="comment-left"> <div class="comment-left">
<a href="#"> <a href="#">
<img class="comment-object" src="https://www.gravatar.com/avatar/{{comment.email|trim|lower|md5}}?d=identicon" alt="user icon"> <img class="comment-object" src="https://www.gravatar.com/avatar/{{comment.email|trim|lower|md5}}?d=identicon" alt="user icon">
@ -18,7 +18,12 @@
<div class="comment-body"> <div class="comment-body">
<div class="comment-heading"> <div class="comment-heading">
<div class="comment-title"><h4>{{comment.title}}</h4></div> <div class="comment-title"><h4>{{comment.title}}</h4></div>
<div class="comment-reply"><a class="comment-add-reply" href="#">{{'PLUGIN_COMMENTS.ADD_REPLY'|t}}</a></div> <div class="comment-reply">
<a class="comment-add-reply" href="#"><i class="fa fa-reply" title="{{'PLUGIN_COMMENTS.ADD_REPLY'|t}}"></i> {{'PLUGIN_COMMENTS.ADD_REPLY'|t}}</a>
{% if grav.user.access.admin.super %}
<a class="comment-delete" href="#"><i class="fa fa-trash" title="{{'PLUGIN_COMMENTS.DELETE'|t}}"></i> {{'PLUGIN_COMMENTS.DELETE'|t}}</a>
{% endif %}
</div>
<div class="comment-meta">{{'PLUGIN_COMMENTS.WRITTEN_ON'|t}} {{comment.date|e}} {{'PLUGIN_COMMENTS.BY'|t}} {{comment.author}}</div> <div class="comment-meta">{{'PLUGIN_COMMENTS.WRITTEN_ON'|t}} {{comment.date|e}} {{'PLUGIN_COMMENTS.BY'|t}} {{comment.author}}</div>
</div> </div>
<div class="comment-text" > <div class="comment-text" >