Repository navigation
Expand file tree
/
Copy pathcomments.php
More file actions
450 lines (373 loc) · 13.8 KB
/
Copy pathcomments.php
File metadata and controls
450 lines (373 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
<?php
namespace Grav\Plugin;
use Grav\Common\Filesystem\Folder;
use Grav\Common\GPM\GPM;
use Grav\Common\Grav;
use Grav\Common\Page\Page;
use Grav\Common\Page\Pages;
use Grav\Common\Plugin;
use Grav\Common\Filesystem\RecursiveFolderFilterIterator;
use Grav\Common\User\User;
use Grav\Common\Utils;
use RocketTheme\Toolbox\File\File;
use RocketTheme\Toolbox\Event\Event;
use Symfony\Component\Yaml\Yaml;
class CommentsPlugin extends Plugin
{
protected $route = 'comments';
protected $enable = false;
protected $comments_cache_id;
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
'onPluginsInitialized' => ['onPluginsInitialized', 0]
];
}
/**
* Initialize form if the page has one. Also catches form processing if user posts the form.
*
* Used by Form plugin < 2.0, kept for backwards compatibility
*
* @deprecated
*/
public function onPageInitialized()
{
/** @var Page $page */
$page = $this->grav['page'];
if (!$page) {
return;
}
if ($this->enable) {
$header = $page->header();
if (!isset($header->form)) {
$header->form = $this->grav['config']->get('plugins.comments.form');
$page->header($header);
}
}
}
/**
* Add the comment form information to the page header dynamically
*
* Used by Form plugin >= 2.0
*/
public function onFormPageHeaderProcessed(Event $event)
{
$header = $event['header'];
if ($this->enable) {
if (!isset($header->form)) {
$header->form = $this->grav['config']->get('plugins.comments.form');
}
}
$event->header = $header;
}
public function onTwigSiteVariables() {
// Old way
$enabled = $this->enable;
$comments = $this->fetchComments();
$this->grav['twig']->enable_comments_plugin = $enabled;
$this->grav['twig']->comments = $comments;
// New way
$this->grav['twig']->twig_vars['enable_comments_plugin'] = $enabled;
$this->grav['twig']->twig_vars['comments'] = $comments;
}
/**
* Determine if the plugin should be enabled based on the enable_on_routes and disable_on_routes config options
*/
private function calculateEnable() {
$uri = $this->grav['uri'];
$disable_on_routes = (array) $this->config->get('plugins.comments.disable_on_routes');
$enable_on_routes = (array) $this->config->get('plugins.comments.enable_on_routes');
$path = $uri->path();
if (!in_array($path, $disable_on_routes)) {
if (in_array($path, $enable_on_routes)) {
$this->enable = true;
} else {
foreach($enable_on_routes as $route) {
if (Utils::startsWith($path, $route)) {
$this->enable = true;
break;
}
}
}
}
}
/**
* Frontend side initialization
*/
public function initializeFrontend()
{
$this->calculateEnable();
$this->enable([
'onTwigTemplatePaths' => ['onTwigTemplatePaths', 0],
]);
if ($this->enable) {
$this->enable([
'onFormProcessed' => ['onFormProcessed', 0],
'onFormPageHeaderProcessed' => ['onFormPageHeaderProcessed', 0],
'onPageInitialized' => ['onPageInitialized', 10],
'onTwigSiteVariables' => ['onTwigSiteVariables', 0]
]);
}
$cache = $this->grav['cache'];
$uri = $this->grav['uri'];
//init cache id
$this->comments_cache_id = md5('comments-data' . $cache->getKey() . '-' . $uri->url());
}
/**
* Admin side initialization
*/
public function initializeAdmin()
{
/** @var Uri $uri */
$uri = $this->grav['uri'];
$this->enable([
'onTwigTemplatePaths' => ['onTwigAdminTemplatePaths', 0],
'onAdminMenu' => ['onAdminMenu', 0],
'onDataTypeExcludeFromDataManagerPluginHook' => ['onDataTypeExcludeFromDataManagerPluginHook', 0],
]);
if (strpos((string) $uri->path(), $this->config->get('plugins.admin.route') . '/' . $this->route) === false) {
return;
}
// Require an authenticated, authorized admin before exposing any comment
// data. isAdmin() only reports that the admin *service* is registered on this
// route, never that the visitor is logged in, and the echo/exit() below runs
// during onPluginsInitialized -- before the admin plugin reaches the pages
// stage where it would render its login screen. Without this gate the exit()
// pre-empted login enforcement entirely and any anonymous visitor could read
// commenter email addresses. (GHSA-3cq9-f4pf-hq59)
$user = $this->grav['user'] ?? null;
if (!$user || !$user->authenticated
|| !($user->authorize('admin.comments') || $user->authorize('admin.super'))) {
return;
}
$page = $this->grav['uri']->param('page');
$comments = $this->getLastComments($page);
if ($page > 0) {
echo json_encode($comments);
exit();
}
$this->grav['twig']->comments = $comments;
$this->grav['twig']->pages = $this->fetchPages();
}
/**
*/
public function onPluginsInitialized()
{
if ($this->isAdmin()) {
$this->initializeAdmin();
} else {
$this->initializeFrontend();
}
}
/**
* Handle form processing instructions.
*
* @param Event $event
*/
public function onFormProcessed(Event $event)
{
$form = $event['form'];
$action = $event['action'];
$params = $event['params'];
if (!$this->active) {
return;
}
switch ($action) {
case 'addComment':
$post = isset($_POST['data']) ? $_POST['data'] : [];
$path = $this->grav['uri']->path();
$lang = filter_var(urldecode((string) $post['lang']), FILTER_SANITIZE_STRING);
$text = filter_var(urldecode((string) $post['text']), FILTER_SANITIZE_STRING);
$name = filter_var(urldecode((string) $post['name']), FILTER_SANITIZE_STRING);
$email = filter_var(urldecode((string) $post['email']), FILTER_SANITIZE_STRING);
$title = filter_var(urldecode((string) $post['title']), FILTER_SANITIZE_STRING);
if (isset($this->grav['user'])) {
$user = $this->grav['user'];
if ($user->authenticated) {
$name = $user->fullname;
$email = $user->email;
}
}
/** @var Language $language */
$language = $this->grav['language'];
$lang = $language->getLanguage();
$filename = DATA_DIR . 'comments';
$filename .= ($lang ? '/' . $lang : '');
$filename .= $path . '.yaml';
$file = File::instance($filename);
if (file_exists($filename)) {
$data = Yaml::parse($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(Yaml::dump($data));
//clear cache
$this->grav['cache']->delete($this->comments_cache_id);
break;
}
}
private function getFilesOrderedByModifiedDate($path = '') {
$files = [];
if (!$path) {
$path = DATA_DIR . 'comments';
}
if (!file_exists($path)) {
Folder::mkdir($path);
}
$dirItr = new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS);
$filterItr = new RecursiveFolderFilterIterator($dirItr);
$itr = new \RecursiveIteratorIterator($filterItr, \RecursiveIteratorIterator::SELF_FIRST);
$itrItr = new \RecursiveIteratorIterator($dirItr, \RecursiveIteratorIterator::SELF_FIRST);
$filesItr = new \RegexIterator($itrItr, '/^.+\.yaml$/i');
// Collect files if modified in the last 7 days
foreach ($filesItr as $filepath => $file) {
$modifiedDate = $file->getMTime();
$sevenDaysAgo = time() - (7 * 24 * 60 * 60);
if ($modifiedDate < $sevenDaysAgo) {
continue;
}
$files[] = (object)array(
"modifiedDate" => $modifiedDate,
"fileName" => $file->getFilename(),
"filePath" => $filepath,
"data" => Yaml::parse(file_get_contents($filepath))
);
}
// Traverse folders and recurse
foreach ($itr as $file) {
if ($file->isDir()) {
$this->getFilesOrderedByModifiedDate($file->getPath() . '/' . $file->getFilename());
}
}
// Order files by last modified date
usort($files, function($a, $b) {
return !($a->modifiedDate > $b->modifiedDate);
});
return $files;
}
private function getLastComments($page = 0) {
$number = 30;
$files = [];
$files = $this->getFilesOrderedByModifiedDate();
$comments = [];
foreach($files as $file) {
$data = Yaml::parse(file_get_contents($file->filePath));
for ($i = 0; $i < count($data['comments']); $i++) {
$commentTimestamp = \DateTime::createFromFormat('D, d M Y H:i:s', $data['comments'][$i]['date'])->getTimestamp();
$data['comments'][$i]['pageTitle'] = $data['title'];
// The absolute server path is never rendered by any template and only
// ever leaked server layout to whoever read the response.
// (GHSA-3cq9-f4pf-hq59)
$data['comments'][$i]['timestamp'] = $commentTimestamp;
}
if (count($data['comments'])) {
$comments = array_merge($comments, $data['comments']);
}
}
// Order comments by date
usort($comments, function($a, $b) {
return !($a['timestamp'] > $b['timestamp']);
});
$totalAvailable = count($comments);
$comments = array_slice($comments, $page * $number, $number);
$totalRetrieved = count($comments);
return (object)array(
"comments" => $comments,
"page" => $page,
"totalAvailable" => $totalAvailable,
"totalRetrieved" => $totalRetrieved
);
}
/**
* Return the comments associated to the current route
*/
private function fetchComments() {
$cache = $this->grav['cache'];
//search in cache
if ($comments = $cache->fetch($this->comments_cache_id)) {
return $comments;
}
$lang = $this->grav['language']->getLanguage();
$filename = $lang ? '/' . $lang : '';
$filename .= $this->grav['uri']->path() . '.yaml';
$data = $this->getDataFromFilename($filename);
$comments = isset($data['comments']) ? $data['comments'] : null;
//save to cache if enabled
$cache->save($this->comments_cache_id, $comments);
return $comments;
}
/**
* Return the latest commented pages
*/
private function fetchPages() {
$files = [];
$files = $this->getFilesOrderedByModifiedDate();
$pages = [];
foreach($files as $file) {
$pages[] = [
'title' => $file->data['title'],
'commentsCount' => count($file->data['comments']),
'lastCommentDate' => date('D, d M Y H:i:s', $file->modifiedDate)
];
}
return $pages;
}
/**
* Given a data file route, return the YAML content already parsed
*/
private function getDataFromFilename($fileRoute) {
//Single item details
$fileInstance = File::instance(DATA_DIR . 'comments/' . $fileRoute);
if (!$fileInstance->content()) {
//Item not found
return;
}
return Yaml::parse($fileInstance->content());
}
/**
* Add templates directory to twig lookup paths.
*/
public function onTwigTemplatePaths()
{
$this->grav['twig']->twig_paths[] = __DIR__ . '/templates';
}
/**
* Add plugin templates path
*/
public function onTwigAdminTemplatePaths()
{
$this->grav['twig']->twig_paths[] = __DIR__ . '/admin/templates';
}
/**
* Add navigation item to the admin plugin
*/
public function onAdminMenu()
{
$this->grav['twig']->plugins_hooked_nav['PLUGIN_COMMENTS.COMMENTS'] = ['route' => $this->route, 'icon' => 'fa-file-text'];
}
/**
* Exclude comments from the Data Manager plugin
*/
public function onDataTypeExcludeFromDataManagerPluginHook()
{
$this->grav['admin']->dataTypesExcludedFromDataManagerPlugin[] = 'comments';
}
}