Merge pull request #30 from assertchris/fix-code-style

Fixed code style
This commit is contained in:
Damian Mooyman 2015-11-02 13:11:05 +13:00
commit c50fa30a27
17 changed files with 2177 additions and 1796 deletions

View File

@ -1,46 +1,54 @@
<?php <?php
/** /**
* This is a helper class which lets us do things with content review data without subsites * This is a helper class which lets us do things with content review data without subsites
* and translatable messing our SQL queries up. * and translatable messing our SQL queries up.
* *
* Make sure any DataQuery-ies you are building are BOTH created & executed between start() * Make sure any DataQuery instances you are building are BOTH created & executed between start()
* and done() because augmentDataQueryCreate and augmentSQL happens there. * and done() because augmentDataQueryCreate and augmentSQL happens there.
*/ */
class ContentReviewCompatability { class ContentReviewCompatability
{
const SUBSITES = 0;
const SUBSITES = 0; const TRANSLATABLE = 1;
const TRANSLATABLE = 1;
/**
/** * Returns the state of other modules before compatibility mode is started.
* @return array - state before compatability mode started, to be passed into done(). *
*/ * @return array
public static function start(){ */
$compat = array( public static function start()
self::SUBSITES => null, {
self::TRANSLATABLE => null $compatibility = array(
); self::SUBSITES => null,
if(ClassInfo::exists('Subsite')){ self::TRANSLATABLE => null,
$compat[self::SUBSITES] = Subsite::$disable_subsite_filter; );
Subsite::disable_subsite_filter(true);
} if (ClassInfo::exists("Subsite")) {
if(ClassInfo::exists('Translatable')){ $compatibility[self::SUBSITES] = Subsite::$disable_subsite_filter;
$compat[self::TRANSLATABLE] = Translatable::locale_filter_enabled(); Subsite::disable_subsite_filter(true);
Translatable::disable_locale_filter(); }
}
return $compat; if (ClassInfo::exists("Translatable")) {
} $compatibility[self::TRANSLATABLE] = Translatable::locale_filter_enabled();
Translatable::disable_locale_filter();
/** }
* @param array $compat - see start()
*/ return $compatibility;
public static function done(array $compat){ }
if(class_exists('Subsite')){
Subsite::$disable_subsite_filter = $compat[self::SUBSITES]; /**
} * @param array $compatibility
if(class_exists('Translatable')){ */
Translatable::enable_locale_filter($compat[self::TRANSLATABLE]); public static function done(array $compatibility)
} {
} if (class_exists("Subsite")) {
Subsite::$disable_subsite_filter = $compatibility[self::SUBSITES];
} }
if (class_exists("Translatable")) {
Translatable::enable_locale_filter($compatibility[self::TRANSLATABLE]);
}
}
}

View File

@ -1,84 +1,94 @@
<?php <?php
/** /**
* CMSPageEditController extension to recieve the additonal action button from * CMSPageEditController extension to receive the additional action button from
* SiteTreeContentReview::updateCMSActions() * SiteTreeContentReview::updateCMSActions()
*
*/ */
class ContentReviewCMSExtension extends LeftAndMainExtension { class ContentReviewCMSExtension extends LeftAndMainExtension
{
/** /**
* * @var array
* @var array */
*/ private static $allowed_actions = array(
private static $allowed_actions = array( "reviewed",
'reviewed', "save_review",
'save_review', );
);
/**
/** * Shows a form with review notes.
* Shows a form with review notes *
* * @param array $data
* @param array $data * @param Form $form
* @param Form $form *
* @return SS_HTTPResponse * @return SS_HTTPResponse
*/ * @throws SS_HTTPResponse_Exception
public function reviewed($data, Form $form) { */
if(!isset($data['ID'])) { public function reviewed($data, Form $form)
throw new SS_HTTPResponse_Exception("No record ID", 404); {
} if (!isset($data["ID"])) {
$SQL_id = (int) $data['ID']; throw new SS_HTTPResponse_Exception('No record ID', 404);
$record = SiteTree::get()->byID($SQL_id); }
if(!$record || !$record->ID) { $id = (int) $data["ID"];
throw new SS_HTTPResponse_Exception("Bad record ID #$SQL_id", 404); $record = SiteTree::get()->byID($id);
}
if (!$record || !$record->ID) {
if(!$record->canEdit()) { throw new SS_HTTPResponse_Exception("Bad record ID #{$id}", 404);
return Security::permissionFailure($this->owner); }
}
if (!$record->canEdit()) {
$fields = new FieldList(); return Security::permissionFailure($this->owner);
$fields->push(HiddenField::create('ID', 'ID', $SQL_id)); }
$fields->push(TextareaField::create('ReviewNotes', 'Review notes'));
$fields = new FieldList();
$actions = new FieldList( $fields->push(HiddenField::create("ID", "ID", $id));
FormAction::create('save_review', 'Save') $fields->push(TextareaField::create("ReviewNotes", "Review notes"));
);
$actions = new FieldList(
$form = CMSForm::create($this->owner, "EditForm", $fields, $actions)->setHTMLID('Form_EditForm'); FormAction::create("save_review", "Save")
$form->setResponseNegotiator($this->owner->getResponseNegotiator()); );
$form->loadDataFrom($record);
$form->disableDefaultAction(); $form = CMSForm::create($this->owner, "EditForm", $fields, $actions)->setHTMLID("Form_EditForm");
$form->setResponseNegotiator($this->owner->getResponseNegotiator());
// TODO Can't merge $FormAttributes in template at the moment $form->loadDataFrom($record);
$form->setTemplate($this->owner->getTemplatesWithSuffix('LeftAndMain_EditForm')); $form->disableDefaultAction();
return $form->forTemplate();
} // TODO Can't merge $FormAttributes in template at the moment
$form->setTemplate($this->owner->getTemplatesWithSuffix("LeftAndMain_EditForm"));
/**
* Save the review notes and redirect back to the page edit form return $form->forTemplate();
* }
* @param array $data
* @param Form $form /**
* @return string - html * Save the review notes and redirect back to the page edit form.
*/ *
public function save_review($data, Form $form) { * @param array $data
if(!isset($data['ID'])) { * @param Form $form
throw new SS_HTTPResponse_Exception("No record ID", 404); *
} * @return string
$SQL_id = (int) $data['ID']; *
$page = SiteTree::get()->byID($SQL_id); * @throws SS_HTTPResponse_Exception
if($page && !$page->canEdit()) { */
return Security::permissionFailure(); public function save_review($data, Form $form)
} {
if(!$page || !$page->ID) { if (!isset($data["ID"])) {
throw new SS_HTTPResponse_Exception("Bad record ID #$SQL_id", 404); throw new SS_HTTPResponse_Exception("No record ID", 404);
} }
$page->addReviewNote(Member::currentUser(), $data['ReviewNotes']); $id = (int) $data["ID"];
$page->advanceReviewDate(); $page = SiteTree::get()->byID($id);
return $this->owner->redirect($this->owner->Link('show/'.$page->ID)); if ($page && !$page->canEdit()) {
} return Security::permissionFailure();
}
if (!$page || !$page->ID) {
throw new SS_HTTPResponse_Exception("Bad record ID #{$id}", 404);
}
$page->addReviewNote(Member::currentUser(), $data["ReviewNotes"]);
$page->advanceReviewDate();
return $this->owner->redirect($this->owner->Link("show/" . $page->ID));
}
} }

View File

@ -1,107 +1,121 @@
<?php <?php
/** /**
* This extensions add a default schema for new pages and pages without a content review setting * This extensions add a default schema for new pages and pages without a content
* * review setting.
*
* @property int $ReviewPeriodDays
*/ */
class ContentReviewDefaultSettings extends DataExtension { class ContentReviewDefaultSettings extends DataExtension
{
/** /**
* * @var array
* @var array */
*/ private static $db = array(
private static $db = array( "ReviewPeriodDays" => "Int",
"ReviewPeriodDays" => "Int", );
);
/**
/** *
* * @var array
* @var array */
*/ private static $many_many = array(
private static $many_many = array( "ContentReviewGroups" => "Group",
'ContentReviewGroups' => 'Group', "ContentReviewUsers" => "Member",
'ContentReviewUsers' => 'Member' );
);
/**
/** *
* * @return string
* @return string */
*/ public function getOwnerNames()
public function getOwnerNames() { {
$names = array(); $names = array();
foreach($this->OwnerGroups() as $group) {
$names[] = $group->getBreadcrumbs(' > '); foreach ($this->OwnerGroups() as $group) {
} $names[] = $group->getBreadcrumbs(" > ");
}
foreach($this->OwnerUsers() as $group) {
$names[] = $group->getName(); foreach ($this->OwnerUsers() as $group) {
} $names[] = $group->getName();
return implode(', ', $names); }
}
return implode(", ", $names);
/** }
* @return ManyManyList
*/ /**
public function OwnerGroups() { * @return ManyManyList
return $this->owner->getManyManyComponents('ContentReviewGroups'); */
} public function OwnerGroups()
{
/** return $this->owner->getManyManyComponents("ContentReviewGroups");
* @return ManyManyList }
*/
public function OwnerUsers() { /**
return $this->owner->getManyManyComponents('ContentReviewUsers'); * @return ManyManyList
} */
public function OwnerUsers()
/** {
* return $this->owner->getManyManyComponents("ContentReviewUsers");
* @param \FieldList $fields }
*/
public function updateCMSFields(\FieldList $fields) { /**
*
$helpText = LiteralField::create('ContentReviewHelp', _t('ContentReview.DEFAULTSETTINGSHELP', 'These content review ' * @param FieldList $fields
. 'settings will apply to all pages that does not have specific Content Review schedule.')); */
$fields->addFieldToTab('Root.ContentReview', $helpText); public function updateCMSFields(FieldList $fields)
{
$reviewFrequency = DropdownField::create("ReviewPeriodDays", _t("ContentReview.REVIEWFREQUENCY", "Review frequency"), SiteTreeContentReview::get_schedule()) $helpText = LiteralField::create("ContentReviewHelp", _t("ContentReview.DEFAULTSETTINGSHELP", "These content review settings will apply to all pages that does not have specific Content Review schedule."));
->setDescription(_t('ContentReview.REVIEWFREQUENCYDESCRIPTION', 'The review date will be set to this far in the future whenever the page is published'));
$fields->addFieldToTab("Root.ContentReview", $helpText);
$fields->addFieldToTab('Root.ContentReview', $reviewFrequency);
$reviewFrequency = DropdownField::create("ReviewPeriodDays", _t("ContentReview.REVIEWFREQUENCY", "Review frequency"), SiteTreeContentReview::get_schedule())
$users = Permission::get_members_by_permission(array("CMS_ACCESS_CMSMain", "ADMIN")); ->setDescription(_t("ContentReview.REVIEWFREQUENCYDESCRIPTION", "The review date will be set to this far in the future whenever the page is published"));
$usersMap = $users->map('ID', 'Title')->toArray(); $fields->addFieldToTab("Root.ContentReview", $reviewFrequency);
asort($usersMap);
$users = Permission::get_members_by_permission(array(
$userField = ListboxField::create('OwnerUsers', _t("ContentReview.PAGEOWNERUSERS", "Users"), $usersMap) "CMS_ACCESS_CMSMain",
->setMultiple(true) "ADMIN",
->setAttribute('data-placeholder', _t('ContentReview.ADDUSERS', 'Add users')) ));
->setDescription(_t('ContentReview.OWNERUSERSDESCRIPTION', 'Page owners that are responsible for reviews'));
$fields->addFieldToTab('Root.ContentReview', $userField); $usersMap = $users->map("ID", "Title")->toArray();
asort($usersMap);
$groupsMap = array();
foreach(Group::get() as $group) { $userField = ListboxField::create("OwnerUsers", _t("ContentReview.PAGEOWNERUSERS", "Users"), $usersMap)
// Listboxfield values are escaped, use ASCII char instead of &raquo; ->setMultiple(true)
$groupsMap[$group->ID] = $group->getBreadcrumbs(' > '); ->setAttribute("data-placeholder", _t("ContentReview.ADDUSERS", "Add users"))
} ->setDescription(_t("ContentReview.OWNERUSERSDESCRIPTION", "Page owners that are responsible for reviews"));
asort($groupsMap);
$fields->addFieldToTab("Root.ContentReview", $userField);
$groupField = ListboxField::create('OwnerGroups', _t("ContentReview.PAGEOWNERGROUPS", "Groups"), $groupsMap)
->setMultiple(true) $groupsMap = array();
->setAttribute('data-placeholder', _t('ContentReview.ADDGROUP', 'Add groups'))
->setDescription(_t('ContentReview.OWNERGROUPSDESCRIPTION', 'Page owners that are responsible for reviews')); foreach (Group::get() as $group) {
$fields->addFieldToTab('Root.ContentReview', $groupField); // Listboxfield values are escaped, use ASCII char instead of &raquo;
} $groupsMap[$group->ID] = $group->getBreadcrumbs(" > ");
}
/**
* Get all Members that are default Content Owners asort($groupsMap);
*
* This includes checking group hierarchy and adding any direct users $groupField = ListboxField::create("OwnerGroups", _t("ContentReview.PAGEOWNERGROUPS", "Groups"), $groupsMap)
* ->setMultiple(true)
* @return \ArrayList ->setAttribute("data-placeholder", _t("ContentReview.ADDGROUP", "Add groups"))
*/ ->setDescription(_t("ContentReview.OWNERGROUPSDESCRIPTION", "Page owners that are responsible for reviews"));
public function ContentReviewOwners() {
return new ArrayList(); $fields->addFieldToTab("Root.ContentReview", $groupField);
return SiteTreeContentReview::merge_owners($this->OwnerGroups(), $this->OwnerUsers()); }
}
/**
* Get all Members that are default Content Owners. This includes checking group hierarchy
* and adding any direct users.
*
* @return ArrayList
*/
public function ContentReviewOwners()
{
return new ArrayList();
return SiteTreeContentReview::merge_owners($this->OwnerGroups(), $this->OwnerUsers());
}
} }

View File

@ -1,17 +1,14 @@
<?php <?php
/** /**
* Description of GroupContentReview * Description of GroupContentReview.
*
* @codeCoverageIgnore
*/ */
class ContentReviewOwner extends DataExtension { class ContentReviewOwner extends DataExtension
{
/** /**
* * @var array
* @var array */
*/ private static $many_many = array(
private static $many_many = array( "SiteTreeContentReview" => "SiteTree",
"SiteTreeContentReview" => "SiteTree" );
);
} }

View File

@ -1,537 +1,586 @@
<?php <?php
/** /**
* Set dates at which content needs to be reviewed and provide * Set dates at which content needs to be reviewed and provide a report and emails to alert
* a report and emails to alert to content needing review * to content needing review.
* *
* @package contentreview * @property string $ContentReviewType
* @property int $ReviewPeriodDays
* @property Date $NextReviewDate
* @property string $LastEditedByName
* @property string $OwnerNames
*
* @method DataList ReviewLogs()
* @method DataList ContentReviewGroups()
* @method DataList ContentReviewUsers()
*/ */
class SiteTreeContentReview extends DataExtension implements PermissionProvider { class SiteTreeContentReview extends DataExtension implements PermissionProvider
{
/**
* @var array
*/
private static $db = array(
"ContentReviewType" => "Enum('Inherit, Disabled, Custom', 'Inherit')",
"ReviewPeriodDays" => "Int",
"NextReviewDate" => "Date",
"LastEditedByName" => "Varchar(255)",
"OwnerNames" => "Varchar(255)",
);
/** /**
* * @var array
* @var array */
*/ private static $defaults = array(
private static $db = array( "ContentReviewType" => "Inherit",
"ContentReviewType" => "Enum('Inherit, Disabled, Custom', 'Inherit')", );
"ReviewPeriodDays" => "Int",
"NextReviewDate" => "Date",
'LastEditedByName' => 'Varchar(255)',
'OwnerNames' => 'Varchar(255)'
);
/**
/** * @var array
* */
* @var array private static $has_many = array(
*/ "ReviewLogs" => "ContentReviewLog",
private static $defaults = array( );
'ContentReviewType' => 'Inherit'
);
/**
*
* @var array
*/
private static $has_many = array(
'ReviewLogs' => 'ContentReviewLog'
);
/** /**
* * @var array
* @var array */
*/ private static $belongs_many_many = array(
private static $belongs_many_many = array( "ContentReviewGroups" => "Group",
'ContentReviewGroups' => 'Group', "ContentReviewUsers" => "Member",
'ContentReviewUsers' => 'Member' );
);
/**
*
* @var array
*/
private static $schedule = array(
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 self::$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
*/
public static function merge_owners(SS_List $groups, SS_List $members) {
$contentReviewOwners = new ArrayList();
if($groups->count()) {
$groupIDs = array();
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')->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
*/
public function updateCMSActions(\FieldList $actions) {
if($this->canBeReviewedBy(Member::currentUser())) {
$reviewAction = FormAction::create('reviewed', _t('ContentReview.BUTTONREVIEWED', 'Content reviewed'))
->setAttribute('data-icon', 'pencil')
->setAttribute('data-text-alternate', _t('ContentReview.BUTTONREVIEWED', 'Content reviewed'));
$actions->push($reviewAction);
}
}
/**
*
* @param SiteTree $page
* @return Date | false - returns false if the content review have disabled
*/
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 false;
}
if(!$options->ReviewPeriodDays) {
return false;
}
// Failover to check on ReviewPeriodDays + LastEdited
$nextReviewUnixSec = strtotime(' + '.$options->ReviewPeriodDays . ' days', SS_Datetime::now()->format('U'));
$date = Date::create('NextReviewDate');
$date->setValue(date('Y-m-d H:i:s', $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 siteconfig
* if their setting is Inherit.
*
* @return DataObject or false if no settings found
*/
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 siteconfig
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 = array();
if(!$options) {
return '';
}
foreach($options->OwnerGroups() as $group) {
$names[] = $group->getBreadcrumbs(' > ');
}
foreach($options->OwnerUsers() as $group) {
$names[] = $group->getName();
}
return implode(', ', $names);
}
/** /**
* * @var array
* @return string */
*/ private static $schedule = array(
public function getEditorName() { 0 => "No automatic review date",
$member = Member::currentUser(); 1 => "1 day",
if($member) { 7 => "1 week",
return $member->FirstName .' '. $member->Surname; 30 => "1 month",
} 60 => "2 months",
return null; 91 => "3 months",
} 121 => "4 months",
152 => "5 months",
/** 183 => "6 months",
* Get all Members that are Content Owners to this page 365 => "12 months",
* );
* This includes checking group hierarchy and adding any direct users
*
* @return \ArrayList
*/
public function ContentReviewOwners() {
return SiteTreeContentReview::merge_owners($this->OwnerGroups(), $this->OwnerUsers());
}
/**
* @return ManyManyList
*/
public function OwnerGroups() {
return $this->owner->getManyManyComponents('ContentReviewGroups');
}
/**
* @return ManyManyList
*/
public function OwnerUsers() {
return $this->owner->getManyManyComponents('ContentReviewUsers');
}
/** /**
* * @return array
* @param FieldList $fields */
* @return void public static function get_schedule()
*/ {
public function updateSettingsFields(FieldList $fields) { return self::$schedule;
}
Requirements::javascript('contentreview/javascript/contentreview.js');
// Display read-only version only
if(!Permission::check("EDIT_CONTENT_REVIEW_FIELDS")) {
$schedule = self::get_schedule();
$contentOwners = ReadonlyField::create('ROContentOwners', _t('ContentReview.CONTENTOWNERS', 'Content Owners'), $this->getOwnerNames());
$nextReviewAt = DateField::create('RONextReviewDate', _t("ContentReview.NEXTREVIEWDATE", "Next review date"), $this->owner->NextReviewDate);
if(!isset($schedule[$this->owner->ReviewPeriodDays])) {
$reviewFreq = ReadonlyField::create("ROReviewPeriodDays", _t("ContentReview.REVIEWFREQUENCY", "Review frequency"), $schedule[0]);
} else {
$reviewFreq = ReadonlyField::create("ROReviewPeriodDays", _t("ContentReview.REVIEWFREQUENCY", "Review frequency"), $schedule[$this->owner->ReviewPeriodDays]);
}
$logConfig = GridFieldConfig::create()
->addComponent(new GridFieldSortableHeader())
->addComponent($logColumns = new GridFieldDataColumns());
// Cast the value to the users prefered date format
$logColumns->setFieldCasting(array(
'Created' => 'DateTimeField->value'
));
$logs = GridField::create('ROReviewNotes', 'Review Notes', $this->owner->ReviewLogs(), $logConfig);
$optionsFrom = ReadonlyField::create('ROType', _t('ContentReview.SETTINGSFROM', "Options are"), $this->owner->ContentReviewType);
$fields->addFieldsToTab("Root.ContentReview", array(
$contentOwners,
$nextReviewAt->performReadonlyTransformation(),
$reviewFreq,
$optionsFrom,
$logs
));
return;
}
$options = array();
$options["Disabled"] = _t('ContentReview.DISABLE', "Disable content review");
$options["Inherit"] = _t('ContentReview.INHERIT', "Inherit from parent page");
$options["Custom"] = _t('ContentReview.CUSTOM', "Custom settings");
$viewersOptionsField = OptionsetField::create("ContentReviewType", _t('ContentReview.OPTIONS', "Options"), $options);
$users = Permission::get_members_by_permission(array("CMS_ACCESS_CMSMain", "ADMIN"));
$usersMap = $users->map('ID', 'Title')->toArray();
asort($usersMap);
$userField = ListboxField::create('OwnerUsers', _t("ContentReview.PAGEOWNERUSERS", "Users"), $usersMap)
->setMultiple(true)
->setAttribute('data-placeholder', _t('ContentReview.ADDUSERS', 'Add users'))
->setDescription(_t('ContentReview.OWNERUSERSDESCRIPTION', 'Page owners that are responsible for reviews'));
$groupsMap = array(); /**
foreach(Group::get() as $group) { * Takes a list of groups and members and return a list of unique member.
// Listboxfield values are escaped, use ASCII char instead of &raquo; *
$groupsMap[$group->ID] = $group->getBreadcrumbs(' > '); * @param SS_List $groups
} * @param SS_List $members
asort($groupsMap); *
* @return ArrayList
$groupField = ListboxField::create('OwnerGroups', _t("ContentReview.PAGEOWNERGROUPS", "Groups"), $groupsMap) */
->setMultiple(true) public static function merge_owners(SS_List $groups, SS_List $members)
->setAttribute('data-placeholder', _t('ContentReview.ADDGROUP', 'Add groups')) {
->setDescription(_t('ContentReview.OWNERGROUPSDESCRIPTION', 'Page owners that are responsible for reviews')); $contentReviewOwners = new ArrayList();
$reviewDate = DateField::create("NextReviewDate", _t("ContentReview.NEXTREVIEWDATE", "Next review date"))
->setConfig('showcalendar', true)
->setConfig('dateformat', 'yyyy-MM-dd')
->setConfig('datavalueformat', 'yyyy-MM-dd')
->setDescription(_t('ContentReview.NEXTREVIEWDATADESCRIPTION', 'Leave blank for no review'));
$reviewFrequency = DropdownField::create("ReviewPeriodDays", _t("ContentReview.REVIEWFREQUENCY", "Review frequency"), self::get_schedule())
->setDescription(_t('ContentReview.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());
$schedule = self::get_schedule();
$fields->addFieldsToTab("Root.ContentReview", array(
new HeaderField(_t('ContentReview.REVIEWHEADER', "Content review"), 2),
$viewersOptionsField,
CompositeField::create(
$userField,
$groupField,
$reviewDate,
$reviewFrequency
)->addExtraClass('custom-settings'),
ReadonlyField::create('ROContentOwners', _t('ContentReview.CONTENTOWNERS', 'Content Owners'), $this->getOwnerNames()),
ReadonlyField::create('RONextReviewDate', _t("ContentReview.NEXTREVIEWDATE", "Next review date"), $this->owner->NextReviewDate),
$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
*
* @return bool - returns true if date was set and false is content review is 'off'
*/
public function advanceReviewDate() {
$options = $this->getOptions();
$nextDate = false;
if($options && $options->ReviewPeriodDays) {
$nextDate = date('Y-m-d', strtotime('+ '.$options->ReviewPeriodDays.' days', SS_Datetime::now()->format('U')));
}
$this->owner->NextReviewDate = $nextDate;
$this->owner->write();
return (bool)$nextDate;
}
/**
* Check if a review is due by a member for this owner
*
* @param Member $member
* @return boolean
*/
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->OwnerGroups()->count() == 0 && $options->OwnerUsers()->count() == 0) {
return false;
}
// This content should be reviewed by someone
if(!$member) {
return true;
}
if($member->inGroups($options->OwnerGroups())) {
return true;
}
if($options->OwnerUsers()->find('ID', $member->ID)) {
return true;
}
return false;
}
/** if ($groups->count()) {
* Set the review data from the review period, if set. $groupIDs = array();
*/
public function onBeforeWrite() {
$this->owner->LastEditedByName=$this->owner->getEditorName();
$this->owner->OwnerNames = $this->owner->getOwnerNames();
// If the user changed the Type, we need to recalculate the
// Next review date
if($this->owner->isChanged('ContentReviewType', 2)) {
// Changed to Disabled
if($this->owner->ContentReviewType == 'Disabled') {
$this->setDefaultReviewDateForDisabled();
// Changed to Custom
} elseif($this->owner->ContentReviewType == 'Custom') {
$this->setDefaultReviewDateForCustom();
// Changed to Inherit
} else {
$this->setDefaultReviewDateForInherited();
}
}
// Ensure that a inherited page always have a next review date
if($this->owner->ContentReviewType == 'Inherit' && !$this->owner->NextReviewDate) {
$this->setDefaultReviewDateForInherited();
}
// Oh yey.. now 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 unittesting)
if(!$this->owner->exists()) {
return;
}
// parent page change it's review period
// && !$this->owner->isChanged('ContentReviewType', 2)
if($this->owner->isChanged('ReviewPeriodDays', 2)) {
$nextReviewUnixSec = strtotime(' + '.$this->owner->ReviewPeriodDays . ' days', SS_Datetime::now()->format('U'));
$this->owner->NextReviewDate = date('Y-m-d', $nextReviewUnixSec);
}
//
if($this->owner->isChanged('NextReviewDate', 2)) {
$c = ContentReviewCompatability::start();
$children = $this->owner->stageChildren(true)->filter('ContentReviewType', 'Inherit');
foreach($children as $child) {
$child->NextReviewDate = $this->owner->NextReviewDate;
$child->write();
}
ContentReviewCompatability::done($c);
}
}
/**
*
*/
private function setDefaultReviewDateForDisabled() {
$this->owner->NextReviewDate = null;
}
/**
*
*/
protected function setDefaultReviewDateForCustom() {
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() {
$options = $this->getOptions();
$nextDate = null;
// Set the review date to be the same as the parents reviewdate
if($options && $this->owner->parent()->exists()) {
$nextDate = $this->getReviewDate($this->owner->parent());
// Use the defualt settings
} 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 array(
"EDIT_CONTENT_REVIEW_FIELDS" => array(
'name' => "Set content owners and review dates",
'category' => _t('Permissions.CONTENT_CATEGORY', 'Content permissions'),
'sort' => 50
)
);
}
/** foreach ($groups as $group) {
* If the queuedjobs module is installed, queue up the first job for 9am tomorrow morning (by default) $familyIDs = $group->collateFamilyIDs();
*/
public function requireDefaultRecords() {
if(class_exists('ContentReviewNotificationJob')) {
// Ensure there is not already a job queued
if(QueuedJobDescriptor::get()->filter('Implementation', 'ContentReviewNotificationJob')->first()) return;
$nextRun = new ContentReviewNotificationJob(); if (is_array($familyIDs)) {
$runHour = Config::inst()->get('ContentReviewNotificationJob', 'first_run_hour'); $groupIDs = array_merge($groupIDs, array_values($familyIDs));
$firstRunTime = date('Y-m-d H:i:s', mktime($runHour, 0, 0, date("m"), date("d")+1, date("y"))); }
}
singleton('QueuedJobService')->queueJob( array_unique($groupIDs);
$nextRun,
$firstRunTime
);
DB::alteration_message(sprintf('Added ContentReviewNotificationJob to run at %s', $firstRunTime)); if (count($groupIDs)) {
} $groupMembers = DataObject::get("Member")->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
*/
public function updateCMSActions(FieldList $actions)
{
if ($this->canBeReviewedBy(Member::currentUser())) {
$reviewAction = FormAction::create("reviewed", _t("ContentReview.BUTTONREVIEWED", "Content reviewed"))
->setAttribute("data-icon", "pencil")
->setAttribute("data-text-alternate", _t("ContentReview.BUTTONREVIEWED", "Content reviewed"));
$actions->push($reviewAction);
}
}
/**
* Returns false if the content review have disabled.
*
* @param SiteTree $page
*
* @return bool|Date
*/
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 false;
}
if (!$options->ReviewPeriodDays) {
return false;
}
// Failover to check on ReviewPeriodDays + LastEdited
$nextReviewUnixSec = strtotime(" + " . $options->ReviewPeriodDays . " days", SS_Datetime::now()->format("U"));
$date = Date::create("NextReviewDate");
$date->setValue(date("Y-m-d H:i:s", $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 = array();
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 = Member::currentUser();
if ($member) {
return $member->FirstName . " " . $member->Surname;
}
return null;
}
/**
* Get all Members that are Content Owners to this page. This includes checking group
* hierarchy and adding any direct users.
*
* @return ArrayList
*/
public function ContentReviewOwners()
{
return SiteTreeContentReview::merge_owners(
$this->OwnerGroups(),
$this->OwnerUsers()
);
}
/**
* @return ManyManyList
*/
public function OwnerGroups()
{
return $this->owner->getManyManyComponents("ContentReviewGroups");
}
/**
* @return ManyManyList
*/
public function OwnerUsers()
{
return $this->owner->getManyManyComponents("ContentReviewUsers");
}
/**
* @param FieldList $fields
*/
public function updateSettingsFields(FieldList $fields)
{
Requirements::javascript("contentreview/javascript/contentreview.js");
// Display read-only version only
if (!Permission::check("EDIT_CONTENT_REVIEW_FIELDS")) {
$schedule = self::get_schedule();
$contentOwners = ReadonlyField::create("ROContentOwners", _t("ContentReview.CONTENTOWNERS", "Content Owners"), $this->getOwnerNames());
$nextReviewAt = DateField::create('RONextReviewDate', _t("ContentReview.NEXTREVIEWDATE", "Next review date"), $this->owner->NextReviewDate);
if (!isset($schedule[$this->owner->ReviewPeriodDays])) {
$reviewFreq = ReadonlyField::create("ROReviewPeriodDays", _t("ContentReview.REVIEWFREQUENCY", "Review frequency"), $schedule[0]);
} else {
$reviewFreq = ReadonlyField::create("ROReviewPeriodDays", _t("ContentReview.REVIEWFREQUENCY", "Review frequency"), $schedule[$this->owner->ReviewPeriodDays]);
}
$logConfig = GridFieldConfig::create()
->addComponent(new GridFieldSortableHeader())
->addComponent($logColumns = new GridFieldDataColumns());
// Cast the value to the users preferred date format
$logColumns->setFieldCasting(array(
"Created" => "DateTimeField->value",
));
$logs = GridField::create("ROReviewNotes", "Review Notes", $this->owner->ReviewLogs(), $logConfig);
$optionsFrom = ReadonlyField::create("ROType", _t("ContentReview.SETTINGSFROM", "Options are"), $this->owner->ContentReviewType);
$fields->addFieldsToTab("Root.ContentReview", array(
$contentOwners,
$nextReviewAt->performReadonlyTransformation(),
$reviewFreq,
$optionsFrom,
$logs,
));
return;
}
$options = array();
$options["Disabled"] = _t("ContentReview.DISABLE", "Disable content review");
$options["Inherit"] = _t("ContentReview.INHERIT", "Inherit from parent page");
$options["Custom"] = _t("ContentReview.CUSTOM", "Custom settings");
$viewersOptionsField = OptionsetField::create("ContentReviewType", _t("ContentReview.OPTIONS", "Options"), $options);
$users = Permission::get_members_by_permission(array("CMS_ACCESS_CMSMain", "ADMIN"));
$usersMap = $users->map("ID", "Title")->toArray();
asort($usersMap);
$userField = ListboxField::create("OwnerUsers", _t("ContentReview.PAGEOWNERUSERS", "Users"), $usersMap)
->setMultiple(true)
->setAttribute("data-placeholder", _t("ContentReview.ADDUSERS", "Add users"))
->setDescription(_t('ContentReview.OWNERUSERSDESCRIPTION', 'Page owners that are responsible for reviews'));
$groupsMap = array();
foreach (Group::get() as $group) {
$groupsMap[$group->ID] = $group->getBreadcrumbs(" > ");
}
asort($groupsMap);
$groupField = ListboxField::create("OwnerGroups", _t("ContentReview.PAGEOWNERGROUPS", "Groups"), $groupsMap)
->setMultiple(true)
->setAttribute("data-placeholder", _t("ContentReview.ADDGROUP", "Add groups"))
->setDescription(_t("ContentReview.OWNERGROUPSDESCRIPTION", "Page owners that are responsible for reviews"));
$reviewDate = DateField::create("NextReviewDate", _t("ContentReview.NEXTREVIEWDATE", "Next review date"))
->setConfig("showcalendar", true)
->setConfig("dateformat", "yyyy-MM-dd")
->setConfig("datavalueformat", "yyyy-MM-dd")
->setDescription(_t("ContentReview.NEXTREVIEWDATADESCRIPTION", "Leave blank for no review"));
$reviewFrequency = DropdownField::create("ReviewPeriodDays", _t("ContentReview.REVIEWFREQUENCY", "Review frequency"), self::get_schedule())
->setDescription(_t("ContentReview.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", array(
new HeaderField(_t("ContentReview.REVIEWHEADER", "Content review"), 2),
$viewersOptionsField,
CompositeField::create(
$userField,
$groupField,
$reviewDate,
$reviewFrequency
)->addExtraClass("custom-settings"),
ReadonlyField::create("ROContentOwners", _t("ContentReview.CONTENTOWNERS", "Content Owners"), $this->getOwnerNames()),
ReadonlyField::create("RONextReviewDate", _t("ContentReview.NEXTREVIEWDATE", "Next review date"), $this->owner->NextReviewDate),
$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()
{
$nextDate = false;
$options = $this->getOptions();
if ($options && $options->ReviewPeriodDays) {
$nextDate = date('Y-m-d', strtotime('+ ' . $options->ReviewPeriodDays . ' days', SS_Datetime::now()->format('U')));
$this->owner->NextReviewDate = $nextDate;
$this->owner->write();
}
return (bool) $nextDate;
}
/**
* 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->OwnerGroups()->count() == 0 && $options->OwnerUsers()->count() == 0) {
return false;
}
if (!$member) {
return true;
}
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.
*/
public function onBeforeWrite()
{
$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 it's review period
// && !$this->owner->isChanged('ContentReviewType', 2)
if ($this->owner->isChanged("ReviewPeriodDays", 2)) {
$nextReviewUnixSec = strtotime(" + " . $this->owner->ReviewPeriodDays . " days", SS_Datetime::now()->format("U"));
$this->owner->NextReviewDate = date("Y-m-d", $nextReviewUnixSec);
}
//
if ($this->owner->isChanged("NextReviewDate", 2)) {
$children = $this->owner->stageChildren(true)->filter("ContentReviewType", "Inherit");
$compatibility = ContentReviewCompatability::start();
foreach ($children as $child) {
$child->NextReviewDate = $this->owner->NextReviewDate;
$child->write();
}
ContentReviewCompatability::done($compatibility);
}
}
private function setDefaultReviewDateForDisabled()
{
$this->owner->NextReviewDate = null;
}
protected function setDefaultReviewDateForCustom()
{
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()
{
$options = $this->getOptions();
$nextDate = null;
if ($options && $this->owner->parent()->exists()) {
$nextDate = $this->getReviewDate($this->owner->parent());
} 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 array(
"EDIT_CONTENT_REVIEW_FIELDS" => array(
"name" => "Set content owners and review dates",
"category" => _t("Permissions.CONTENT_CATEGORY", "Content permissions"),
"sort" => 50,
),
);
}
/**
* If the queued jobs module is installed, queue up the first job for 9am tomorrow morning
* (by default).
*/
public function requireDefaultRecords()
{
if (class_exists("ContentReviewNotificationJob")) {
// Ensure there is not already a job queued
if (QueuedJobDescriptor::get()->filter("Implementation", "ContentReviewNotificationJob")->first()) {
return;
}
$nextRun = new ContentReviewNotificationJob();
$runHour = Config::inst()->get("ContentReviewNotificationJob", "first_run_hour");
$firstRunTime = date("Y-m-d H:i:s", mktime($runHour, 0, 0, date("m"), date("d") + 1, date("y")));
singleton("QueuedJobService")->queueJob(
$nextRun,
$firstRunTime
);
DB::alteration_message(sprintf("Added ContentReviewNotificationJob to run at %s", $firstRunTime));
}
}
} }

View File

@ -1,82 +1,106 @@
<?php <?php
if(!class_exists('AbstractQueuedJob')) { if (!class_exists("AbstractQueuedJob")) {
return; return;
} }
/** /**
* Class ContentReviewNotificationJob * Allows the content review module to use the optional queued jobs module to automatically
* * process content review emails. If the module isn't installed, nothing is done - SilverStripe
* Allows the contentreview module to use the optional queuedjobs module to automatically process content review emails. * will never include this class declaration.
* If the module isn't installed, nothing is done - SilverStripe will never include this class declaration.
* *
* If the module is installed, it will create a new job to be processed once every day by default. * If the module is installed, it will create a new job to be processed once every day by default.
* *
* @see https://github.com/silverstripe-australia/silverstripe-queuedjobs * @see https://github.com/silverstripe-australia/silverstripe-queuedjobs
*/ */
class ContentReviewNotificationJob extends AbstractQueuedJob implements QueuedJob { class ContentReviewNotificationJob extends AbstractQueuedJob implements QueuedJob
/** {
* @var int The hour that the first job will be created at (for the next day). All other jobs should be triggered /**
* around this time too, as the next generation is queued when this job is run. * The hour that the first job will be created at (for the next day). All other jobs should
* @config * be triggered around this time too, as the next generation is queued when this job is run.
*/ *
private static $first_run_hour = 9; * @var int
*
* @config
*/
private static $first_run_hour = 9;
/** /**
* @var int The hour at which to run these jobs * The hour at which to run these jobs.
* @config *
*/ * @var int
private static $next_run_hour = 9; *
* @config
*/
private static $next_run_hour = 9;
/** /**
* @var int The minutes past the hour (see above) at which to run these jobs * The minutes past the hour (see above) at which to run these jobs.
* @config *
*/ * @var int
private static $next_run_minute = 0; *
* @config
*/
private static $next_run_minute = 0;
/** /**
* @var int The number of days to skip between job runs (e.g. 1 means run this job every day, 2 means run it every * The number of days to skip between job runs (1 means run this job every day,
* second day etc.) * 2 means run it every second day etc).
* @config *
*/ * @var int
private static $next_run_in_days = 1; *
* @config
*/
private static $next_run_in_days = 1;
public function getTitle() { /**
return 'Content Review Notification Job'; * @return string
} */
public function getTitle()
{
return "Content Review Notification Job";
}
public function getJobType() { /**
$this->totalSteps = 1; * @return string
return QueuedJob::QUEUED; */
} public function getJobType()
{
$this->totalSteps = 1;
public function process() { return QueuedJob::QUEUED;
$this->queueNextRun(); }
$task = new ContentReviewEmails(); public function process()
$task->run(new SS_HTTPRequest('GET', '/dev/tasks/ContentReviewEmails')); {
$this->queueNextRun();
$this->currentStep = 1; $task = new ContentReviewEmails();
$this->isComplete = true; $task->run(new SS_HTTPRequest("GET", "/dev/tasks/ContentReviewEmails"));
}
/** $this->currentStep = 1;
* Queue up the next job to run. $this->isComplete = true;
*/ }
protected function queueNextRun() {
$nextRun = new ContentReviewNotificationJob();
$nextRunTime = mktime(
self::$next_run_hour,
self::$next_run_minute,
0,
date('m'),
date('d') + self::$next_run_in_days,
date('Y')
);
singleton('QueuedJobService')->queueJob( /**
$nextRun, * Queue up the next job to run.
date('Y-m-d H:i:s', $nextRunTime) */
); protected function queueNextRun()
} {
} $nextRun = new ContentReviewNotificationJob();
$nextRunTime = mktime(
self::$next_run_hour,
self::$next_run_minute,
0,
date("m"),
date("d") + self::$next_run_in_days,
date("Y")
);
singleton("QueuedJobService")->queueJob(
$nextRun,
date("Y-m-d H:i:s", $nextRunTime)
);
}
}

View File

@ -1,45 +1,43 @@
<?php <?php
class ContentReviewLog extends DataObject { class ContentReviewLog extends DataObject
{
/** /**
* * @var array
* @var array */
*/ private static $db = array(
private static $db = array( "Note" => "Text",
'Note' => 'Text' );
);
/**
/** * @var array
* */
* @var array private static $has_one = array(
*/ "Reviewer" => "Member",
private static $has_one = array( "SiteTree" => "SiteTree",
'Reviewer' => 'Member', );
'SiteTree' => 'SiteTree'
); /**
* @var array
/** */
* private static $summary_fields = array(
* @var array "Note" => array("title" => "Note"),
*/ "Created" => array("title" => "Reviewed at"),
private static $summary_fields = array( "Reviewer.Title" => array("title" => "Reviewed by"),
'Note' => array('title' => 'Note'), );
'Created' => array('title' => 'Reviewed at'),
'Reviewer.Title' => array('title' => 'Reviewed by') /**
); * @var string
*/
/** private static $default_sort = "Created DESC";
*
* @var string /**
*/ * @param mixed $member
private static $default_sort = 'Created DESC'; *
* @return bool
/** */
* public function canView($member = null)
* @return bool {
*/ return (bool) Member::currentUser();
public function canView($member = null) { }
return (bool)Member::currentUser();
}
} }

View File

@ -1,165 +1,168 @@
<?php <?php
require_once 'Zend/Date.php';
require_once "Zend/Date.php";
/** /**
* Show all pages that need to be reviewed * Show all pages that need to be reviewed.
*
* @package contentreview
*/ */
class PagesDueForReviewReport extends SS_Report { class PagesDueForReviewReport extends SS_Report
{
/**
* @return string
*/
public function title()
{
return _t("PagesDueForReviewReport.TITLE", "Pages due for review");
}
/** /**
* * @return FieldList
* @return string */
*/ public function parameterFields()
public function title() { {
return _t('PagesDueForReviewReport.TITLE', 'Pages due for review'); $filtersList = new FieldList();
}
/** $filtersList->push(
* DateField::create("ReviewDateAfter", "Review date after or on")
* @return \FieldList ->setConfig("showcalendar", true)
*/ );
public function parameterFields() {
$filtersList = new FieldList();
$filtersList->push( $filtersList->push(
DateField::create('ReviewDateAfter', 'Review date after or on') DateField::create("ReviewDateBefore", "Review date before or on", date("d/m/Y", strtotime("midnight")))
->setConfig('showcalendar', true) ->setConfig("showcalendar", true)
); );
$filtersList->push(
DateField::create('ReviewDateBefore', 'Review date before or on', date('d/m/Y', strtotime('midnight')))
->setConfig('showcalendar', true)
);
$filtersList->push(new CheckboxField('ShowVirtualPages', 'Show Virtual Pages')); $filtersList->push(new CheckboxField("ShowVirtualPages", "Show Virtual Pages"));
return $filtersList; return $filtersList;
} }
/** /**
* * @return array
* @return array */
*/ public function columns()
public function columns() { {
$linkBase = singleton("CMSPageEditController")->Link("show");
$linkBase = singleton('CMSPageEditController')->Link('show'); $linkPath = parse_url($linkBase, PHP_URL_PATH);
$linkPath = parse_url($linkBase, PHP_URL_PATH); $linkQuery = parse_url($linkBase, PHP_URL_QUERY);
$linkQuery = parse_url($linkBase, PHP_URL_QUERY);
$fields = array(
$fields = array( "Title" => array(
'Title' => array( "title" => "Page name",
'title' => 'Page name', "formatting" => "<a href='{$linkPath}/\$ID?{$linkQuery}' title='Edit page'>\$value</a>"
'formatting' => sprintf('<a href=\"%s/$ID?%s\" title=\"Edit page\">$value</a>', $linkPath, $linkQuery) ),
), "NextReviewDate" => array(
'NextReviewDate' => array( "title" => "Review Date",
'title' => 'Review Date', "casting" => "Date->Full",
'casting' => 'Date->Full', "formatting" => function ($value, $item) {
'formatting' => function($value, $item) { if ($item->ContentReviewType == "Disabled") {
if($item->ContentReviewType == 'Disabled') { return "disabled";
return 'disabled'; }
} if ($item->ContentReviewType == "Inherit") {
if($item->ContentReviewType == 'Inherit') { $setting = $item->getOptions();
$setting = $item->getOptions(); if (!$setting) {
if(!$setting) { return "disabled";
return 'disabled'; }
} return $item->obj("NextReviewDate")->Full();
return $item->obj('NextReviewDate')->Full(); }
} return $value;
return $value; }
} ),
), "OwnerNames" => array(
'OwnerNames' => array( "title" => "Owner"
'title' => 'Owner' ),
), "LastEditedByName" => "Last edited by",
'LastEditedByName' => 'Last edited by', "AbsoluteLink" => array(
'AbsoluteLink' => array( "title" => "URL",
'title' => 'URL', "formatting" => function ($value, $item) {
'formatting' => function($value, $item) { $liveLink = $item->AbsoluteLiveLink;
$liveLink = $item->AbsoluteLiveLink; $stageLink = $item->AbsoluteLink();
$stageLink = $item->AbsoluteLink();
return sprintf('%s <a href="%s">%s</a>',
$stageLink,
$liveLink ? $liveLink : $stageLink . '?stage=Stage',
$liveLink ? '(live)' : '(draft)'
);
}
),
'ContentReviewType' => array(
'title' => 'Settings are',
'formatting' => function($value, $item) use($linkPath, $linkQuery) {
if($item->ContentReviewType == 'Inherit') {
$options = $item->getOptions();
if($options && $options instanceof SiteConfig) {
return 'Inherited from <a href="admin/settings">Settings</a>';
} elseif($options) {
return sprintf(
'Inherited from <a href="%s/%d?%s">%s</a>',
$linkPath,
$options->ID,
$linkQuery,
$options->Title
);
}
}
return $value;
}
),
);
return $fields; return sprintf("%s <a href='%s'>%s</a>",
} $stageLink,
$liveLink ? $liveLink : $stageLink . "?stage=Stage",
$liveLink ? "(live)" : "(draft)"
);
}
),
"ContentReviewType" => array(
"title" => "Settings are",
"formatting" => function ($value, $item) use ($linkPath,$linkQuery) {
if ($item->ContentReviewType == "Inherit") {
$options = $item->getOptions();
if ($options && $options instanceof SiteConfig) {
return "Inherited from <a href='admin/settings'>Settings</a>";
} elseif ($options) {
return sprintf(
"Inherited from <a href='%s/%d?%s'>%s</a>",
$linkPath,
$options->ID,
$linkQuery,
$options->Title
);
}
}
/** return $value;
* }
* @param array $params ),
* @return SS_List );
*/
public function sourceRecords($params = array()) {
Versioned::reading_stage('Stage');
$c = ContentReviewCompatability::start();
$records = SiteTree::get();
if(empty($params['ReviewDateBefore']) && empty($params['ReviewDateAfter'])) { return $fields;
// If there's no review dates set, default to all pages due for review now }
$reviewDate = new Zend_Date(SS_Datetime::now()->Format('U'));
$reviewDate->add(1, Zend_Date::DAY);
$records = $records->where(sprintf('"NextReviewDate" < \'%s\'', $reviewDate->toString('YYYY-MM-dd')));
} else {
// Review date before
if(!empty($params['ReviewDateBefore'])) {
// TODO Get value from DateField->dataValue() once we have access to form elements here
$reviewDate = new Zend_Date($params['ReviewDateBefore'], i18n::get_date_format());
$reviewDate->add(1, Zend_Date::DAY);
$records = $records->where(sprintf('"NextReviewDate" < \'%s\'', $reviewDate->toString('YYYY-MM-dd')));
}
// Review date after /**
if(!empty($params['ReviewDateAfter'])) { * @param array $params
// TODO Get value from DateField->dataValue() once we have access to form elements here *
$reviewDate = new Zend_Date($params['ReviewDateAfter'], i18n::get_date_format()); * @return SS_List
$records = $records->where(sprintf('"NextReviewDate" >= \'%s\'', $reviewDate->toString('YYYY-MM-dd'))); */public function sourceRecords($params = array())
} {
} Versioned::reading_stage("Stage");
// Show virtual pages? $records = SiteTree::get();
if(empty($params['ShowVirtualPages'])) { $compatibility = ContentReviewCompatability::start();
$virtualPageClasses = ClassInfo::subclassesFor('VirtualPage');
$records = $records->where(sprintf(
'"SiteTree"."ClassName" NOT IN (\'%s\')',
implode("','", array_values($virtualPageClasses))
));
}
// Owner dropdown if (empty($params["ReviewDateBefore"]) && empty($params["ReviewDateAfter"])) {
if(!empty($params['ContentReviewOwner'])) { // If there's no review dates set, default to all pages due for review now
$ownerNames = Convert::raw2sql($params['ContentReviewOwner']); $reviewDate = new Zend_Date(SS_Datetime::now()->Format("U"));
$records = $records->filter('OwnerNames:PartialMatch', $ownerNames); $reviewDate->add(1, Zend_Date::DAY);
} $records = $records->where(sprintf('"NextReviewDate" < \'%s\'', $reviewDate->toString("YYYY-MM-dd")));
} else {
$r = new ArrayList($records->sort('NextReviewDate', 'DESC')->toArray()); // Review date before
ContentReviewCompatability::done($c); if (!empty($params['ReviewDateBefore'])) {
return $r; // TODO Get value from DateField->dataValue() once we have access to form elements here
} $reviewDate = new Zend_Date($params["ReviewDateBefore"], Config::inst()->get("i18n", "date_format"));
$reviewDate->add(1, Zend_Date::DAY);
$records = $records->where(sprintf("\"NextReviewDate\" < '%s'", $reviewDate->toString("YYYY-MM-dd")));
}
// Review date after
if (!empty($params["ReviewDateAfter"])) {
// TODO Get value from DateField->dataValue() once we have access to form elements here
$reviewDate = new Zend_Date($params["ReviewDateAfter"], Config::inst()->get("i18n", "date_format"));
$records = $records->where(sprintf("\"NextReviewDate\" >= '%s'", $reviewDate->toString("YYYY-MM-dd")));
}
}
// Show virtual pages?
if (empty($params["ShowVirtualPages"])) {
$virtualPageClasses = ClassInfo::subclassesFor("VirtualPage");
$records = $records->where(sprintf(
"\"SiteTree\".\"ClassName\" NOT IN ('%s')",
implode("','", array_values($virtualPageClasses))
));
}
// Owner dropdown
if (!empty($params["ContentReviewOwner"])) {
$ownerNames = Convert::raw2sql($params["ContentReviewOwner"]);
$records = $records->filter("OwnerNames:PartialMatch", $ownerNames);
}
$records = new ArrayList($records->sort("NextReviewDate", "DESC")->toArray());
ContentReviewCompatability::done($compatibility);
return $records;
}
} }

View File

@ -1,142 +1,148 @@
<?php <?php
require_once 'Zend/Date.php';
require_once "Zend/Date.php";
/** /**
* Show all pages that need to be reviewed * Show all pages that need to be reviewed.
*
* @package contentreview
*/ */
class PagesWithoutReviewScheduleReport extends SS_Report { class PagesWithoutReviewScheduleReport extends SS_Report
{
/**
* @return string
*/
public function title()
{
return _t("PagesWithoutReviewScheduleReport.TITLE", "Pages without a scheduled review.");
}
/** /**
* * @return FieldList
* @return string */
*/ public function parameterFields()
public function title() { {
return _t('PagesWithoutReviewScheduleReport.TITLE', 'Pages without a scheduled review.'); $params = new FieldList();
} $params->push(new CheckboxField("ShowVirtualPages", "Show Virtual Pages"));
/** return $params;
* }
* @return \FieldList
*/
public function parameterFields() {
$params = new FieldList();
$params->push(new CheckboxField('ShowVirtualPages', 'Show Virtual Pages'));
return $params;
}
/** /**
* * @return array
* @return array */
*/ public function columns()
public function columns() { {
$linkBase = singleton('CMSPageEditController')->Link('show'); $linkBase = singleton("CMSPageEditController")->Link("show");
$linkPath = parse_url($linkBase, PHP_URL_PATH); $linkPath = parse_url($linkBase, PHP_URL_PATH);
$linkQuery = parse_url($linkBase, PHP_URL_QUERY); $linkQuery = parse_url($linkBase, PHP_URL_QUERY);
$fields = array( $fields = array(
'Title' => array( "Title" => array(
'title' => 'Page name', "title" => "Page name",
'formatting' => sprintf('<a href=\"%s/$ID?%s\" title=\"Edit page\">$value</a>', $linkPath, $linkQuery) "formatting" => "<a href='{$linkPath}/\$ID?{$linkQuery}' title='Edit page'>\$value</a>",
), ),
'NextReviewDate' => array( "NextReviewDate" => array(
'title' => 'Review Date', "title" => "Review Date",
'casting' => 'Date->Full' "casting" => "Date->Full",
), ),
'OwnerNames' => array( "OwnerNames" => array(
'title' => 'Owner' "title" => "Owner",
), ),
'LastEditedByName' => 'Last edited by', "LastEditedByName" => "Last edited by",
'AbsoluteLink' => array( "AbsoluteLink" => array(
'title' => 'URL', "title" => "URL",
'formatting' => function($value, $item) { "formatting" => function ($value, $item) {
$liveLink = $item->AbsoluteLiveLink; $liveLink = $item->AbsoluteLiveLink;
$stageLink = $item->AbsoluteLink(); $stageLink = $item->AbsoluteLink();
return sprintf('%s <a href="%s">%s</a>',
$stageLink,
$liveLink ? $liveLink : $stageLink . '?stage=Stage',
$liveLink ? '(live)' : '(draft)'
);
}
),
'ContentReviewType' => array(
'title' => 'Settings are',
'formatting' => function($value, $item) use($linkPath, $linkQuery) {
if($item->ContentReviewType == 'Inherit') {
$options = $item->getOptions();
if($options && $options instanceof SiteConfig) {
return 'Inherited from <a href="admin/settings">Settings</a>';
} elseif($options) {
return sprintf(
'Inherited from <a href="%s/%d?%s">%s</a>',
$linkPath,
$options->ID,
$linkQuery,
$options->Title
);
}
}
return $value;
}
)
);
return $fields; return sprintf("%s <a href='%s'>%s</a>",
} $stageLink,
$liveLink ? $liveLink : $stageLink . "?stage=Stage",
$liveLink ? "(live)" : "(draft)"
);
},
),
"ContentReviewType" => array(
"title" => "Settings are",
"formatting" => function ($value, $item) use ($linkPath, $linkQuery) {
if ($item->ContentReviewType == "Inherit") {
$options = $item->getOptions();
if ($options && $options instanceof SiteConfig) {
return "Inherited from <a href='admin/settings'>Settings</a>";
} elseif ($options) {
return sprintf(
"Inherited from <a href='%s/%d?%s'>%s</a>",
$linkPath,
$options->ID,
$linkQuery,
$options->Title
);
}
}
/** return $value;
* },
* @param array $params ),
* @return SS_List );
*/
public function sourceRecords($params = array()) {
Versioned::reading_stage('Stage');
$c = ContentReviewCompatability::start();
$records = SiteTree::get();
// If there's no review dates set, default to all pages due for review now return $fields;
// $records = $records->where('"NextReviewDate" IS NULL OR "OwnerNames" IS NULL OR "OwnerNames" = \'\''); }
// Show virtual pages? /**
if(empty($params['ShowVirtualPages'])) { * @param array $params
$virtualPageClasses = ClassInfo::subclassesFor('VirtualPage'); *
$records = $records->where(sprintf( * @return SS_List
'"SiteTree"."ClassName" NOT IN (\'%s\')', */
implode("','", array_values($virtualPageClasses)) public function sourceRecords($params = array())
)); {
} Versioned::reading_stage("Stage");
$records->sort('ParentID');
$records = $records->toArray();
// Trim out calculated values
$list = new ArrayList();
foreach($records as $record) {
if(!$this->hasReviewSchedule($record)) {
$list->push($record);
}
}
ContentReviewCompatability::done($c);
return $list;
}
/**
*
* @param DataObject $record
* @return boolean
*/
protected function hasReviewSchedule(DataObject $record) {
if(!$record->obj('NextReviewDate')->exists()) {
return false;
}
$options = $record->getOptions(); $records = SiteTree::get();
if($options->OwnerGroups()->count() == 0 && $options->OwnerUsers()->count() == 0) { $compatibility = ContentReviewCompatability::start();
return false;
}
return true; // If there's no review dates set, default to all pages due for review now.
}
} // Show virtual pages?
if (empty($params["ShowVirtualPages"])) {
$virtualPageClasses = ClassInfo::subclassesFor("VirtualPage");
$records = $records->where(sprintf(
"\"SiteTree\".\"ClassName\" NOT IN ('%s')",
implode("','", array_values($virtualPageClasses))
));
}
$records->sort("ParentID");
$records = $records->toArray();
// Trim out calculated values
$list = new ArrayList();
foreach ($records as $record) {
if (!$this->hasReviewSchedule($record)) {
$list->push($record);
}
}
ContentReviewCompatability::done($compatibility);
return $list;
}
/**
* @param DataObject $record
*
* @return bool
*/
protected function hasReviewSchedule(DataObject $record)
{
if (!$record->obj("NextReviewDate")->exists()) {
return false;
}
$options = $record->getOptions();
if ($options->OwnerGroups()->count() == 0 && $options->OwnerUsers()->count() == 0) {
return false;
}
return true;
}
}

View File

@ -1,92 +1,94 @@
<?php <?php
/** /**
* Daily task to send emails to the owners of content items * Daily task to send emails to the owners of content items when the review date rolls around.
* when the review date rolls around
*
*
* @todo create a page cache for the inherited so that we dont unneccesary need to look up parent pages
* @package contentreview
*/ */
class ContentReviewEmails extends BuildTask { class ContentReviewEmails extends BuildTask
{
/**
* Holds a cached array for looking up members via their ID.
*
* @var array
*/
protected static $member_cache = array();
/** /**
* Holds a cached array for looking up members via their ID * @param SS_HTTPRequest $request
* */
* @var array public function run($request)
*/ {
protected static $member_cache = array(); $compatibility = ContentReviewCompatability::start();
/**
*
* @param SS_HTTPRequest $request
*/
public function run($request) {
$c = ContentReviewCompatability::start();
$now = class_exists('SS_Datetime') ? SS_Datetime::now()->URLDate() : SSDatetime::now()->URLDate();
// First grab all the pages with a custom setting
$pages = Page::get('Page')->where('"SiteTree"."NextReviewDate" <= \''.$now.'\'');
$overduePages = $this->getOverduePagesForOwners($pages);
// Lets send one email to one owner with all the pages in there instead of no of pages of emails
foreach($overduePages as $memberID => $pages) {
$this->notifyOwner($memberID, $pages);
}
ContentReviewCompatability::done($c);
}
/**
*
* @param SS_list $pages
* @param array &$pages
* @return array
*/
protected function getOverduePagesForOwners(SS_list $pages) {
$overduePages = array();
foreach($pages as $page) {
if(!$page->canBeReviewedBy()) {
continue;
}
$option = $page->getOptions();
foreach($option->ContentReviewOwners() as $owner) {
if(!isset(self::$member_cache[$owner->ID])) {
self::$member_cache[$owner->ID] = $owner;
}
if(!isset($overduePages[$owner->ID])) {
$overduePages[$owner->ID] = new ArrayList();
}
$overduePages[$owner->ID]->push($page);
}
}
return $overduePages;
}
/**
*
* @param int $owner
* @param array $pages
*/
protected function notifyOwner($ownerID, SS_List $pages) {
$owner = self::$member_cache[$ownerID];
$sender = Security::findAnAdministrator();
$senderEmail = ($sender->Email) ? $sender->Email : Config::inst()->get('Email', 'admin_email');
$subject = _t('ContentReviewEmails.SUBJECT', 'Page(s) are due for content review'); $now = class_exists("SS_Datetime") ? SS_Datetime::now()->URLDate() : SSDatetime::now()->URLDate();
$email = new Email();
$email->setTo($owner->Email); // First grab all the pages with a custom setting
$email->setFrom($senderEmail); $pages = Page::get("Page")->where("\"SiteTree\".\"NextReviewDate\" <= '{$now}'");
$email->setTemplate('ContentReviewEmail');
$email->setSubject($subject); $overduePages = $this->getOverduePagesForOwners($pages);
$email->populateTemplate(array(
"Recipient" => $owner, // Lets send one email to one owner with all the pages in there instead of no of pages
"Sender" => $sender, // of emails.
"Pages" => $pages foreach ($overduePages as $memberID => $pages) {
)); $this->notifyOwner($memberID, $pages);
$email->send(); }
}
ContentReviewCompatability::done($compatibility);
}
/**
* @param SS_list $pages
*
* @return array
*/
protected function getOverduePagesForOwners(SS_list $pages)
{
$overduePages = array();
foreach ($pages as $page) {
if (!$page->canBeReviewedBy()) {
continue;
}
$option = $page->getOptions();
foreach ($option->ContentReviewOwners() as $owner) {
if (!isset(self::$member_cache[$owner->ID])) {
self::$member_cache[$owner->ID] = $owner;
}
if (!isset($overduePages[$owner->ID])) {
$overduePages[$owner->ID] = new ArrayList();
}
$overduePages[$owner->ID]->push($page);
}
}
return $overduePages;
}
/**
* @param int $ownerID
* @param array|SS_List $pages
*/
protected function notifyOwner($ownerID, SS_List $pages)
{
$owner = self::$member_cache[$ownerID];
$sender = Security::findAnAdministrator();
$senderEmail = ($sender->Email) ? $sender->Email : Config::inst()->get("Email", "admin_email");
$subject = _t("ContentReviewEmails.SUBJECT", "Page(s) are due for content review");
$email = new Email();
$email->setTo($owner->Email);
$email->setFrom($senderEmail);
$email->setTemplate("ContentReviewEmail");
$email->setSubject($subject);
$email->populateTemplate(array(
"Recipient" => $owner,
"Sender" => $sender,
"Pages" => $pages,
));
$email->send();
}
} }

View File

@ -1,25 +1,27 @@
<?php <?php
/** /**
* Task which migrates the ContentReview Module's SiteTree->OwnerID column to a new column name * Task which migrates the ContentReview Module's SiteTree->OwnerID column to a new column name.
*/ */
class ContentReviewOwnerMigrationTask extends BuildTask { class ContentReviewOwnerMigrationTask extends BuildTask
{
/** /**
* * @param SS_HTTPRequest $request
* @param SS_HTTPRequest $request */
*/ public function run($request)
public function run($request) { {
$results = DB::query('SHOW columns from "SiteTree" WHERE "field" = \'OwnerID\''); $results = DB::query("SHOW columns from \"SiteTree\" WHERE \"field\" = 'OwnerID'");
if ($results->numRecords() == 0) {
echo "<h1>No need to run task. SiteTree->OwnerID doesn't exist</h1>"; if ($results->numRecords() == 0) {
} else { echo "<h1>No need to run task. SiteTree->OwnerID doesn't exist</h1>";
DB::query('UPDATE "SiteTree" SET "ContentReviewOwnerID" = "OwnerID"'); } else {
DB::query('UPDATE "SiteTree_Live" SET "ContentReviewOwnerID" = "OwnerID"'); DB::query("UPDATE \"SiteTree\" SET \"ContentReviewOwnerID\" = \"OwnerID\"");
DB::query('UPDATE "SiteTree_versions" SET "ContentReviewOwnerID" = "OwnerID"'); DB::query("UPDATE \"SiteTree_Live\" SET \"ContentReviewOwnerID\" = \"OwnerID\"");
DB::query('ALTER TABLE "SiteTree" DROP COLUMN "OwnerID"'); DB::query("UPDATE \"SiteTree_versions\" SET \"ContentReviewOwnerID\" = \"OwnerID\"");
DB::query('ALTER TABLE "SiteTree_Live" DROP COLUMN "OwnerID"'); DB::query("ALTER TABLE \"SiteTree\" DROP COLUMN \"OwnerID\"");
DB::query('ALTER TABLE "SiteTree_versions" DROP COLUMN "OwnerID"'); DB::query("ALTER TABLE \"SiteTree_Live\" DROP COLUMN \"OwnerID\"");
echo "<h1>Migrated 3 tables. Dropped obsolete OwnerID column</h1>"; DB::query("ALTER TABLE \"SiteTree_versions\" DROP COLUMN \"OwnerID\"");
} echo "<h1>Migrated 3 tables. Dropped obsolete OwnerID column</h1>";
} }
} }
}

View File

@ -1,36 +1,42 @@
<?php <?php
/** /**
* Extend this class when writing unit tests which are compatable with other modules. All * Extend this class when writing unit tests which are compatible with other modules.
* compatability code goes here. * All compatibility code goes here.
*/ */
abstract class ContentReviewBaseTest extends FunctionalTest { abstract class ContentReviewBaseTest extends FunctionalTest
{
protected $translatableEnabledBefore; /**
* @var bool
public function setUp(){ */
parent::setUp(); protected $translatableEnabledBefore;
/*
* We set the locale for pages explicitly, because if we don't, then we get into a situation public function setUp()
* where the page takes on the tester's (your) locale, and any calls to simulate subsequent requests {
* (e.g. $this->post()) do not seem to get passed the tester's locale, but instead fallback to the default locale. parent::setUp();
*
* So we set the pages locale to be the default locale, which will then match any subsequent requests. /*
* * We set the locale for pages explicitly, because if we don't, then we get into a situation
* If creating pages in your unit tests (rather than reading from the fixtures file), you must explicitly call * where the page takes on the tester's (your) locale, and any calls to simulate subsequent requests
* self::compat() on the page, for the same reasons as above. * (e.g. $this->post()) do not seem to get passed the tester's locale, but instead fallback to the default locale.
*/ *
if(class_exists('Translatable')){ * So we set the pages locale to be the default locale, which will then match any subsequent requests.
fwrite(STDOUT, 'TRANSLATABLE DISABLED FFS'); *
$this->translatableEnabledBefore = Translatable::is_enabled(); * If creating pages in your unit tests (rather than reading from the fixtures file), you must explicitly call
Translatable::disable(); * self::compat() on the page, for the same reasons as above.
} */
} if (class_exists("Translatable")) {
$this->translatableEnabledBefore = SiteTree::has_extension("Translatable");
public function tearDown(){ SiteTree::remove_extension("Translatable");
if(class_exists('Translatable')){ }
if($this->translatableEnabledBefore) Translatable::enable(); }
}
} public function tearDown()
{
} if (class_exists("Translatable")) {
if ($this->translatableEnabledBefore) {
SiteTree::add_extension("Translatable");
}
}
}
}

View File

@ -1,67 +1,101 @@
<?php <?php
class ContentReviewCMSPageEditControllerTest extends ContentReviewBaseTest { /**
* @mixin PHPUnit_Framework_TestCase
public static $fixture_file = 'contentreview/tests/ContentReviewTest.yml'; */
class ContentReviewCMSPageEditControllerTest extends ContentReviewBaseTest
protected $requiredExtensions = array( {
"SiteTree" => array("SiteTreeContentReview"), /**
"Group" => array("ContentReviewOwner"), * @var string
"Member" => array("ContentReviewOwner"), */
"CMSPageEditController" => array("ContentReviewCMSExtension"), public static $fixture_file = "contentreview/tests/ContentReviewTest.yml";
"SiteConfig" => array("ContentReviewDefaultSettings"),
);
public function testReviewedThrowsExceptionWithNoRecordID() {
$this->setExpectedException('SS_HTTPResponse_Exception', 'No record ID', 404);
$controller = new CMSPageEditController();
$dummyForm = new CMSForm($controller, 'EditForm', new FieldList(), new FieldList());
$controller->reviewed(array('ID'=>null, 'Message' => null), $dummyForm);
}
public function testReviewedThrowsExceptionWithWrongRecordID() {
$this->setExpectedException('SS_HTTPResponse_Exception');
$controller = new CMSPageEditController();
$dummyForm = new CMSForm($controller, 'EditForm', new FieldList(), new FieldList());
$controller->reviewed(array('ID'=>'FAIL', 'Message' => null), $dummyForm);
}
public function testReviewedWithAuthor() {
$author = $this->objFromFixture('Member', 'author');
$this->loginAs($author);
$page = $this->objFromFixture('Page', 'home');
$data = array(
'action_reviewed' => 1,
'ID' => $page->ID
);
$response = $this->post('admin/pages/edit/EditForm', $data);
$this->assertEquals('OK', $response->getStatusDescription());
$this->assertEquals(200, $response->getStatusCode());
}
public function testSaveReview() {
$author = $this->objFromFixture('Member', 'author');
$this->loginAs($author);
$page = $this->objFromFixture('Page', 'home');
$data = array(
'action_save_review' => 1,
'ID' => $page->ID,
'ReviewNotes' => 'This is the best page ever'
);
$response = $this->post('admin/pages/edit/EditForm', $data);
$this->assertEquals('OK', $response->getStatusDescription());
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals(1, $page->ReviewLogs()->count());
$reviewLog = $page->ReviewLogs()->first();
$this->assertEquals($data['ReviewNotes'], $reviewLog->Note);
}
}
/**
* @var array
*/
protected $requiredExtensions = array(
"SiteTree" => array("SiteTreeContentReview"),
"Group" => array("ContentReviewOwner"),
"Member" => array("ContentReviewOwner"),
"CMSPageEditController" => array("ContentReviewCMSExtension"),
"SiteConfig" => array("ContentReviewDefaultSettings"),
);
public function testReviewedThrowsExceptionWithNoRecordID()
{
$this->setExpectedException("SS_HTTPResponse_Exception");
/** @var CMSPageEditController|ContentReviewCMSExtension $controller */
$controller = new CMSPageEditController();
$dummyForm = new CMSForm($controller, "EditForm", new FieldList(), new FieldList());
$controller->reviewed(array(
"ID" => null,
"Message" => null,
), $dummyForm);
}
public function testReviewedThrowsExceptionWithWrongRecordID()
{
$this->setExpectedException("SS_HTTPResponse_Exception");
/** @var CMSPageEditController|ContentReviewCMSExtension $controller */
$controller = new CMSPageEditController();
$dummyForm = new CMSForm($controller, "EditForm", new FieldList(), new FieldList());
$controller->reviewed(array(
"ID" => "FAIL",
"Message" => null,
), $dummyForm);
}
public function testReviewedWithAuthor()
{
/** @var Member $author */
$author = $this->objFromFixture("Member", "author");
$this->loginAs($author);
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "home");
$data = array(
"action_reviewed" => 1,
"ID" => $page->ID,
);
$response = $this->post("admin/pages/edit/EditForm", $data);
$this->assertEquals("OK", $response->getStatusDescription());
$this->assertEquals(200, $response->getStatusCode());
}
public function testSaveReview()
{
/** @var Member $author */
$author = $this->objFromFixture("Member", "author");
$this->loginAs($author);
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "home");
$data = array(
"action_save_review" => 1,
"ID" => $page->ID,
"ReviewNotes" => "This is the best page ever",
);
$response = $this->post("admin/pages/edit/EditForm", $data);
$this->assertEquals("OK", $response->getStatusDescription());
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals(1, $page->ReviewLogs()->count());
$reviewLog = $page->ReviewLogs()->first();
$this->assertEquals($data["ReviewNotes"], $reviewLog->Note);
}
}

View File

@ -1,38 +1,47 @@
<?php <?php
class ContentReviewNotificationTest extends SapphireTest { /**
* @mixin PHPUnit_Framework_TestCase
public static $fixture_file = 'contentreview/tests/ContentReviewTest.yml'; */
class ContentReviewNotificationTest extends SapphireTest
protected $requiredExtensions = array( {
"SiteTree" => array("SiteTreeContentReview"), /**
"Group" => array("ContentReviewOwner"), * @var string
"Member" => array("ContentReviewOwner"), */
"CMSPageEditController" => array("ContentReviewCMSExtension"), public static $fixture_file = "contentreview/tests/ContentReviewTest.yml";
"SiteConfig" => array("ContentReviewDefaultSettings"),
); /**
* @var array
public function testContentReviewEmails() { */
SS_Datetime::set_mock_now('2010-02-24 12:00:00'); protected $requiredExtensions = array(
"SiteTree" => array("SiteTreeContentReview"),
// This propagates the next review date to 'contact-child' page from the parent page "Group" => array("ContentReviewOwner"),
$childParentPage = $this->objFromFixture('Page', 'contact'); "Member" => array("ContentReviewOwner"),
$childParentPage->NextReviewDate = '2010-02-23'; "CMSPageEditController" => array("ContentReviewCMSExtension"),
$childParentPage->write(); "SiteConfig" => array("ContentReviewDefaultSettings"),
);
$task = new ContentReviewEmails();
$task->run(new SS_HTTPRequest('GET', '/dev/tasks/ContentReviewEmails')); public function testContentReviewEmails()
{
$expectedSubject = _t('ContentReviewEmails.SUBJECT', 'Page(s) are due for content review'); SS_Datetime::set_mock_now("2010-02-24 12:00:00");
$email = $this->findEmail('author@example.com', null, $expectedSubject);
/** @var Page|SiteTreeContentReview $childParentPage */
$this->assertNotNull($email, 'Email haven\'t been sent.'); $childParentPage = $this->objFromFixture("Page", "contact");
$childParentPage->NextReviewDate = "2010-02-23";
$this->assertContains('There are 3 pages that are due for review today by you.', $email['htmlContent']); $childParentPage->write();
$this->assertContains('Staff', $email['htmlContent']);
$this->assertContains('Contact Us', $email['htmlContent']); $task = new ContentReviewEmails();
$this->assertContains('Contact Us Child', $email['htmlContent']); $task->run(new SS_HTTPRequest("GET", "/dev/tasks/ContentReviewEmails"));
SS_Datetime::clear_mock_now(); $expectedSubject = _t("ContentReviewEmails.SUBJECT", "Page(s) are due for content review");
} $email = $this->findEmail("author@example.com", null, $expectedSubject);
$this->assertNotNull($email, "Email haven't been sent.");
$this->assertContains("There are 3 pages that are due for review today by you.", $email["htmlContent"]);
$this->assertContains("Staff", $email["htmlContent"]);
$this->assertContains("Contact Us", $email["htmlContent"]);
$this->assertContains("Contact Us Child", $email["htmlContent"]);
SS_Datetime::clear_mock_now();
}
} }

View File

@ -1,67 +1,81 @@
<?php <?php
class ContentReviewReportTest extends FunctionalTest { class ContentReviewReportTest extends FunctionalTest
{
public static $fixture_file = 'contentreview/tests/ContentReviewTest.yml'; /**
* @var string
protected $requiredExtensions = array( */
"SiteTree" => array("SiteTreeContentReview"), public static $fixture_file = "contentreview/tests/ContentReviewTest.yml";
"Group" => array("ContentReviewOwner"),
"Member" => array("ContentReviewOwner"),
"CMSPageEditController" => array("ContentReviewCMSExtension"),
"SiteConfig" => array("ContentReviewDefaultSettings"),
);
public function testPagesDueForReviewReport() {
$editor = $this->objFromFixture('Member', 'editor');
$this->logInAs($editor);
$report = new PagesDueForReviewReport();
$report->parameterFields();
$report->columns();
$report->title();
$results = $report->sourceRecords(array(
'ReviewDateAfter' => '01/01/2010',
'ReviewDateBefore' => '12/12/2010'
));
$this->assertEquals(array( /**
'Contact Us', * @var array
'Contact Us Child', */
'Staff', protected $requiredExtensions = array(
'About Us', "SiteTree" => array("SiteTreeContentReview"),
'Home' "Group" => array("ContentReviewOwner"),
), $results->column('Title')); "Member" => array("ContentReviewOwner"),
"CMSPageEditController" => array("ContentReviewCMSExtension"),
SS_Datetime::set_mock_now('2010-02-13 00:00:00'); "SiteConfig" => array("ContentReviewDefaultSettings"),
$results = $report->sourceRecords(array()); );
$this->assertEquals(array(
'About Us', public function testPagesDueForReviewReport()
'Home' {
), $results->column('Title')); /** @var Member $editor */
$editor = $this->objFromFixture("Member", "editor");
SS_Datetime::clear_mock_now();
} $this->logInAs($editor);
public function testPagesWithoutReviewScheduleReport() { $report = new PagesDueForReviewReport();
$editor = $this->objFromFixture('Member', 'editor');
$this->logInAs($editor); $report->parameterFields();
$report = new PagesWithoutReviewScheduleReport(); $report->columns();
$report->title();
$report->parameterFields();
$report->columns(); $results = $report->sourceRecords(array(
$report->title(); "ReviewDateAfter" => "01/01/2010",
"ReviewDateBefore" => "12/12/2010",
$results = $report->sourceRecords(); ));
$this->assertEquals(array( $this->assertEquals(array(
'Home', "Contact Us",
'About Us', "Contact Us Child",
'Page without review date', "Staff",
'Page owned by group', "About Us",
), $results->column('Title')); "Home",
} ), $results->column("Title"));
SS_Datetime::set_mock_now("2010-02-13 00:00:00");
$results = $report->sourceRecords(array());
$this->assertEquals(array(
"About Us",
"Home",
), $results->column("Title"));
SS_Datetime::clear_mock_now();
}
public function testPagesWithoutReviewScheduleReport()
{
/** @var Member $editor */
$editor = $this->objFromFixture("Member", "editor");
$this->logInAs($editor);
$report = new PagesWithoutReviewScheduleReport();
$report->parameterFields();
$report->columns();
$report->title();
$results = $report->sourceRecords();
$this->assertEquals(array(
"Home",
"About Us",
"Page without review date",
"Page owned by group",
), $results->column("Title"));
}
} }

View File

@ -1,196 +1,294 @@
<?php <?php
/** /**
* This class tests that settings are inherited correctly based on the inherited, custom or disabled settings * This class tests that settings are inherited correctly based on the inherited,
* custom or disabled settings.
*
* @mixin PHPUnit_Framework_TestCase
*/ */
class ContentReviewSettingsTest extends SapphireTest { class ContentReviewSettingsTest extends SapphireTest
{
/**
* @var string
*/
public static $fixture_file = "contentreview/tests/ContentReviewSettingsTest.yml";
public static $fixture_file = 'contentreview/tests/ContentReviewSettingsTest.yml'; /**
* @var array
protected $requiredExtensions = array( */
"SiteTree" => array("SiteTreeContentReview"), protected $requiredExtensions = array(
"Group" => array("ContentReviewOwner"), "SiteTree" => array("SiteTreeContentReview"),
"Member" => array("ContentReviewOwner"), "Group" => array("ContentReviewOwner"),
"CMSPageEditController" => array("ContentReviewCMSExtension"), "Member" => array("ContentReviewOwner"),
"SiteConfig" => array("ContentReviewDefaultSettings"), "CMSPageEditController" => array("ContentReviewCMSExtension"),
); "SiteConfig" => array("ContentReviewDefaultSettings"),
);
public function testAdvanceReviewDate10Days() {
$page = new Page();
$page->ContentReviewType = 'Custom';
$page->ReviewPeriodDays = 10;
$this->assertTrue($page->advanceReviewDate());
$page->write();
$this->assertEquals(date('Y-m-d', strtotime('now + 10 days')), $page->NextReviewDate);
}
public function testAdvanceReviewDateNull() {
$page = new Page();
$page->ContentReviewType = 'Custom';
$page->ReviewPeriodDays = 0;
$this->assertFalse($page->advanceReviewDate());
$page->write();
$this->assertEquals(null, $page->NextReviewDate);
}
public function testAdvanceReviewFromCustomSettings() {
$page = $this->objFromFixture('Page', 'custom');
$this->assertTrue($page->advanceReviewDate());
$page->write();
$this->assertEquals(date('Y-m-d', strtotime('now + '.$page->ReviewPeriodDays.' days')), $page->NextReviewDate);
}
public function testAdvanceReviewFromInheritedSettings() {
$page = $this->objFromFixture('Page', 'page-1-1');
$parentPage = $this->objFromFixture('Page', 'page-1');
$this->assertTrue($page->advanceReviewDate());
$page->write();
$this->assertEquals(date('Y-m-d', strtotime('now + '.$parentPage->ReviewPeriodDays.' days')), $page->NextReviewDate);
}
public function testAdvanceReviewFromInheritedSiteConfigSettings() {
$page = $this->objFromFixture('Page', 'inherit');
$siteConfig = $this->objFromFixture('SiteConfig', 'default');
$this->assertTrue($page->advanceReviewDate());
$page->write();
$this->assertEquals(date('Y-m-d', strtotime('now + '.$siteConfig->ReviewPeriodDays.' days')), $page->NextReviewDate);
}
public function testGetSettingsObjectFromCustom() {
$page = $this->objFromFixture('Page', 'custom');
$this->assertEquals('Custom', $page->ContentReviewType);
$this->assertEquals($page, $page->getOptions());
}
public function testGetSettingsObjectFromDisabled() {
$page = $this->objFromFixture('Page', 'disabled');
$this->assertEquals('Disabled', $page->ContentReviewType);
$this->assertFalse($page->getOptions());
}
public function testGetOptionObjectFromInheritedDisabled() {
$page = $this->objFromFixture('Page', 'page-2-1-1');
$this->assertEquals('Inherit', $page->ContentReviewType);
$this->assertFalse($page->getOptions());
}
public function testGetOptionObjectFromDeeplyInheritedPage() {
$page = $this->objFromFixture('Page', 'page-3-1-1-1');
$this->assertEquals('Inherit', $page->ContentReviewType);
$this->assertInstanceOf('SiteConfig', $page->getOptions());
}
public function testGetSettingsObjectFromInheritPage() {
$page = $this->objFromFixture('Page', 'page-1-1');
$parentPage = $this->objFromFixture('Page', 'page-1');
$this->assertEquals('Inherit', $page->ContentReviewType);
$this->assertEquals(get_class($parentPage), get_class($page->getOptions()));
$this->assertEquals($parentPage->ID, $page->getOptions()->ID);
}
public function testGetSettingsObjectFromInheritedRootPage() { public function testAdvanceReviewDate10Days()
$page = $this->objFromFixture('Page', 'inherit'); {
$this->assertEquals('Inherit', $page->ContentReviewType); /** @var Page|SiteTreeContentReview $page */
$this->assertEquals($this->objFromFixture('SiteConfig', 'default'), $page->getOptions()); $page = new Page();
}
$page->ContentReviewType = "Custom";
public function testGetNextReviewDateFromCustomSettings() { $page->ReviewPeriodDays = 10;
$page = $this->objFromFixture('Page', 'custom');
$date = $page->getReviewDate(); $this->assertTrue($page->advanceReviewDate());
$this->assertEquals('2010-02-01', $date->format('Y-m-d'));
} $page->write();
public function testGetNextReviewDateFromSiteConfigInheritedSetting() { $this->assertEquals(date("Y-m-d", strtotime("now + 10 days")), $page->NextReviewDate);
$page = $this->objFromFixture('Page', 'inherit'); }
$nextReviewDate = $page->getReviewDate();
public function testAdvanceReviewDateNull()
$this->assertInstanceOf('Date', $nextReviewDate); {
$expected = $this->addDaysToDate(SS_Datetime::now(), $this->objFromFixture('SiteConfig', 'default')->ReviewPeriodDays); /** @var Page|SiteTreeContentReview $page */
$this->assertEquals($expected , $nextReviewDate->format('Y-m-d')); $page = new Page();
}
$page->ContentReviewType = "Custom";
public function testGetNextReviewDateFromPageInheritedSetting() { $page->ReviewPeriodDays = 0;
$page = $this->objFromFixture('Page', 'page-1-1');
$nextReviewDate = $page->getReviewDate(); $this->assertFalse($page->advanceReviewDate());
$this->assertInstanceOf('Date', $nextReviewDate); $page->write();
// It should be the same as the parents reviewdate
$expected = $this->objFromFixture('Page', 'page-1')->NextReviewDate; $this->assertEquals(null, $page->NextReviewDate);
$this->assertEquals($expected, $nextReviewDate->format('Y-m-d')); }
}
public function testAdvanceReviewFromCustomSettings()
public function testUpdateNextReviewDateFromCustomToDisabled() { {
$page = $this->objFromFixture('Page', 'custom'); /** @var Page|SiteTreeContentReview $page */
// before write() $page = $this->objFromFixture("Page", "custom");
$this->assertEquals('2010-02-01', $page->NextReviewDate);
$this->assertTrue($page->advanceReviewDate());
// Change and write
$page->ContentReviewType = 'Disabled'; $page->write();
$page->write();
$this->assertEquals(date("Y-m-d", strtotime("now + " . $page->ReviewPeriodDays . " days")), $page->NextReviewDate);
// clear cache }
DataObject::flush_and_destroy_cache();
unset($page); public function testAdvanceReviewFromInheritedSettings()
{
// After write() /** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture('Page', 'custom'); $page = $this->objFromFixture("Page", "page-1-1");
$this->assertNull($page->NextReviewDate);
} /** @var Page|SiteTreeContentReview $parentPage */
$parentPage = $this->objFromFixture("Page", "page-1");
public function testUpdateNextReviewDateFromDisabledToCustom() {
$page = $this->objFromFixture('Page', 'disabled'); $this->assertTrue($page->advanceReviewDate());
// before
$this->assertNull($page->NextReviewDate); $page->write();
// Change and write $this->assertEquals(date("Y-m-d", strtotime("now + " . $parentPage->ReviewPeriodDays . " days")), $page->NextReviewDate);
$page->ContentReviewType = 'Custom'; }
$page->ReviewPeriodDays = '7';
$page->write(); public function testAdvanceReviewFromInheritedSiteConfigSettings()
// clear cache {
DataObject::flush_and_destroy_cache(); /** @var Page|SiteTreeContentReview $page */
unset($page); $page = $this->objFromFixture("Page", "inherit");
// After write() /** @var SiteConfig|ContentReviewDefaultSettings $siteConfig */
$page = $this->objFromFixture('Page', 'disabled'); $siteConfig = $this->objFromFixture("SiteConfig", "default");
$expected = date('Y-m-d', strtotime('+ '.$page->ReviewPeriodDays.' days'));
$this->assertEquals($expected, $page->NextReviewDate); $this->assertTrue($page->advanceReviewDate());
}
$page->write();
public function testParentChangedOptionsAndChildShouldToo() {
$parentPage = $this->objFromFixture('Page', 'page-1'); $this->assertEquals(date("Y-m-d", strtotime("now + " . $siteConfig->ReviewPeriodDays . " days")), $page->NextReviewDate);
$childPage = $this->objFromFixture('Page', 'page-1-1'); }
// BEFORE: parent page have a period of five days, so childPage should have a public function testGetSettingsObjectFromCustom()
// review date LastEdited + 5 days {
$expected = $this->addDaysToDate($childPage->obj('LastEdited'), $parentPage->ReviewPeriodDays); /** @var Page|SiteTreeContentReview $page */
$this->assertEquals($parentPage->NextReviewDate, $childPage->NextReviewDate); $page = $this->objFromFixture("Page", "custom");
$oldChildDate = $childPage->NextReviewDate; $this->assertEquals("Custom", $page->ContentReviewType);
// But if we change the parent page ReviewPeriodDays to 10, the childs should $this->assertEquals($page, $page->getOptions());
// change as well }
$parentPage->ReviewPeriodDays = 10;
$parentPage->write(); public function testGetSettingsObjectFromDisabled()
{
// Flush all the caches! /** @var Page|SiteTreeContentReview $page */
DataObject::flush_and_destroy_cache(); $page = $this->objFromFixture("Page", "disabled");
$parentPage = $this->objFromFixture('Page', 'page-1'); $this->assertEquals("Disabled", $page->ContentReviewType);
$childPage = $this->objFromFixture('Page', 'page-1-1'); $this->assertFalse($page->getOptions());
}
// AFTER: parent page have a period of 10 days, so childPage should have a
// review date now + 10 days public function testGetOptionObjectFromInheritedDisabled()
$this->assertNotEquals($oldChildDate, $childPage->NextReviewDate); {
$this->assertEquals($this->addDaysToDate(date('Y-m-d'), 10), $childPage->NextReviewDate); /** @var Page|SiteTreeContentReview $page */
$this->assertEquals($parentPage->NextReviewDate, $childPage->NextReviewDate); $page = $this->objFromFixture("Page", "page-2-1-1");
}
$this->assertEquals("Inherit", $page->ContentReviewType);
// helper method for this test class $this->assertFalse($page->getOptions());
private function addDaysToDate($date, $days, $format='Y-m-d') { }
if(is_object($date)) {
$sec = strtotime('+ '. $days .' days', $date->format('U')); public function testGetOptionObjectFromDeeplyInheritedPage()
} else { {
$sec = strtotime('+ '. $days .' days', strtotime($date)); /** @var Page|SiteTreeContentReview $page */
} $page = $this->objFromFixture("Page", "page-3-1-1-1");
return date($format, $sec);
} $this->assertEquals("Inherit", $page->ContentReviewType);
} $this->assertInstanceOf("SiteConfig", $page->getOptions());
}
public function testGetSettingsObjectFromInheritPage()
{
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "page-1-1");
/** @var Page|SiteTreeContentReview $parentPage */
$parentPage = $this->objFromFixture("Page", "page-1");
$this->assertEquals("Inherit", $page->ContentReviewType);
$this->assertEquals(get_class($parentPage), get_class($page->getOptions()));
$this->assertEquals($parentPage->ID, $page->getOptions()->ID);
}
public function testGetSettingsObjectFromInheritedRootPage()
{
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "inherit");
$this->assertEquals("Inherit", $page->ContentReviewType);
$this->assertEquals($this->objFromFixture("SiteConfig", "default"), $page->getOptions());
}
public function testGetNextReviewDateFromCustomSettings()
{
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture('Page', 'custom');
$date = $page->getReviewDate();
$this->assertEquals('2010-02-01', $date->format('Y-m-d'));
}
public function testGetNextReviewDateFromSiteConfigInheritedSetting()
{
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "inherit");
$nextReviewDate = $page->getReviewDate();
$this->assertInstanceOf("Date", $nextReviewDate);
/** @var SiteConfig|ContentReviewDefaultSettings $siteConfig */
$siteConfig = $this->objFromFixture("SiteConfig", "default");
$expected = $this->addDaysToDate(SS_Datetime::now(), $siteConfig->ReviewPeriodDays);
$this->assertEquals($expected, $nextReviewDate->format("Y-m-d"));
}
public function testGetNextReviewDateFromPageInheritedSetting()
{
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "page-1-1");
$nextReviewDate = $page->getReviewDate();
$this->assertInstanceOf("Date", $nextReviewDate);
/** @var Page|SiteTreeContentReview $nextPage */
$nextPage = $this->objFromFixture("Page", "page-1");
$expected = $nextPage->NextReviewDate;
$this->assertEquals($expected, $nextReviewDate->format("Y-m-d"));
}
public function testUpdateNextReviewDateFromCustomToDisabled()
{
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "custom");
// before write()
$this->assertEquals("2010-02-01", $page->NextReviewDate);
$page->ContentReviewType = "Disabled";
$page->write();
DataObject::flush_and_destroy_cache();
unset($page);
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "custom");
$this->assertNull($page->NextReviewDate);
}
public function testUpdateNextReviewDateFromDisabledToCustom()
{
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "disabled");
$this->assertNull($page->NextReviewDate);
$page->ContentReviewType = "Custom";
$page->ReviewPeriodDays = "7";
$page->write();
DataObject::flush_and_destroy_cache();
unset($page);
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "disabled");
$expected = date("Y-m-d", strtotime("+ " . $page->ReviewPeriodDays . " days"));
$this->assertEquals($expected, $page->NextReviewDate);
}
public function testParentChangedOptionsAndChildShouldToo()
{
/** @var Page|SiteTreeContentReview $parentPage */
$parentPage = $this->objFromFixture("Page", "page-1");
/** @var Page|SiteTreeContentReview $childPage */
$childPage = $this->objFromFixture("Page", "page-1-1");
// BEFORE: parent page have a period of five days, so childPage should have a
// review date LastEdited + 5 days
$this->assertEquals($parentPage->NextReviewDate, $childPage->NextReviewDate);
$oldChildDate = $childPage->NextReviewDate;
// But if we change the parent page ReviewPeriodDays to 10, the childs should
// change as well
$parentPage->ReviewPeriodDays = 10;
$parentPage->write();
// Flush all the caches!
DataObject::flush_and_destroy_cache();
/** @var Page|SiteTreeContentReview $page */
$parentPage = $this->objFromFixture("Page", "page-1");
/** @var Page|SiteTreeContentReview $page */
$childPage = $this->objFromFixture("Page", "page-1-1");
// AFTER: parent page have a period of 10 days, so childPage should have
// a review date now + 10 days.
$this->assertNotEquals($oldChildDate, $childPage->NextReviewDate);
$this->assertEquals($this->addDaysToDate(date("Y-m-d"), 10), $childPage->NextReviewDate);
$this->assertEquals($parentPage->NextReviewDate, $childPage->NextReviewDate);
}
/**
* @param string|SS_DateTime|DateTime $date
* @param int $days
* @param string $format
*
* @return bool|string
*/
private function addDaysToDate($date, $days, $format = "Y-m-d")
{
if (is_object($date)) {
$sec = strtotime("+ " . $days . " days", $date->format("U"));
} else {
$sec = strtotime("+ " . $days . " days", strtotime($date));
}
return date($format, $sec);
}
}

View File

@ -1,177 +1,284 @@
<?php <?php
class SiteTreeContentReviewTest extends ContentReviewBaseTest { /**
* @mixin PHPUnit_Framework_TestCase
public static $fixture_file = 'contentreview/tests/ContentReviewTest.yml'; */
class SiteTreeContentReviewTest extends ContentReviewBaseTest
protected $requiredExtensions = array( {
"SiteTree" => array("SiteTreeContentReview"), /**
"Group" => array("ContentReviewOwner"), * @var string
"Member" => array("ContentReviewOwner"), */
"CMSPageEditController" => array("ContentReviewCMSExtension"), public static $fixture_file = "contentreview/tests/ContentReviewTest.yml";
"SiteConfig" => array("ContentReviewDefaultSettings"),
);
public function testOwnerNames() {
$editor = $this->objFromFixture('Member', 'editor');
$this->logInAs($editor);
$page = new Page();
$page->ReviewPeriodDays = 10;
$page->ContentReviewType ='Custom';
$page->ContentReviewUsers()->push($editor);
$page->write();
$this->assertTrue($page->canPublish()); /**
$this->assertTrue($page->doPublish()); * @var array
$this->assertEquals($page->OwnerNames, "Test Editor", 'Test Editor should be the owner'); */
protected $requiredExtensions = array(
$page = $this->objFromFixture('Page', 'about'); "SiteTree" => array("SiteTreeContentReview"),
$page->OwnerUsers()->removeAll(); "Group" => array("ContentReviewOwner"),
$page->write(); "Member" => array("ContentReviewOwner"),
"CMSPageEditController" => array("ContentReviewCMSExtension"),
$this->assertTrue($page->canPublish()); "SiteConfig" => array("ContentReviewDefaultSettings"),
$this->assertTrue($page->doPublish()); );
$this->assertEquals('', $page->OwnerNames);
}
public function testPermissionsExists() {
$perms = singleton('SiteTreeContentReview')->providePermissions();
$this->assertTrue(isset($perms['EDIT_CONTENT_REVIEW_FIELDS']));
}
public function testUserWithPermissionCanEdit() {
$editor = $this->objFromFixture('Member', 'editor');
$this->logInAs($editor);
$page = new Page();
$fields = $page->getSettingsFields();
$this->assertNotNull($fields->dataFieldByName('NextReviewDate'));
}
public function testUserWithoutPermissionCannotEdit() {
$author = $this->objFromFixture('Member', 'author');
$this->logInAs($author);
$page = new Page();
$fields = $page->getSettingsFields();
$this->assertNull($fields->dataFieldByName('NextReviewDate'));
}
public function testAutomaticallyToNotSetReviewDate() {
$editor = $this->objFromFixture('Member', 'editor');
$this->logInAs($editor);
$page = new Page();
$page->ReviewPeriodDays = 10;
$page->write();
$this->assertTrue($page->doPublish());
$this->assertEquals(null, $page->NextReviewDate);
}
public function testAddReviewNote() {
$author = $this->objFromFixture('Member', 'author');
$page = $this->objFromFixture('Page', 'home');
$page->addReviewNote($author, 'This is a message');
// Get the page again to make sure it's not only cached in memory
$homepage = $this->objFromFixture('Page', 'home');
$this->assertEquals(1, $homepage->ReviewLogs()->count());
$this->assertEquals('This is a message', $homepage->ReviewLogs()->first()->Note);
}
public function testGetContentReviewOwners() {
$page = $this->objFromFixture('Page', 'group-owned');
$owners = $page->ContentReviewOwners();
$this->assertEquals(1, $owners->count());
$this->assertEquals('author@example.com', $owners->first()->Email);
}
public function testCanNotBeReviewBecauseNoReviewDate() {
SS_Datetime::set_mock_now('2010-01-01 12:00:00');
$author = $this->objFromFixture('Member', 'author');
$page = $this->objFromFixture('Page', 'no-review');
// page 'no-review' is owned by author, but there is no review date
$this->assertFalse($page->canBeReviewedBy($author));
SS_Datetime::clear_mock_now();
}
public function testCanNotBeReviewedBecauseInFuture() {
SS_Datetime::set_mock_now('2010-01-01 12:00:00');
$author = $this->objFromFixture('Member', 'author');
$page = $this->objFromFixture('Page', 'staff');
// page 'staff' is owned by author, but the review date is in the future
$this->assertFalse($page->canBeReviewedBy($author));
SS_Datetime::clear_mock_now();
}
public function testCanNotBeReviewedByUser() {
SS_Datetime::set_mock_now('2010-03-01 12:00:00');
$author = $this->objFromFixture('Member', 'author');
$page = $this->objFromFixture('Page', 'home');
// page 'home' doesnt have any owners
$this->assertFalse($page->canBeReviewedBy($author));
SS_Datetime::clear_mock_now();
}
public function testCanBeReviewedByUser() {
SS_Datetime::set_mock_now('2010-03-01 12:00:00');
$author = $this->objFromFixture('Member', 'author');
$page = $this->objFromFixture('Page', 'staff');
// page 'staff' is owned by author
$this->assertTrue($page->canBeReviewedBy($author));
SS_Datetime::clear_mock_now();
}
public function testCanNotBeReviewedByGroup() {
SS_Datetime::set_mock_now('2010-03-01 12:00:00');
$author = $this->objFromFixture('Member', 'editor');
$page = $this->objFromFixture('Page', 'contact');
// page 'contact' is owned by the authorgroup
$this->assertFalse($page->canBeReviewedBy($author));
SS_Datetime::clear_mock_now();
}
public function testCanBeReviewedByGroup() {
SS_Datetime::set_mock_now('2010-03-01 12:00:00');
$author = $this->objFromFixture('Member', 'author');
$page = $this->objFromFixture('Page', 'contact');
// page 'contact' is owned by the authorgroup
$this->assertTrue($page->canBeReviewedBy($author));
SS_Datetime::clear_mock_now();
}
public function testCanBeReviewedFromInheritedSetting() {
SS_Datetime::set_mock_now('2013-03-01 12:00:00');
$author = $this->objFromFixture('Member', 'author');
$parentPage = $this->objFromFixture('Page', 'contact');
// This saves the parentPages.NextReview date to the child page
$parentPage->NextReviewDate = '2013-01-01';
$parentPage->write();
$page = $this->objFromFixture('Page', 'contact-child');
$this->assertTrue($page->canBeReviewedBy($author));
SS_Datetime::clear_mock_now();
}
public function testReviewActionVisibleForAuthor() {
SS_Datetime::set_mock_now('2020-03-01 12:00:00');
$page = $this->objFromFixture('Page', 'contact');
$author = $this->objFromFixture('Member', 'author');
$this->logInAs($author);
$fields = $page->getCMSActions(); public function testOwnerNames()
$this->assertNotNull($fields->fieldByName('action_reviewed')); {
SS_Datetime::clear_mock_now(); /** @var Member $editor */
} $editor = $this->objFromFixture("Member", "editor");
public function testReviewActionNotVisibleForEditor() { $this->logInAs($editor);
SS_Datetime::set_mock_now('2020-03-01 12:00:00');
$page = $this->objFromFixture('Page', 'contact'); /** @var Page|SiteTreeContentReview $page */
$author = $this->objFromFixture('Member', 'editor'); $page = new Page();
$this->logInAs($author); $page->ReviewPeriodDays = 10;
$page->ContentReviewType = "Custom";
$fields = $page->getCMSActions();
$this->assertNull($fields->fieldByName('action_reviewed')); $page->ContentReviewUsers()->push($editor);
SS_Datetime::clear_mock_now(); $page->write();
}
$this->assertTrue($page->canPublish());
$this->assertTrue($page->doPublish());
$this->assertEquals($page->OwnerNames, "Test Editor", "Test Editor should be the owner");
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "about");
$page->OwnerUsers()->removeAll();
$page->write();
$this->assertTrue($page->canPublish());
$this->assertTrue($page->doPublish());
$this->assertEquals("", $page->OwnerNames);
}
public function testPermissionsExists()
{
$perms = singleton("SiteTreeContentReview")->providePermissions();
$this->assertTrue(isset($perms["EDIT_CONTENT_REVIEW_FIELDS"]));
}
public function testUserWithPermissionCanEdit()
{
/** @var Member $editor */
$editor = $this->objFromFixture("Member", "editor");
$this->logInAs($editor);
/** @var Page|SiteTreeContentReview $page */
$page = new Page();
$fields = $page->getSettingsFields();
$this->assertNotNull($fields->dataFieldByName("NextReviewDate"));
}
public function testUserWithoutPermissionCannotEdit()
{
/** @var Member $author */
$author = $this->objFromFixture("Member", "author");
$this->logInAs($author);
/** @var Page|SiteTreeContentReview $page */
$page = new Page();
$fields = $page->getSettingsFields();
$this->assertNull($fields->dataFieldByName("NextReviewDate"));
}
public function testAutomaticallyToNotSetReviewDate()
{
/** @var Member $editor */
$editor = $this->objFromFixture("Member", "editor");
$this->logInAs($editor);
/** @var Page|SiteTreeContentReview $page */
$page = new Page();
$page->ReviewPeriodDays = 10;
$page->write();
$this->assertTrue($page->doPublish());
$this->assertEquals(null, $page->NextReviewDate);
}
public function testAddReviewNote()
{
/** @var Member $author */
$author = $this->objFromFixture("Member", "author");
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "home");
$page->addReviewNote($author, "This is a message");
/** @var Page|SiteTreeContentReview $page */
$homepage = $this->objFromFixture("Page", "home");
$this->assertEquals(1, $homepage->ReviewLogs()->count());
$this->assertEquals("This is a message", $homepage->ReviewLogs()->first()->Note);
}
public function testGetContentReviewOwners()
{
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "group-owned");
$owners = $page->ContentReviewOwners();
$this->assertEquals(1, $owners->count());
$this->assertEquals("author@example.com", $owners->first()->Email);
}
public function testCanNotBeReviewBecauseNoReviewDate()
{
SS_Datetime::set_mock_now("2010-01-01 12:00:00");
/** @var Member $author */
$author = $this->objFromFixture("Member", "author");
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "no-review");
$this->assertFalse($page->canBeReviewedBy($author));
SS_Datetime::clear_mock_now();
}
public function testCanNotBeReviewedBecauseInFuture()
{
SS_Datetime::set_mock_now("2010-01-01 12:00:00");
/** @var Member $author */
$author = $this->objFromFixture("Member", "author");
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "staff");
$this->assertFalse($page->canBeReviewedBy($author));
SS_Datetime::clear_mock_now();
}
public function testCanNotBeReviewedByUser()
{
SS_Datetime::set_mock_now("2010-03-01 12:00:00");
/** @var Member $author */
$author = $this->objFromFixture("Member", "author");
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "home");
$this->assertFalse($page->canBeReviewedBy($author));
SS_Datetime::clear_mock_now();
}
public function testCanBeReviewedByUser()
{
SS_Datetime::set_mock_now("2010-03-01 12:00:00");
/** @var Member $author */
$author = $this->objFromFixture("Member", "author");
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "staff");
$this->assertTrue($page->canBeReviewedBy($author));
SS_Datetime::clear_mock_now();
}
public function testCanNotBeReviewedByGroup()
{
SS_Datetime::set_mock_now("2010-03-01 12:00:00");
/** @var Member $author */
$author = $this->objFromFixture("Member", "editor");
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "contact");
$this->assertFalse($page->canBeReviewedBy($author));
SS_Datetime::clear_mock_now();
}
public function testCanBeReviewedByGroup()
{
SS_Datetime::set_mock_now("2010-03-01 12:00:00");
/** @var Member $author */
$author = $this->objFromFixture("Member", "author");
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "contact");
$this->assertTrue($page->canBeReviewedBy($author));
SS_Datetime::clear_mock_now();
}
public function testCanBeReviewedFromInheritedSetting()
{
SS_Datetime::set_mock_now("2013-03-01 12:00:00");
/** @var Member $author */
$author = $this->objFromFixture("Member", "author");
/** @var Page|SiteTreeContentReview $parentPage */
$parentPage = $this->objFromFixture("Page", "contact");
$parentPage->NextReviewDate = "2013-01-01";
$parentPage->write();
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "contact-child");
$this->assertTrue($page->canBeReviewedBy($author));
SS_Datetime::clear_mock_now();
}
public function testReviewActionVisibleForAuthor()
{
SS_Datetime::set_mock_now("2020-03-01 12:00:00");
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "contact");
/** @var Member $author */
$author = $this->objFromFixture("Member", "author");
$this->logInAs($author);
$fields = $page->getCMSActions();
$this->assertNotNull($fields->fieldByName("action_reviewed"));
SS_Datetime::clear_mock_now();
}
public function testReviewActionNotVisibleForEditor()
{
SS_Datetime::set_mock_now("2020-03-01 12:00:00");
/** @var Page|SiteTreeContentReview $page */
$page = $this->objFromFixture("Page", "contact");
/** @var Member $author */
$author = $this->objFromFixture("Member", "editor");
$this->logInAs($author);
$fields = $page->getCMSActions();
$this->assertNull($fields->fieldByName("action_reviewed"));
SS_Datetime::clear_mock_now();
}
} }