forked from silverstripe/silverstripe-contentreview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSiteTreeContentReview.php
712 lines (609 loc) · 22 KB
/
SiteTreeContentReview.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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
<?php
namespace SilverStripe\ContentReview\Extensions;
use Exception;
use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\ContentReview\Jobs\ContentReviewNotificationJob;
use SilverStripe\ContentReview\Models\ContentReviewLog;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Forms\CompositeField;
use SilverStripe\Forms\DateField;
use SilverStripe\Forms\DateTimeField;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridFieldConfig;
use SilverStripe\Forms\GridField\GridFieldConfig_RecordEditor;
use SilverStripe\Forms\GridField\GridFieldDataColumns;
use SilverStripe\Forms\GridField\GridFieldSortableHeader;
use SilverStripe\Forms\HeaderField;
use SilverStripe\Forms\ListboxField;
use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\OptionsetField;
use SilverStripe\Forms\ReadonlyField;
use SilverStripe\Model\List\ArrayList;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DB;
use SilverStripe\ORM\HasManyList;
use SilverStripe\ORM\ManyManyList;
use SilverStripe\ORM\FieldType\DBDate;
use SilverStripe\ORM\FieldType\DBDatetime;
use SilverStripe\Model\List\SS_List;
use SilverStripe\Security\Group;
use SilverStripe\Security\Member;
use SilverStripe\Security\Permission;
use SilverStripe\Security\PermissionProvider;
use SilverStripe\Security\Security;
use SilverStripe\SiteConfig\SiteConfig;
use SilverStripe\View\Requirements;
use Symbiote\QueuedJobs\DataObjects\QueuedJobDescriptor;
use Symbiote\QueuedJobs\Services\QueuedJobService;
use SilverStripe\Core\Extension;
/**
* Set dates at which content needs to be reviewed and provide a report and emails to alert
* to content needing review.
*
* @property string $ContentReviewType
* @property int $ReviewPeriodDays
* @property Date $NextReviewDate
* @property string $LastEditedByName
* @property string $OwnerNames
*
* @method ManyManyList<Group> ContentReviewGroups()
* @method ManyManyList<Member> ContentReviewUsers()
* @method HasManyList<ContentReviewLog> ReviewLogs()
*
* @extends Extension<SiteTree>
*/
class SiteTreeContentReview extends Extension implements PermissionProvider
{
/**
* @var array
*/
private static $db = [
"ContentReviewType" => "Enum('Inherit, Disabled, Custom', 'Inherit')",
"ReviewPeriodDays" => "Int",
"NextReviewDate" => "Date",
"LastEditedByName" => "Varchar(255)",
"OwnerNames" => "Varchar(255)",
];
/**
* @var array
*/
private static $defaults = [
"ContentReviewType" => "Inherit",
];
/**
* @var array
*/
private static $has_many = [
"ReviewLogs" => ContentReviewLog::class,
];
/**
* @var array
*/
private static $belongs_many_many = [
"ContentReviewGroups" => Group::class,
"ContentReviewUsers" => Member::class,
];
private static array $scaffold_cms_fields_settings = [
'ignoreFields' => [
'ContentReviewType',
'ReviewPeriodDays',
'NextReviewDate',
'LastEditedByName',
'OwnerNames',
],
'ignoreRelations' => [
'ReviewLogs',
'ContentReviewGroups',
'ContentReviewUsers',
],
];
/**
* @var array
*/
private static $schedule = [
0 => "No automatic review date",
1 => "1 day",
7 => "1 week",
30 => "1 month",
60 => "2 months",
91 => "3 months",
121 => "4 months",
152 => "5 months",
183 => "6 months",
365 => "12 months",
];
/**
* @return array
*/
public static function get_schedule()
{
return Config::inst()->get(static::class, 'schedule');
}
/**
* Takes a list of groups and members and return a list of unique member.
*
* @param SS_List $groups
* @param SS_List $members
*
* @return ArrayList<Group|Member>
*/
public static function merge_owners(SS_List $groups, SS_List $members)
{
$contentReviewOwners = new ArrayList();
if ($groups->count()) {
$groupIDs = [];
foreach ($groups as $group) {
$familyIDs = $group->collateFamilyIDs();
if (is_array($familyIDs)) {
$groupIDs = array_merge($groupIDs, array_values($familyIDs ?? []));
}
}
array_unique($groupIDs ?? []);
if (count($groupIDs ?? [])) {
$groupMembers = DataObject::get(Member::class)
->where("\"Group\".\"ID\" IN (" . implode(",", $groupIDs) . ")")
->leftJoin("Group_Members", "\"Member\".\"ID\" = \"Group_Members\".\"MemberID\"")
->leftJoin('Group', "\"Group_Members\".\"GroupID\" = \"Group\".\"ID\"");
$contentReviewOwners->merge($groupMembers);
}
}
$contentReviewOwners->merge($members);
$contentReviewOwners->removeDuplicates();
return $contentReviewOwners;
}
/**
* @param FieldList $actions
*/
protected function updateCMSActions(FieldList $actions)
{
if (!$this->canBeReviewedBy(Security::getCurrentUser())) {
return;
}
Requirements::css('silverstripe/contentreview:client/dist/styles/contentreview.css');
Requirements::javascript('silverstripe/contentreview:client/dist/js/contentreview.js');
$reviewTab = LiteralField::create('ContentReviewButton', $this->owner->renderWith(__CLASS__ . '_button'));
$actions->insertAfter('MajorActions', $reviewTab);
}
/**
* Returns false if the content review have disabled.
*
* @param SiteTree $page
*
* @return null|DBDate
*/
public function getReviewDate(SiteTree $page = null)
{
if ($page === null) {
$page = $this->owner;
}
if ($page->obj('NextReviewDate')->exists()) {
return $page->obj('NextReviewDate');
}
$options = $this->owner->getOptions();
if (!$options) {
return null;
}
if (!$options->ReviewPeriodDays) {
return null;
}
// Failover to check on ReviewPeriodDays + LastEdited
$nextReviewUnixSec = strtotime(' + ' . $options->ReviewPeriodDays . ' days', DBDatetime::now()->getTimestamp());
$date = DBDate::create('NextReviewDate');
$date->setValue($nextReviewUnixSec);
return $date;
}
/**
* Get the object that have the information about the content review settings. Either:
*
* - a SiteTreeContentReview decorated object
* - the default SiteTree config
* - false if this page have it's content review disabled
*
* Will go through parents and root pages will use the site config if their setting is Inherit.
*
* @return bool|DataObject
*
* @throws Exception
*/
public function getOptions()
{
if ($this->owner->ContentReviewType == "Custom") {
return $this->owner;
}
if ($this->owner->ContentReviewType == "Disabled") {
return false;
}
$page = $this->owner;
// $page is inheriting it's settings from it's parent, find
// the first valid parent with a valid setting
while ($parent = $page->Parent()) {
// Root page, use site config
if (!$parent->exists()) {
return SiteConfig::current_site_config();
}
if ($parent->ContentReviewType == "Custom") {
return $parent;
}
if ($parent->ContentReviewType == "Disabled") {
return false;
}
$page = $parent;
}
throw new Exception("This shouldn't really happen, as per usual developer logic.");
}
/**
* @return string
*/
public function getOwnerNames()
{
$options = $this->getOptions();
$names = [];
if (!$options) {
return "";
}
foreach ($options->OwnerGroups() as $group) {
$names[] = $group->getBreadcrumbs(" > ");
}
foreach ($options->OwnerUsers() as $group) {
$names[] = $group->getName();
}
return implode(", ", $names);
}
/**
* @return null|string
*/
public function getEditorName()
{
$member = Security::getCurrentUser();
if ($member) {
return $member->getTitle();
}
return null;
}
/**
* Get all Members that are Content Owners to this page. This includes checking group
* hierarchy and adding any direct users.
*
* @return ArrayList<Group|Member>
*/
public function ContentReviewOwners()
{
return SiteTreeContentReview::merge_owners(
$this->OwnerGroups(),
$this->OwnerUsers()
);
}
/**
* @return ManyManyList<Group>
*/
public function OwnerGroups()
{
return $this->owner->getManyManyComponents("ContentReviewGroups");
}
/**
* @return ManyManyList<Member>
*/
public function OwnerUsers()
{
return $this->owner->getManyManyComponents("ContentReviewUsers");
}
/**
* @param FieldList $fields
*/
protected function updateSettingsFields(FieldList $fields)
{
if ($this->owner->hasMethod('displayContentReview') && !$this->owner->displayContentReview()) {
return;
}
Requirements::javascript('silverstripe/contentreview:client/dist/js/contentreview.js');
// Display read-only version only
if (!Permission::check("EDIT_CONTENT_REVIEW_FIELDS")) {
$schedule = SiteTreeContentReview::get_schedule();
$contentOwners = ReadonlyField::create(
"ROContentOwners",
_t(__CLASS__ . ".CONTENTOWNERS", "Content Owners"),
$this->getOwnerNames()
);
$nextReviewAt = DateField::create(
'RONextReviewDate',
_t(__CLASS__ . ".NEXTREVIEWDATE", "Next review date"),
$this->owner->NextReviewDate
);
if (!isset($schedule[$this->owner->ReviewPeriodDays])) {
$reviewFreq = ReadonlyField::create(
"ROReviewPeriodDays",
_t(__CLASS__ . ".REVIEWFREQUENCY", "Review frequency"),
$schedule[0]
);
} else {
$reviewFreq = ReadonlyField::create(
"ROReviewPeriodDays",
_t(__CLASS__ . ".REVIEWFREQUENCY", "Review frequency"),
$schedule[$this->owner->ReviewPeriodDays]
);
}
$logConfig = GridFieldConfig::create()
->addComponent(Injector::inst()->create(GridFieldSortableHeader::class))
->addComponent($logColumns = Injector::inst()->create(GridFieldDataColumns::class));
// Cast the value to the users preferred date format
$logColumns->setFieldCasting([
'Created' => DateTimeField::class . '->value',
]);
$logs = GridField::create("ROReviewNotes", "Review Notes", $this->owner->ReviewLogs(), $logConfig);
$optionsFrom = ReadonlyField::create(
"ROType",
_t(__CLASS__ . ".SETTINGSFROM", "Options are"),
$this->owner->ContentReviewType
);
$fields->addFieldsToTab("Root.ContentReview", [
$contentOwners,
$nextReviewAt->performReadonlyTransformation(),
$reviewFreq,
$optionsFrom,
$logs,
]);
return;
}
$options = [];
$options["Disabled"] = _t(__CLASS__ . ".DISABLE", "Disable content review");
$options["Inherit"] = _t(__CLASS__ . ".INHERIT", "Inherit from parent page");
$options["Custom"] = _t(__CLASS__ . ".CUSTOM", "Custom settings");
$viewersOptionsField = OptionsetField::create(
"ContentReviewType",
_t(__CLASS__ . ".OPTIONS", "Options"),
$options
);
$users = Permission::get_members_by_permission(['CMS_ACCESS_CMSMain', 'CMS_ACCESS_LeftAndMain', 'ADMIN']);
$usersMap = $users->map("ID", "Title")->toArray();
asort($usersMap);
$userField = ListboxField::create("OwnerUsers", _t(__CLASS__ . ".PAGEOWNERUSERS", "Users"), $usersMap)
->addExtraClass('custom-setting')
->setAttribute("data-placeholder", _t(__CLASS__ . ".ADDUSERS", "Add users"))
->setDescription(_t(__CLASS__ . '.OWNERUSERSDESCRIPTION', 'Page owners that are responsible for reviews'));
$groupsMap = [];
foreach (Group::get() as $group) {
$groupsMap[$group->ID] = $group->getBreadcrumbs(" > ");
}
asort($groupsMap);
$groupField = ListboxField::create("OwnerGroups", _t(__CLASS__ . ".PAGEOWNERGROUPS", "Groups"), $groupsMap)
->addExtraClass('custom-setting')
->setAttribute("data-placeholder", _t(__CLASS__ . ".ADDGROUP", "Add groups"))
->setDescription(_t(__CLASS__ . ".OWNERGROUPSDESCRIPTION", "Page owners that are responsible for reviews"));
$reviewDate = DateField::create("NextReviewDate", _t(__CLASS__ . ".NEXTREVIEWDATE", "Next review date"))
->setDescription(_t(__CLASS__ . ".NEXTREVIEWDATADESCRIPTION", "Leave blank for no review"));
$reviewFrequency = DropdownField::create(
"ReviewPeriodDays",
_t(__CLASS__ . ".REVIEWFREQUENCY", "Review frequency"),
SiteTreeContentReview::get_schedule()
)
->addExtraClass('custom-setting')
->setDescription(_t(
__CLASS__ . ".REVIEWFREQUENCYDESCRIPTION",
"The review date will be set to this far in the future whenever the page is published"
));
$notesField = GridField::create(
"ReviewNotes",
"Review Notes",
$this->owner->ReviewLogs(),
GridFieldConfig_RecordEditor::create()
);
$fields->addFieldsToTab("Root.ContentReview", [
HeaderField::create('ContentReviewHeader', _t(__CLASS__ . ".REVIEWHEADER", "Content review"), 2),
$viewersOptionsField,
CompositeField::create(
$userField,
$groupField,
$reviewDate,
$reviewFrequency
)->addExtraClass("review-settings"),
ReadonlyField::create(
"ROContentOwners",
_t(__CLASS__ . ".CONTENTOWNERS", "Content Owners"),
$this->getOwnerNames()
),
$notesField,
]);
}
/**
* Creates a ContentReviewLog and connects it to this Page.
*
* @param Member $reviewer
* @param string $message
*/
public function addReviewNote(Member $reviewer, $message)
{
$reviewLog = ContentReviewLog::create();
$reviewLog->Note = $message;
$reviewLog->ReviewerID = $reviewer->ID;
$this->owner->ReviewLogs()->add($reviewLog);
}
/**
* Advance review date to the next date based on review period or set it to null
* if there is no schedule. Returns true if date was required and false is content
* review is 'off'.
*
* @return bool
*/
public function advanceReviewDate()
{
$nextDateTimestamp = false;
$options = $this->getOptions();
if ($options && $options->ReviewPeriodDays) {
$nextDateTimestamp = strtotime(
' + ' . $options->ReviewPeriodDays . ' days',
DBDatetime::now()->getTimestamp()
);
$this->owner->NextReviewDate = DBDate::create()->setValue($nextDateTimestamp)->Format(DBDate::ISO_DATE);
$this->owner->write();
}
if ($options && $options->ReviewPeriodDays == 0) {
$this->owner->NextReviewDate = null;
$this->owner->write();
}
return (bool)$nextDateTimestamp;
}
/**
* Check if a review is due by a member for this owner.
*
* @param Member $member
*
* @return bool
*/
public function canBeReviewedBy(Member $member = null)
{
if (!$this->owner->obj('NextReviewDate')->exists()) {
return false;
}
if ($this->owner->obj('NextReviewDate')->InFuture()) {
return false;
}
$options = $this->getOptions();
if (!$options) {
return false;
}
if (!$options
// Options can be a SiteConfig with different extension applied
|| (!$options->hasExtension(__CLASS__)
&& !$options->hasExtension(ContentReviewDefaultSettings::class))
) {
return false;
}
if ($options->OwnerGroups()->count() == 0 && $options->OwnerUsers()->count() == 0) {
return false;
}
if (!$member) {
return true;
}
// Check whether this user is allowed to review the content of the page.
if ($this->owner->hasMethod("canReviewContent") && !$this->owner->canReviewContent($member)) {
return false;
}
if ($member->inGroups($options->OwnerGroups())) {
return true;
}
if ($options->OwnerUsers()->find("ID", $member->ID)) {
return true;
}
return false;
}
/**
* Set the review data from the review period, if set.
*/
protected function onBeforeWrite()
{
// Only update if DB fields have been changed
$changedFields = $this->owner->getChangedFields(true, 2);
if ($changedFields) {
$this->owner->LastEditedByName = $this->owner->getEditorName();
$this->owner->OwnerNames = $this->owner->getOwnerNames();
}
// If the user changed the type, we need to recalculate the review date.
if ($this->owner->isChanged("ContentReviewType", 2)) {
if ($this->owner->ContentReviewType == "Disabled") {
$this->setDefaultReviewDateForDisabled();
} elseif ($this->owner->ContentReviewType == "Custom") {
$this->setDefaultReviewDateForCustom();
} else {
$this->setDefaultReviewDateForInherited();
}
}
// Ensure that a inherited page always have a next review date
if ($this->owner->ContentReviewType == "Inherit" && !$this->owner->NextReviewDate) {
$this->setDefaultReviewDateForInherited();
}
// We need to update all the child pages that inherit this setting. We can only
// change children after this record has been created, otherwise the stageChildren
// method will grab all pages in the DB (this messes up unit testing)
if (!$this->owner->exists()) {
return;
}
// parent page change its review period
// && !$this->owner->isChanged('ContentReviewType', 2)
if ($this->owner->isChanged('ReviewPeriodDays', 2)) {
$nextReviewUnixSec = strtotime(
' + ' . $this->owner->ReviewPeriodDays . ' days',
DBDatetime::now()->getTimestamp()
);
$this->owner->NextReviewDate = DBDate::create()->setValue($nextReviewUnixSec)->Format('y-MM-dd');
}
}
private function setDefaultReviewDateForDisabled()
{
$this->owner->NextReviewDate = null;
}
protected function setDefaultReviewDateForCustom()
{
// Don't overwrite existing value
if ($this->owner->NextReviewDate) {
return;
}
$this->owner->NextReviewDate = null;
$nextDate = $this->getReviewDate();
if (is_object($nextDate)) {
$this->owner->NextReviewDate = $nextDate->getValue();
} else {
$this->owner->NextReviewDate = $nextDate;
}
}
protected function setDefaultReviewDateForInherited()
{
// Don't overwrite existing value
if ($this->owner->NextReviewDate) {
return;
}
$options = $this->getOptions();
$nextDate = null;
if ($options instanceof SiteTree) {
$nextDate = $this->getReviewDate($options);
} elseif ($options instanceof SiteConfig) {
$nextDate = $this->getReviewDate();
}
if (is_object($nextDate)) {
$this->owner->NextReviewDate = $nextDate->getValue();
} else {
$this->owner->NextReviewDate = $nextDate;
}
}
/**
* Provide permissions to the CMS.
*
* @return array
*/
public function providePermissions()
{
return [
"EDIT_CONTENT_REVIEW_FIELDS" => [
"name" => "Set content owners and review dates",
"category" => _t("SilverStripe\\Security\\Permission.CONTENT_CATEGORY", "Content permissions"),
"sort" => 50,
],
];
}
/**
* If the queued jobs module is installed, queue up the first job for 9am tomorrow morning
* (by default).
*/
protected function onRequireDefaultRecords()
{
if (class_exists(ContentReviewNotificationJob::class)) {
// Ensure there is not already a job queued
if (QueuedJobDescriptor::get()->filter("Implementation", ContentReviewNotificationJob::class)->first()) {
return;
}
$nextRun = Injector::inst()->create(ContentReviewNotificationJob::class);
$runHour = Config::inst()->get(ContentReviewNotificationJob::class, "first_run_hour");
$firstRunTime = date(
"Y-m-d H:i:s",
mktime($runHour ?? 0, 0, 0, date("m"), date("d") + 1, date("y"))
);
singleton(QueuedJobService::class)->queueJob(
$nextRun,
$firstRunTime
);
DB::alteration_message(sprintf("Added ContentReviewNotificationJob to run at %s", $firstRunTime));
}
}
}