-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRatingPlugin.php
534 lines (502 loc) · 17.8 KB
/
RatingPlugin.php
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
<?php
/**
* Allows users to rate discussions and comments.
*
* @todo Make links point to signin for guests
*/
class RatingPlugin extends Gdn_Plugin {
/** @var string Currently selected filter. */
protected $filter = '';
/** @var array Period filters */
protected $periodFilters = [];
/**
* Init the period filters
*
* @return void.
*/
public function __construct() {
$this->periodFilters = [
'today' => [
'Name' => t('Today'),
'Filter' => [
'd.DateInserted >=' => Gdn_Format::toDateTime(time() - 86400)
]
],
'week' => [
'Name' => t('Last Week'),
'Filter' => [
'd.DateInserted >=' => Gdn_Format::toDateTime(time() - 604800),
'd.DateInserted <=' => Gdn_Format::toDateTime(),
]
],
'month' => [
'Name' => t('Last Month'),
'Filter' => [
'd.DateInserted >=' => Gdn_Format::toDateTime(time() - 2592000),
'd.DateInserted <=' => Gdn_Format::toDateTime(),
]
],
'ever' => [
'Name' => t('All Time'),
'Filter' => []
]
];
}
/**
* Init db changes and set default comment sort.
*
* @return void.
*/
public function setup() {
$this->structure();
}
/**
* Transform Discussion/Comment Score to indexed integer column.
*
* This would make a better performance but might be destructive!
*
* @return void.
*/
public function structure() {
Gdn::config()->touch(['rating.Comments.OrderBy' => 'Score desc']);
// Replace null with zero in Score
Gdn::structure()
->table('Discussion')
->column('Score', 'int(11)', 0, 'index')
->set();
Gdn::structure()
->table('Comment')
->column('Score', 'int(11)', 0, 'index')
->set();
}
/**
* Allows changing sort order.
*
* @param SettingsController $sender Instance of the calling class.
*
* @return void.
*/
public function settingsController_rating_create($sender) {
$sender->permission('Garden.Settings.Manage');
$sender->setHighlightRoute('dashboard/settings/plugins');
$sender->setData('Title', t('Rating Settings'));
$sender->setData(
'Description',
t('This plugin allows users to rate discussions and comments and empowers the admin to sort posts based on the rating.')
);
// Save homepage in order to be able to restore it later.
// Only if it is not already discussions/top
$defaultController = Gdn::router()->getRoute('DefaultController');
if ($defaultController['Destination'] != 'discussions/top') {
Gdn::config()->saveToConfig(
'rating.OriginalDefaultController',
$defaultController['Destination']
);
}
// Choices for sort directions.
$validSortDirections = ['desc' => 'Descending', 'asc' => 'Ascending'];
// Choices for sort field.
$validSortFields = ['Score' => 'Score', 'DateInserted' => 'Date Inserted'];
// Valid period settings
$validPeriods = array_map(
function ($filter) {
return $filter['Name'];
},
$this->periodFilters
);
if ($sender->Form->authenticatedPostBack() === false) {
// If form is displayed "unposted", fill fields with config values.
$orderBy = explode(' ', Gdn::config('rating.Comments.OrderBy'));
$sortField = $orderBy[0] ?? false;
$sortDirection = $orderBy[1] ?? false;
if (array_key_exists($sortField, $validSortFields)) {
$sender->Form->setValue('SortField', $sortField);
}
if (array_key_exists($sortDirection, $validSortDirections)) {
$sender->Form->setValue('SortDirection', $sortDirection);
}
if (Gdn::router()->getRoute('DefaultController')['Destination'] == 'discussions/top') {
$sender->Form->setValue('TopHome', true);
}
$sender->Form->setValue('Period', Gdn::config('rating.Period.Default', 'ever'));
} else {
// After POST, validate input and built/save config string.
$sortField = $sender->Form->getFormValue('SortField');
$sortDirection = $sender->Form->getFormValue('SortDirection');
// Validate sort field.
if (!array_key_exists($sortField, $validSortFields)) {
$sender->Form->addError(
'Comment Sort Field must be either "Score" or "DateInserted"',
'SortField'
);
}
// Validate sort direction.
if (!array_key_exists($sortDirection, $validSortDirections)) {
$sender->Form->addError(
'Sort Direction must be either "asc" or "desc"',
'SortDirection'
);
}
// Validate period.
$period = $sender->Form->getFormValue('Period');
if (!array_key_exists($period, $validPeriods)) {
$sender->Form->addError(
'Period must be one of '.implode(', ', array_keys($validPeriods)).'.',
'Period'
);
}
// If there are no validation errors, save config setting.
if (!$sender->Form->errors()) {
Gdn::config()->saveToConfig('rating.Comments.OrderBy', $sortField.' '.$sortDirection);
Gdn::config()->saveToConfig('rating.Period.Default', $period);
if ($sender->Form->getFormValue('TopHome', false) == true) {
// Set "Top" as homepage.
Gdn::router()->setRoute(
'DefaultController',
'discussions/top',
'Internal'
);
} else {
// Restore homepage.
Gdn::router()->setRoute(
'DefaultController',
Gdn::config('rating.OriginalDefaultController', 'discussions'),
'Internal'
);
}
$sender->informMessage(
sprite('Check', 'InformSprite').t('Your settings have been saved.'),
['CssClass' => 'Dismissable AutoDismiss HasSprite']
);
}
}
$configurationModule = new ConfigurationModule($sender);
$configurationModule->initialize([
'SortField' => [
'LabelCode' => 'Comment Sort Field',
'Control' => 'radiolist',
'Items' => $validSortFields
],
'SortDirection' => [
'LabelCode' => 'Sort Direction',
'Control' => 'radiolist',
'Items' => $validSortDirections
],
'TopHome' => [
'LabelCode' => 'Set "Top" as Homepage',
'Control' => 'checkbox',
'default' => true
],
'Period' => [
'LabelCode' => 'Default time period to show',
'Control' => 'dropdown',
'Items' => $validPeriods
]
]);
$configurationModule->renderAll();
}
/**
* Add link to "Top" discussions to discussion filter.
*
* @param GardenController $sender Instance of the sending class.
*
* @return void.
*/
public function base_afterDiscussionFilters_handler($sender) {
$cssClass = 'Top';
// Change class if "Top" is current page.
if (
strtolower(Gdn::controller()->RequestMethod) == 'top' &&
strtolower(Gdn::controller()->ControllerName) == 'discussionscontroller'
) {
$cssClass .= ' Active';
}
// Insert link.
echo '<li class="', $cssClass, '">';
echo anchor(
sprite('SpTop').t('Top Rated'),
'/discussions/top/'.Gdn::config('rating.Period.Default', 'ever')
);
echo '</li>';
}
/**
* Add CSS & JS files. Do plugins permission checks.
*
* Permission is checked once per controller here so that it doesn't need
* to be done on every event fired.
*
* @param GardenController $sender Instance of the calling class.
*
* @return void.
*/
public function base_render_before($sender) {
// Include style & script.
$sender->addCssFile('rating.css', 'plugins/rating');
$sender->addJsFile('rating.js', 'plugins/rating');
// Check for adding permissions only once per page call.
if (
Gdn::session()->checkPermission(
['Plugins.Rating.Add', 'Plugins.Rating.Manage'],
false
)
) {
// Reflect permission in css class.
$cssClass = ' RatingAllowed';
$sender->addDefinition('RatingPermission', true);
} else {
$cssClass = ' RatingDisallowed';
}
$sender->CssClass .= $cssClass;
}
/**
* Helper method to print the rating snippet.
*
* @param string $postType Either "Discussion" or "Comment".
* @param integer $postID The DiscussionID/CommentID.
* @param integer $score The current score of this post.
*
* @return void
*/
public function printRatingTemplate($postType, $postID, $score) {
?>
<div class="RatingContainer Rating<?= $postType ?>" data-posttype="<?= $postType ?>" data-postid="<?= $postID ?>">
<a class="RatingUp"><?= t('▲') ?></a>
<span class="Rating" data-rating="<?= $score ?>"><?= $score ?></span>
<a class="RatingDown"><?= t('▼') ?></a>
</div>
<?php
}
/**
* Insert rating markup into discussions lists.
*
* @param GardenController $sender Instance of the calling class.
* @param mixed $args Event arguments.
*
* @return void.
*/
public function base_beforeDiscussionContent_handler($sender, $args) {
// Adding voting controls destroys table layout.
if ($sender->View == 'table') {
return;
}
$this->printRatingTemplate(
'Discussion',
$args['Discussion']->DiscussionID,
$args['Discussion']->Score
);
}
/**
* Insert rating markup into discussion.
*
* @param GardenController $sender Instance of the calling class.
* @param mixed $args Event arguments.
*
* @return void.
*/
public function base_beforeDiscussionDisplay_handler($sender, $args) {
$this->printRatingTemplate(
'Discussion',
$args['Discussion']->DiscussionID,
$args['Discussion']->Score
);
}
/**
* Insert rating markup into comment.
*
* @param GardenController $sender Instance of the calling class.
* @param mixed $args Event arguments.
*
* @return void.
*/
public function base_beforeCommentMeta_handler($sender, $args) {
$this->printRatingTemplate(
'Comment',
$args['Comment']->CommentID,
$args['Comment']->Score
);
}
/**
* Endpoint for changing a discussion/comments rating.
*
* Only called from js files. Needs parameters
* type: "discussion" (default) or "comment"
* id: The DiscussionID or CommentID
* rate: "up" (default) or "down"
* "Plugins.Rating.Add" or "Plugins.Rating.Manage" permissions needed.
*
* @param PluginController $sender Instance of the calling class.
*
* @return bool Whether Score has been updated.
*/
public function pluginController_rating_create($sender) {
// Store manage permission since it will be needed more often.
if (Gdn::session()->checkPermission('Plugins.Rating.Manage')) {
$canManage = true;
} else {
// If has neither Add nor Manage rights, break.
if (!Gdn::session()->checkPermission('Plugins.Rating.Add')) {
throw permissionException('Plugins.Rating.Add');
}
}
// Check for valid TransientKey to prevent clickbaiting.
if (!Gdn::session()->validateTransientKey(Gdn::request()->get('tk', false))) {
throw new Exception('Transient Key is invalid.');
}
// Sanity check for post id.
$postID = intval(Gdn::request()->get('id', 0));
if ($postID <= 0) {
throw new Exception('Post ID is invalid.');
}
// Get post type
if (Gdn::request()->get('type', 'Discussion') == 'Comment') {
$postType = 'Comment';
} else {
$postType = 'Discussion';
}
$modelName = $postType.'Model';
$postModel = new $modelName();
// Prevent users from voting on their own posts.
if (!$canManage) {
$post = $postModel->getID($postID);
if ($post->InsertUserID == Gdn::session()->UserID) {
return false;
}
}
// Determine rating.
if (Gdn::request()->get('rate', 'up') == 'down') {
$score = -1;
} else {
$score = 1;
}
$currentScore = $postModel->getUserScore(
$postID,
Gdn::session()->UserID
);
$newScore = $currentScore + $score;
// Ensure that users without manage permissions cannot give
// a score > 1 / < -1.
if (!$canManage && ($newScore > 1 || $newScore < -1)) {
return false;
}
// Echoes the new total score of the post so that it can be displayed.
echo $postModel->setUserScore(
$postID,
Gdn::session()->UserID,
$newScore
);
// Return true since update was successful.
return true;
}
/**
* Add new discussion list sorted by column Score.
*
* This makes use of the discussion sort feature of Vanilla 2.3. For
* versions below it would have to be implemented n another way.
*
* @param DiscussionsController $sender Instance of the calling class.
*
* @return void.
*/
public function discussionsController_top_create($sender) {
// "score" sort is removed in index(), so we have to re-insert it
// before we can add it.
$discussionModel = new DiscussionModel();
DiscussionModel::addSort(
'score',
'Top',
['Score' => 'desc', 'd.DateInserted' => 'desc']
);
foreach ($this->periodFilters as $key => $value) {
DiscussionModel::addFilter(
$key,
$value['Name'],
$value['Filter'],
'Rating'
);
}
$this->filter = $sender->RequestArgs[0] ?? Gdn::config('rating.Period.Default', 'ever');
Gdn::request()->setRequestArguments(
'get',
[
'sort' => 'score',
'filter' => $this->filter
]
);
// Add info needed for displaying a discussions page.
$sender->title(t('Top Rated'));
$sender->setData('_PagerUrl', 'discussions/top/'.$this->filter.'/{Page}');
$sender->View = 'index';
$page = $sender->RequestArgs[1] ?? '';
if ($page == 'feed.rss') {
$page = 'feed';
}
// Re-use the original discussions index view.
$sender->index($page);
}
/**
* Adapt some settings of index view.
*
* In order to re-use the discussions index view, we need to change
* a few settings a) after the index() method has been run and b) before
* the view is rendered.
*
* @param DiscussionsController $sender Instance of the calling class.
*
* @return void.
*/
public function discussionsController_render_before($sender) {
if (strtolower($sender->RequestMethod) != 'top') {
return;
}
// Change canonical url.
$sender->canonicalUrl(
url(
ConcatSep('/', 'discussions', 'top', $sender->data('_Page')),
true
)
);
// Correct feed address.
if ($sender->Head) {
$sender->Head->addRss(
url('/discussions/top/feed.rss', true),
$sender->Head->title()
);
}
// Set the breadcrumbs
$sender->setData(
'Breadcrumbs',
[['Name' => t('Top Rated'), 'Url' => '/discussions/top']]
);
}
/**
* Change comments sort order.
*
* @param CommentModel $sender Instance of the calling class.
*
* @return void.
*/
public function commentModel_afterConstruct_handler($sender) {
$sender->orderBy(Gdn::config('rating.Comments.OrderBy', 'Score desc'));
}
/**
* Add navigation links for switching between period views.
*
* @param DiscussionsController $sender Instance of the calling class.
*
* @return void.
*/
public function discussionsController_afterPageTitle_handler($sender) {
if (strtolower($sender->RequestMethod) != 'top') {
return;
}
echo '<ul class="RatingNav">';
foreach ($this->periodFilters as $key => $value) {
echo '<li';
if ($this->filter == $key) {
echo ' class="Active"';
}
echo '>', anchor($value['Name'], "/discussions/top/$key"), '</li>';
}
echo '</ul>';
}
}