Reformat as PSR-2

This commit is contained in:
Damian Mooyman 2016-02-19 13:48:25 +13:00
parent c2fee6bd33
commit 4b31713128
21 changed files with 3368 additions and 3041 deletions

View File

@ -13,7 +13,8 @@
* *
* @package comments * @package comments
*/ */
class Commenting { class Commenting
{
/** /**
* Adds commenting to a {@link DataObject} * Adds commenting to a {@link DataObject}
@ -26,13 +27,16 @@ class Commenting {
* *
* @throws InvalidArgumentException * @throws InvalidArgumentException
*/ */
public static function add($class, $settings = false) { public static function add($class, $settings = false)
{
Deprecation::notice('2.0', 'Using Commenting::add is deprecated. Please use the config API instead'); Deprecation::notice('2.0', 'Using Commenting::add is deprecated. Please use the config API instead');
Config::inst()->update($class, 'extensions', array('CommentsExtension')); Config::inst()->update($class, 'extensions', array('CommentsExtension'));
// Check if settings must be customised // Check if settings must be customised
if($settings === false) return; if ($settings === false) {
if(!is_array($settings)) { return;
}
if (!is_array($settings)) {
throw new InvalidArgumentException('$settings needs to be an array or null'); throw new InvalidArgumentException('$settings needs to be an array or null');
} }
Config::inst()->update($class, 'comments', $settings); Config::inst()->update($class, 'comments', $settings);
@ -46,7 +50,8 @@ class Commenting {
* *
* @param string $class Class to remove {@link CommentsExtension} from * @param string $class Class to remove {@link CommentsExtension} from
*/ */
public static function remove($class) { public static function remove($class)
{
Deprecation::notice('2.0', 'Using Commenting::remove is deprecated. Please use the config API instead'); Deprecation::notice('2.0', 'Using Commenting::remove is deprecated. Please use the config API instead');
$class::remove_extension('CommentsExtension'); $class::remove_extension('CommentsExtension');
} }
@ -58,7 +63,8 @@ class Commenting {
* *
* @return bool * @return bool
*/ */
public static function has_commenting($class) { public static function has_commenting($class)
{
Deprecation::notice('2.0', 'Using Commenting::has_commenting is deprecated. Please use the config API instead'); Deprecation::notice('2.0', 'Using Commenting::has_commenting is deprecated. Please use the config API instead');
return $class::has_extension('CommentsExtension'); return $class::has_extension('CommentsExtension');
} }
@ -74,9 +80,12 @@ class Commenting {
* @param string $key setting to change * @param string $key setting to change
* @param mixed $value value of the setting * @param mixed $value value of the setting
*/ */
public static function set_config_value($class, $key, $value = false) { public static function set_config_value($class, $key, $value = false)
{
Deprecation::notice('2.0', 'Commenting::set_config_value is deprecated. Use the config api instead'); Deprecation::notice('2.0', 'Commenting::set_config_value is deprecated. Use the config api instead');
if($class === "all") $class = 'CommentsExtension'; if ($class === "all") {
$class = 'CommentsExtension';
}
Config::inst()->update($class, 'comments', array($key => $value)); Config::inst()->update($class, 'comments', array($key => $value));
} }
@ -91,7 +100,8 @@ class Commenting {
* @throws Exception * @throws Exception
* @return mixed * @return mixed
*/ */
public static function get_config_value($class, $key) { public static function get_config_value($class, $key)
{
Deprecation::notice( Deprecation::notice(
'2.0', '2.0',
'Using Commenting::get_config_value is deprecated. Please use $parent->getCommentsOption() or ' 'Using Commenting::get_config_value is deprecated. Please use $parent->getCommentsOption() or '
@ -99,9 +109,9 @@ class Commenting {
); );
// Get settings // Get settings
if(!$class) { if (!$class) {
$class = 'CommentsExtension'; $class = 'CommentsExtension';
} elseif(!$class::has_extension('CommentsExtension')) { } elseif (!$class::has_extension('CommentsExtension')) {
throw new InvalidArgumentException("$class does not have commenting enabled"); throw new InvalidArgumentException("$class does not have commenting enabled");
} }
return singleton($class)->getCommentsOption($key); return singleton($class)->getCommentsOption($key);
@ -118,9 +128,12 @@ class Commenting {
* @param string $value Expected value * @param string $value Expected value
* @return boolean * @return boolean
*/ */
public static function config_value_equals($class, $key, $value) { public static function config_value_equals($class, $key, $value)
{
$check = self::get_config_value($class, $key); $check = self::get_config_value($class, $key);
if($check && ($check == $value)) return true; if ($check && ($check == $value)) {
return true;
}
} }
/** /**
@ -131,13 +144,16 @@ class Commenting {
* @param string $class * @param string $class
* @return boolean true * @return boolean true
*/ */
public static function can_member_post($class) { public static function can_member_post($class)
{
Deprecation::notice('2.0', 'Use $instance->canPostComment() directly instead'); Deprecation::notice('2.0', 'Use $instance->canPostComment() directly instead');
$member = Member::currentUser(); $member = Member::currentUser();
// Check permission // Check permission
$permission = self::get_config_value($class, 'required_permission'); $permission = self::get_config_value($class, 'required_permission');
if($permission && !Permission::check($permission)) return false; if ($permission && !Permission::check($permission)) {
return false;
}
// Check login required // Check login required
$requireLogin = self::get_config_value($class, 'require_login'); $requireLogin = self::get_config_value($class, 'require_login');

View File

@ -5,7 +5,8 @@
* *
* @package comments * @package comments
*/ */
class CommentAdmin extends LeftAndMain implements PermissionProvider { class CommentAdmin extends LeftAndMain implements PermissionProvider
{
private static $url_segment = 'comments'; private static $url_segment = 'comments';
@ -24,7 +25,8 @@ class CommentAdmin extends LeftAndMain implements PermissionProvider {
'unmoderated' 'unmoderated'
); );
public function providePermissions() { public function providePermissions()
{
return array( return array(
"CMS_ACCESS_CommentAdmin" => array( "CMS_ACCESS_CommentAdmin" => array(
'name' => _t('CommentAdmin.ADMIN_PERMISSION', "Access to 'Comments' section"), 'name' => _t('CommentAdmin.ADMIN_PERMISSION', "Access to 'Comments' section"),
@ -36,13 +38,16 @@ class CommentAdmin extends LeftAndMain implements PermissionProvider {
/** /**
* @return Form * @return Form
*/ */
public function getEditForm($id = null, $fields = null) { public function getEditForm($id = null, $fields = null)
if(!$id) $id = $this->currentPageID(); {
if (!$id) {
$id = $this->currentPageID();
}
$form = parent::getEditForm($id); $form = parent::getEditForm($id);
$record = $this->getRecord($id); $record = $this->getRecord($id);
if($record && !$record->canView()) { if ($record && !$record->canView()) {
return Security::permissionFailure($this); return Security::permissionFailure($this);
} }
@ -106,7 +111,7 @@ class CommentAdmin extends LeftAndMain implements PermissionProvider {
$form->addExtraClass('cms-edit-form'); $form->addExtraClass('cms-edit-form');
$form->setTemplate($this->getTemplatesWithSuffix('_EditForm')); $form->setTemplate($this->getTemplatesWithSuffix('_EditForm'));
if($form->Fields()->hasTabset()) { if ($form->Fields()->hasTabset()) {
$form->Fields()->findOrMakeTab('Root')->setTemplate('CMSTabSet'); $form->Fields()->findOrMakeTab('Root')->setTemplate('CMSTabSet');
$form->addExtraClass('center ss-tabset cms-tabset ' . $this->BaseCSSClasses()); $form->addExtraClass('center ss-tabset cms-tabset ' . $this->BaseCSSClasses());
} }

View File

@ -1,15 +1,17 @@
<?php <?php
class CommentsGridField extends GridField { class CommentsGridField extends GridField
{
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
protected function newRow($total, $index, $record, $attributes, $content) { protected function newRow($total, $index, $record, $attributes, $content)
if(!isset($attributes['class'])) { {
if (!isset($attributes['class'])) {
$attributes['class'] = ''; $attributes['class'] = '';
} }
if($record->IsSpam) { if ($record->IsSpam) {
$attributes['class'] .= ' spam'; $attributes['class'] .= ' spam';
} }

View File

@ -1,11 +1,13 @@
<?php <?php
class CommentsGridFieldAction implements GridField_ColumnProvider, GridField_ActionProvider { class CommentsGridFieldAction implements GridField_ColumnProvider, GridField_ActionProvider
{
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function augmentColumns($gridField, &$columns) { public function augmentColumns($gridField, &$columns)
if(!in_array('Actions', $columns)) { {
if (!in_array('Actions', $columns)) {
$columns[] = 'Actions'; $columns[] = 'Actions';
} }
} }
@ -13,15 +15,17 @@ class CommentsGridFieldAction implements GridField_ColumnProvider, GridField_Act
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function getColumnAttributes($gridField, $record, $columnName) { public function getColumnAttributes($gridField, $record, $columnName)
{
return array('class' => 'col-buttons'); return array('class' => 'col-buttons');
} }
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function getColumnMetadata($gridField, $columnName) { public function getColumnMetadata($gridField, $columnName)
if($columnName == 'Actions') { {
if ($columnName == 'Actions') {
return array('title' => ''); return array('title' => '');
} }
} }
@ -29,19 +33,23 @@ class CommentsGridFieldAction implements GridField_ColumnProvider, GridField_Act
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function getColumnsHandled($gridField) { public function getColumnsHandled($gridField)
{
return array('Actions'); return array('Actions');
} }
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function getColumnContent($gridField, $record, $columnName) { public function getColumnContent($gridField, $record, $columnName)
if(!$record->canEdit()) return; {
if (!$record->canEdit()) {
return;
}
$field = ""; $field = "";
if(!$record->IsSpam || !$record->Moderated) { if (!$record->IsSpam || !$record->Moderated) {
$field .= GridField_FormAction::create( $field .= GridField_FormAction::create(
$gridField, $gridField,
'CustomAction' . $record->ID . 'Spam', 'CustomAction' . $record->ID . 'Spam',
@ -51,7 +59,7 @@ class CommentsGridFieldAction implements GridField_ColumnProvider, GridField_Act
)->Field(); )->Field();
} }
if($record->IsSpam || !$record->Moderated) { if ($record->IsSpam || !$record->Moderated) {
$field .= GridField_FormAction::create( $field .= GridField_FormAction::create(
$gridField, $gridField,
'CustomAction' . $record->ID . 'Approve', 'CustomAction' . $record->ID . 'Approve',
@ -67,15 +75,17 @@ class CommentsGridFieldAction implements GridField_ColumnProvider, GridField_Act
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function getActions($gridField) { public function getActions($gridField)
{
return array('spam', 'approve'); return array('spam', 'approve');
} }
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function handleAction(GridField $gridField, $actionName, $arguments, $data) { public function handleAction(GridField $gridField, $actionName, $arguments, $data)
if($actionName == 'spam') { {
if ($actionName == 'spam') {
$comment = Comment::get()->byID($arguments["RecordID"]); $comment = Comment::get()->byID($arguments["RecordID"]);
$comment->markSpam(); $comment->markSpam();
@ -86,7 +96,7 @@ class CommentsGridFieldAction implements GridField_ColumnProvider, GridField_Act
); );
} }
if($actionName == 'approve') { if ($actionName == 'approve') {
$comment = Comment::get()->byID($arguments["RecordID"]); $comment = Comment::get()->byID($arguments["RecordID"]);
$comment->markApproved(); $comment->markApproved();

View File

@ -3,8 +3,8 @@
/** /**
* @package comments * @package comments
*/ */
class CommentsGridFieldBulkAction extends GridFieldBulkActionHandler { class CommentsGridFieldBulkAction extends GridFieldBulkActionHandler
{
} }
/** /**
@ -12,7 +12,8 @@ class CommentsGridFieldBulkAction extends GridFieldBulkActionHandler {
* *
* @package comments * @package comments
*/ */
class CommentsGridFieldBulkAction_Handlers extends CommentsGridFieldBulkAction { class CommentsGridFieldBulkAction_Handlers extends CommentsGridFieldBulkAction
{
private static $allowed_actions = array( private static $allowed_actions = array(
'spam', 'spam',
@ -25,10 +26,11 @@ class CommentsGridFieldBulkAction_Handlers extends CommentsGridFieldBulkAction {
); );
public function spam(SS_HTTPRequest $request) { public function spam(SS_HTTPRequest $request)
{
$ids = array(); $ids = array();
foreach($this->getRecords() as $record) { foreach ($this->getRecords() as $record) {
array_push($ids, $record->ID); array_push($ids, $record->ID);
$record->markSpam(); $record->markSpam();
} }
@ -44,10 +46,11 @@ class CommentsGridFieldBulkAction_Handlers extends CommentsGridFieldBulkAction {
} }
public function approve(SS_HTTPRequest $request) { public function approve(SS_HTTPRequest $request)
{
$ids = array(); $ids = array();
foreach($this->getRecords() as $record) { foreach ($this->getRecords() as $record) {
array_push($ids, $record->ID); array_push($ids, $record->ID);
$record->markApproved(); $record->markApproved();
} }

View File

@ -1,7 +1,9 @@
<?php <?php
class CommentsGridFieldConfig extends GridFieldConfig_RecordEditor { class CommentsGridFieldConfig extends GridFieldConfig_RecordEditor
public function __construct($itemsPerPage = 25) { {
public function __construct($itemsPerPage = 25)
{
parent::__construct($itemsPerPage); parent::__construct($itemsPerPage);
// $this->addComponent(new GridFieldExportButton()); // $this->addComponent(new GridFieldExportButton());
@ -11,7 +13,7 @@ class CommentsGridFieldConfig extends GridFieldConfig_RecordEditor {
// Format column // Format column
$columns = $this->getComponentByType('GridFieldDataColumns'); $columns = $this->getComponentByType('GridFieldDataColumns');
$columns->setFieldFormatting(array( $columns->setFieldFormatting(array(
'ParentTitle' => function($value, &$item) { 'ParentTitle' => function ($value, &$item) {
return sprintf( return sprintf(
'<a href="%s" class="cms-panel-link external-link action" target="_blank">%s</a>', '<a href="%s" class="cms-panel-link external-link action" target="_blank">%s</a>',
Convert::raw2att($item->Link()), Convert::raw2att($item->Link()),

View File

@ -4,7 +4,8 @@
* @package comments * @package comments
*/ */
class CommentingController extends Controller { class CommentingController extends Controller
{
private static $allowed_actions = array( private static $allowed_actions = array(
'delete', 'delete',
@ -67,7 +68,8 @@ class CommentingController extends Controller {
* *
* @param string $class * @param string $class
*/ */
public function setBaseClass($class) { public function setBaseClass($class)
{
$this->baseClass = $class; $this->baseClass = $class;
} }
@ -76,7 +78,8 @@ class CommentingController extends Controller {
* *
* @return string * @return string
*/ */
public function getBaseClass() { public function getBaseClass()
{
return $this->baseClass; return $this->baseClass;
} }
@ -85,7 +88,8 @@ class CommentingController extends Controller {
* *
* @param DataObject $record * @param DataObject $record
*/ */
public function setOwnerRecord($record) { public function setOwnerRecord($record)
{
$this->ownerRecord = $record; $this->ownerRecord = $record;
} }
@ -94,7 +98,8 @@ class CommentingController extends Controller {
* *
* @return DataObject * @return DataObject
*/ */
public function getOwnerRecord() { public function getOwnerRecord()
{
return $this->ownerRecord; return $this->ownerRecord;
} }
@ -103,7 +108,8 @@ class CommentingController extends Controller {
* *
* @param Controller $controller * @param Controller $controller
*/ */
public function setOwnerController($controller) { public function setOwnerController($controller)
{
$this->ownerController = $controller; $this->ownerController = $controller;
} }
@ -112,7 +118,8 @@ class CommentingController extends Controller {
* *
* @return Controller * @return Controller
*/ */
public function getOwnerController() { public function getOwnerController()
{
return $this->ownerController; return $this->ownerController;
} }
@ -122,14 +129,15 @@ class CommentingController extends Controller {
* @param string $key * @param string $key
* @return mixed Result if the setting is available, or null otherwise * @return mixed Result if the setting is available, or null otherwise
*/ */
public function getOption($key) { public function getOption($key)
{
// If possible use the current record // If possible use the current record
if($record = $this->getOwnerRecord()) { if ($record = $this->getOwnerRecord()) {
return $record->getCommentsOption($key); return $record->getCommentsOption($key);
} }
// Otherwise a singleton of that record // Otherwise a singleton of that record
if($class = $this->getBaseClass()) { if ($class = $this->getBaseClass()) {
return singleton($class)->getCommentsOption($key); return singleton($class)->getCommentsOption($key);
} }
@ -142,8 +150,9 @@ class CommentingController extends Controller {
* *
* @return string * @return string
*/ */
public function Link($action = '', $id = '', $other = '') { public function Link($action = '', $id = '', $other = '')
return Controller::join_links(Director::baseURL(), __CLASS__ , $action, $id, $other); {
return Controller::join_links(Director::baseURL(), __CLASS__, $action, $id, $other);
} }
/** /**
@ -151,7 +160,8 @@ class CommentingController extends Controller {
* *
* @return HTMLText * @return HTMLText
*/ */
public function rss() { public function rss()
{
return $this->getFeed($this->request)->outputToBrowser(); return $this->getFeed($this->request)->outputToBrowser();
} }
@ -167,13 +177,14 @@ class CommentingController extends Controller {
* *
* @return RSSFeed * @return RSSFeed
*/ */
public function getFeed(SS_HTTPRequest $request) { public function getFeed(SS_HTTPRequest $request)
{
$link = $this->Link('rss'); $link = $this->Link('rss');
$class = $request->param('ID'); $class = $request->param('ID');
$id = $request->param('OtherID'); $id = $request->param('OtherID');
// Support old pageid param // Support old pageid param
if(!$id && !$class && ($id = $request->getVar('pageid'))) { if (!$id && !$class && ($id = $request->getVar('pageid'))) {
$class = 'SiteTree'; $class = 'SiteTree';
} }
@ -183,8 +194,8 @@ class CommentingController extends Controller {
)); ));
// Check if class filter // Check if class filter
if($class) { if ($class) {
if(!is_subclass_of($class, 'DataObject') || !$class::has_extension('CommentsExtension')) { if (!is_subclass_of($class, 'DataObject') || !$class::has_extension('CommentsExtension')) {
return $this->httpError(404); return $this->httpError(404);
} }
$this->setBaseClass($class); $this->setBaseClass($class);
@ -192,7 +203,7 @@ class CommentingController extends Controller {
$link = Controller::join_links($link, $class); $link = Controller::join_links($link, $class);
// Check if id filter // Check if id filter
if($id) { if ($id) {
$comments = $comments->filter('ParentID', $id); $comments = $comments->filter('ParentID', $id);
$link = Controller::join_links($link, $id); $link = Controller::join_links($link, $id);
$this->setOwnerRecord(DataObject::get_by_id($class, $id)); $this->setOwnerRecord(DataObject::get_by_id($class, $id));
@ -216,13 +227,18 @@ class CommentingController extends Controller {
/** /**
* Deletes a given {@link Comment} via the URL. * Deletes a given {@link Comment} via the URL.
*/ */
public function delete() { public function delete()
{
$comment = $this->getComment(); $comment = $this->getComment();
if(!$comment) return $this->httpError(404); if (!$comment) {
if(!$comment->canDelete()) { return $this->httpError(404);
}
if (!$comment->canDelete()) {
return Security::permissionFailure($this, 'You do not have permission to delete this comment'); return Security::permissionFailure($this, 'You do not have permission to delete this comment');
} }
if(!$comment->getSecurityToken()->checkRequest($this->request)) return $this->httpError(400); if (!$comment->getSecurityToken()->checkRequest($this->request)) {
return $this->httpError(400);
}
$comment->delete(); $comment->delete();
@ -234,13 +250,18 @@ class CommentingController extends Controller {
/** /**
* Marks a given {@link Comment} as spam. Removes the comment from display * Marks a given {@link Comment} as spam. Removes the comment from display
*/ */
public function spam() { public function spam()
{
$comment = $this->getComment(); $comment = $this->getComment();
if(!$comment) return $this->httpError(404); if (!$comment) {
if(!$comment->canEdit()) { return $this->httpError(404);
}
if (!$comment->canEdit()) {
return Security::permissionFailure($this, 'You do not have permission to edit this comment'); return Security::permissionFailure($this, 'You do not have permission to edit this comment');
} }
if(!$comment->getSecurityToken()->checkRequest($this->request)) return $this->httpError(400); if (!$comment->getSecurityToken()->checkRequest($this->request)) {
return $this->httpError(400);
}
$comment->markSpam(); $comment->markSpam();
return $this->renderChangedCommentState($comment); return $this->renderChangedCommentState($comment);
@ -249,13 +270,18 @@ class CommentingController extends Controller {
/** /**
* Marks a given {@link Comment} as ham (not spam). * Marks a given {@link Comment} as ham (not spam).
*/ */
public function ham() { public function ham()
{
$comment = $this->getComment(); $comment = $this->getComment();
if(!$comment) return $this->httpError(404); if (!$comment) {
if(!$comment->canEdit()) { return $this->httpError(404);
}
if (!$comment->canEdit()) {
return Security::permissionFailure($this, 'You do not have permission to edit this comment'); return Security::permissionFailure($this, 'You do not have permission to edit this comment');
} }
if(!$comment->getSecurityToken()->checkRequest($this->request)) return $this->httpError(400); if (!$comment->getSecurityToken()->checkRequest($this->request)) {
return $this->httpError(400);
}
$comment->markApproved(); $comment->markApproved();
return $this->renderChangedCommentState($comment); return $this->renderChangedCommentState($comment);
@ -264,13 +290,18 @@ class CommentingController extends Controller {
/** /**
* Marks a given {@link Comment} as approved. * Marks a given {@link Comment} as approved.
*/ */
public function approve() { public function approve()
{
$comment = $this->getComment(); $comment = $this->getComment();
if(!$comment) return $this->httpError(404); if (!$comment) {
if(!$comment->canEdit()) { return $this->httpError(404);
}
if (!$comment->canEdit()) {
return Security::permissionFailure($this, 'You do not have permission to approve this comment'); return Security::permissionFailure($this, 'You do not have permission to approve this comment');
} }
if(!$comment->getSecurityToken()->checkRequest($this->request)) return $this->httpError(400); if (!$comment->getSecurityToken()->checkRequest($this->request)) {
return $this->httpError(400);
}
$comment->markApproved(); $comment->markApproved();
return $this->renderChangedCommentState($comment); return $this->renderChangedCommentState($comment);
@ -281,7 +312,8 @@ class CommentingController extends Controller {
* are allowed to avoid phishing. If it's an AJAX request render the * are allowed to avoid phishing. If it's an AJAX request render the
* comment in it's new state * comment in it's new state
*/ */
private function renderChangedCommentState($comment) { private function renderChangedCommentState($comment)
{
$referer = $this->request->getHeader('Referer'); $referer = $this->request->getHeader('Referer');
// Render comment using AJAX // Render comment using AJAX
@ -295,7 +327,7 @@ class CommentingController extends Controller {
// Redirect to the comment, but check for phishing // Redirect to the comment, but check for phishing
$url = $referer . '#comment-' . $comment->ID; $url = $referer . '#comment-' . $comment->ID;
// absolute redirection URLs not located on this site may cause phishing // absolute redirection URLs not located on this site may cause phishing
if(Director::is_site_url($url)) { if (Director::is_site_url($url)) {
return $this->redirect($url); return $this->redirect($url);
} else { } else {
return false; return false;
@ -310,13 +342,14 @@ class CommentingController extends Controller {
* *
* @return Comment|false * @return Comment|false
*/ */
public function getComment() { public function getComment()
{
$id = isset($this->urlParams['ID']) ? $this->urlParams['ID'] : false; $id = isset($this->urlParams['ID']) ? $this->urlParams['ID'] : false;
if($id) { if ($id) {
$comment = DataObject::get_by_id('Comment', $id); $comment = DataObject::get_by_id('Comment', $id);
if($comment) { if ($comment) {
$this->fallbackReturnURL = $comment->Link(); $this->fallbackReturnURL = $comment->Link();
return $comment; return $comment;
} }
@ -330,7 +363,8 @@ class CommentingController extends Controller {
* *
* @param Comment $comment * @param Comment $comment
*/ */
public function ReplyForm($comment) { public function ReplyForm($comment)
{
// Enables multiple forms with different names to use the same handler // Enables multiple forms with different names to use the same handler
$form = $this->CommentsForm(); $form = $this->CommentsForm();
$form->setName('ReplyForm_'.$comment->ID); $form->setName('ReplyForm_'.$comment->ID);
@ -355,11 +389,12 @@ class CommentingController extends Controller {
* *
* @param SS_HTTPRequest $request * @param SS_HTTPRequest $request
*/ */
public function reply(SS_HTTPRequest $request) { public function reply(SS_HTTPRequest $request)
{
// Extract parent comment from reply and build this way // Extract parent comment from reply and build this way
if($parentID = $request->param('ParentCommentID')) { if ($parentID = $request->param('ParentCommentID')) {
$comment = DataObject::get_by_id('Comment', $parentID, true); $comment = DataObject::get_by_id('Comment', $parentID, true);
if($comment) { if ($comment) {
return $this->ReplyForm($comment); return $this->ReplyForm($comment);
} }
} }
@ -371,7 +406,8 @@ class CommentingController extends Controller {
* *
* @return Form * @return Form
*/ */
public function CommentsForm() { public function CommentsForm()
{
$usePreview = $this->getOption('use_preview'); $usePreview = $this->getOption('use_preview');
$nameRequired = _t('CommentInterface.YOURNAME_MESSAGE_REQUIRED', 'Please enter your name'); $nameRequired = _t('CommentInterface.YOURNAME_MESSAGE_REQUIRED', 'Please enter your name');
@ -415,7 +451,7 @@ class CommentingController extends Controller {
// Preview formatted comment. Makes most sense when shortcodes or // Preview formatted comment. Makes most sense when shortcodes or
// limited HTML is allowed. Populated by JS/Ajax. // limited HTML is allowed. Populated by JS/Ajax.
if($usePreview) { if ($usePreview) {
$fields->insertAfter( $fields->insertAfter(
ReadonlyField::create('PreviewComment', _t('CommentInterface.PREVIEWLABEL', 'Preview')) ReadonlyField::create('PreviewComment', _t('CommentInterface.PREVIEWLABEL', 'Preview'))
->setAttribute('style', 'display: none'), // enable through JS ->setAttribute('style', 'display: none'), // enable through JS
@ -429,7 +465,7 @@ class CommentingController extends Controller {
$actions = new FieldList( $actions = new FieldList(
new FormAction("doPostComment", _t('CommentInterface.POST', 'Post')) new FormAction("doPostComment", _t('CommentInterface.POST', 'Post'))
); );
if($usePreview) { if ($usePreview) {
$actions->push( $actions->push(
FormAction::create('doPreviewComment', _t('CommentInterface.PREVIEW', 'Preview')) FormAction::create('doPreviewComment', _t('CommentInterface.PREVIEW', 'Preview'))
->addExtraClass('action-minor') ->addExtraClass('action-minor')
@ -444,11 +480,11 @@ class CommentingController extends Controller {
$form = new Form($this, 'CommentsForm', $fields, $actions, $required); $form = new Form($this, 'CommentsForm', $fields, $actions, $required);
// if the record exists load the extra required data // if the record exists load the extra required data
if($record = $this->getOwnerRecord()) { if ($record = $this->getOwnerRecord()) {
// Load member data // Load member data
$member = Member::currentUser(); $member = Member::currentUser();
if(($record->CommentsRequireLogin || $record->PostingRequiredPermission) && $member) { if (($record->CommentsRequireLogin || $record->PostingRequiredPermission) && $member) {
$fields = $form->Fields(); $fields = $form->Fields();
$fields->removeByName('Name'); $fields->removeByName('Name');
@ -471,7 +507,7 @@ class CommentingController extends Controller {
$form->setRedirectToFormOnValidationError(true); $form->setRedirectToFormOnValidationError(true);
// load any data from the cookies // load any data from the cookies
if($data = Cookie::get('CommentsForm_UserData')) { if ($data = Cookie::get('CommentsForm_UserData')) {
$data = Convert::json2array($data); $data = Convert::json2array($data);
$form->loadDataFrom(array( $form->loadDataFrom(array(
@ -481,12 +517,12 @@ class CommentingController extends Controller {
)); ));
// allow previous value to fill if comment not stored in cookie (i.e. validation error) // allow previous value to fill if comment not stored in cookie (i.e. validation error)
$prevComment = Cookie::get('CommentsForm_Comment'); $prevComment = Cookie::get('CommentsForm_Comment');
if($prevComment && $prevComment != ''){ if ($prevComment && $prevComment != '') {
$form->loadDataFrom(array("Comment" => $prevComment)); $form->loadDataFrom(array("Comment" => $prevComment));
} }
} }
if(!empty($member)) { if (!empty($member)) {
$form->loadDataFrom($member); $form->loadDataFrom($member);
} }
@ -502,15 +538,18 @@ class CommentingController extends Controller {
* @param array $data * @param array $data
* @param Form $form * @param Form $form
*/ */
public function doPostComment($data, $form) { public function doPostComment($data, $form)
{
// Load class and parent from data // Load class and parent from data
if(isset($data['BaseClass'])) { if (isset($data['BaseClass'])) {
$this->setBaseClass($data['BaseClass']); $this->setBaseClass($data['BaseClass']);
} }
if(isset($data['ParentID']) && ($class = $this->getBaseClass())) { if (isset($data['ParentID']) && ($class = $this->getBaseClass())) {
$this->setOwnerRecord($class::get()->byID($data['ParentID'])); $this->setOwnerRecord($class::get()->byID($data['ParentID']));
} }
if(!$this->getOwnerRecord()) return $this->httpError(404); if (!$this->getOwnerRecord()) {
return $this->httpError(404);
}
// cache users data // cache users data
Cookie::set("CommentsForm_UserData", Convert::raw2json($data)); Cookie::set("CommentsForm_UserData", Convert::raw2json($data));
@ -520,7 +559,7 @@ class CommentingController extends Controller {
$this->extend('onBeforePostComment', $form); $this->extend('onBeforePostComment', $form);
// If commenting can only be done by logged in users, make sure the user is logged in // If commenting can only be done by logged in users, make sure the user is logged in
if(!$this->getOwnerRecord()->canPostComment()) { if (!$this->getOwnerRecord()->canPostComment()) {
return Security::permissionFailure( return Security::permissionFailure(
$this, $this,
_t( _t(
@ -531,12 +570,12 @@ class CommentingController extends Controller {
); );
} }
if($member = Member::currentUser()) { if ($member = Member::currentUser()) {
$form->Fields()->push(new HiddenField("AuthorID", "Author ID", $member->ID)); $form->Fields()->push(new HiddenField("AuthorID", "Author ID", $member->ID));
} }
// What kind of moderation is required? // What kind of moderation is required?
switch($this->getOwnerRecord()->ModerationRequired) { switch ($this->getOwnerRecord()->ModerationRequired) {
case 'Required': case 'Required':
$requireModeration = true; $requireModeration = true;
break; break;
@ -558,7 +597,7 @@ class CommentingController extends Controller {
// Save into DB, or call pre-save hooks to give accurate preview // Save into DB, or call pre-save hooks to give accurate preview
$usePreview = $this->getOption('use_preview'); $usePreview = $this->getOption('use_preview');
$isPreview = $usePreview && !empty($data['IsPreview']); $isPreview = $usePreview && !empty($data['IsPreview']);
if($isPreview) { if ($isPreview) {
$comment->extend('onBeforeWrite'); $comment->extend('onBeforeWrite');
} else { } else {
$comment->write(); $comment->write();
@ -576,19 +615,19 @@ class CommentingController extends Controller {
Cookie::set('CommentsForm_Comment', false); Cookie::set('CommentsForm_Comment', false);
// Find parent link // Find parent link
if(!empty($data['ReturnURL'])) { if (!empty($data['ReturnURL'])) {
$url = $data['ReturnURL']; $url = $data['ReturnURL'];
} elseif($parent = $comment->getParent()) { } elseif ($parent = $comment->getParent()) {
$url = $parent->Link(); $url = $parent->Link();
} else { } else {
return $this->redirectBack(); return $this->redirectBack();
} }
// Given a redirect page exists, attempt to link to the correct anchor // Given a redirect page exists, attempt to link to the correct anchor
if($comment->IsSpam) { if ($comment->IsSpam) {
// Link to the form with the error message contained // Link to the form with the error message contained
$hash = $form->FormName(); $hash = $form->FormName();
} else if(!$comment->Moderated) { } elseif (!$comment->Moderated) {
// Display the "awaiting moderation" text // Display the "awaiting moderation" text
$holder = $this->getOption('comments_holder_id'); $holder = $this->getOption('comments_holder_id');
$hash = "{$holder}_PostCommentForm_error"; $hash = "{$holder}_PostCommentForm_error";
@ -600,13 +639,15 @@ class CommentingController extends Controller {
return $this->redirect(Controller::join_links($url, "#{$hash}")); return $this->redirect(Controller::join_links($url, "#{$hash}"));
} }
public function doPreviewComment($data, $form) { public function doPreviewComment($data, $form)
{
$data['IsPreview'] = 1; $data['IsPreview'] = 1;
return $this->doPostComment($data, $form); return $this->doPostComment($data, $form);
} }
public function redirectBack() { public function redirectBack()
{
// Don't cache the redirect back ever // Don't cache the redirect back ever
HTTP::set_cache_age(0); HTTP::set_cache_age(0);
@ -615,25 +656,28 @@ class CommentingController extends Controller {
// In edge-cases, this will be called outside of a handleRequest() context; in that case, // In edge-cases, this will be called outside of a handleRequest() context; in that case,
// redirect to the homepage - don't break into the global state at this stage because we'll // redirect to the homepage - don't break into the global state at this stage because we'll
// be calling from a test context or something else where the global state is inappropraite // be calling from a test context or something else where the global state is inappropraite
if($this->request) { if ($this->request) {
if($this->request->requestVar('BackURL')) { if ($this->request->requestVar('BackURL')) {
$url = $this->request->requestVar('BackURL'); $url = $this->request->requestVar('BackURL');
} else if($this->request->isAjax() && $this->request->getHeader('X-Backurl')) { } elseif ($this->request->isAjax() && $this->request->getHeader('X-Backurl')) {
$url = $this->request->getHeader('X-Backurl'); $url = $this->request->getHeader('X-Backurl');
} else if($this->request->getHeader('Referer')) { } elseif ($this->request->getHeader('Referer')) {
$url = $this->request->getHeader('Referer'); $url = $this->request->getHeader('Referer');
} }
} }
if(!$url) $url = $this->fallbackReturnURL; if (!$url) {
if(!$url) $url = Director::baseURL(); $url = $this->fallbackReturnURL;
}
if (!$url) {
$url = Director::baseURL();
}
// absolute redirection URLs not located on this site may cause phishing // absolute redirection URLs not located on this site may cause phishing
if(Director::is_site_url($url)) { if (Director::is_site_url($url)) {
return $this->redirect($url); return $this->redirect($url);
} else { } else {
return false; return false;
} }
} }
} }

View File

@ -5,7 +5,8 @@
* *
* @package comments * @package comments
*/ */
class CommentsExtension extends DataExtension { class CommentsExtension extends DataExtension
{
/** /**
* Default configuration values * Default configuration values
* *
@ -78,29 +79,30 @@ class CommentsExtension extends DataExtension {
* CMS configurable options should default to the config values, but respect * CMS configurable options should default to the config values, but respect
* default values specified by the object * default values specified by the object
*/ */
public function populateDefaults() { public function populateDefaults()
{
$defaults = $this->owner->config()->defaults; $defaults = $this->owner->config()->defaults;
// Set if comments should be enabled by default // Set if comments should be enabled by default
if(isset($defaults['ProvideComments'])) { if (isset($defaults['ProvideComments'])) {
$this->owner->ProvideComments = $defaults['ProvideComments']; $this->owner->ProvideComments = $defaults['ProvideComments'];
} else { } else {
$this->owner->ProvideComments = $this->owner->getCommentsOption('enabled') ? 1 : 0; $this->owner->ProvideComments = $this->owner->getCommentsOption('enabled') ? 1 : 0;
} }
// If moderation options should be configurable via the CMS then // If moderation options should be configurable via the CMS then
if(isset($defaults['ModerationRequired'])) { if (isset($defaults['ModerationRequired'])) {
$this->owner->ModerationRequired = $defaults['ModerationRequired']; $this->owner->ModerationRequired = $defaults['ModerationRequired'];
} elseif($this->owner->getCommentsOption('require_moderation')) { } elseif ($this->owner->getCommentsOption('require_moderation')) {
$this->owner->ModerationRequired = 'Required'; $this->owner->ModerationRequired = 'Required';
} elseif($this->owner->getCommentsOption('require_moderation_nonmembers')) { } elseif ($this->owner->getCommentsOption('require_moderation_nonmembers')) {
$this->owner->ModerationRequired = 'NonMembersOnly'; $this->owner->ModerationRequired = 'NonMembersOnly';
} else { } else {
$this->owner->ModerationRequired = 'None'; $this->owner->ModerationRequired = 'None';
} }
// Set login required // Set login required
if(isset($defaults['CommentsRequireLogin'])) { if (isset($defaults['CommentsRequireLogin'])) {
$this->owner->CommentsRequireLogin = $defaults['CommentsRequireLogin']; $this->owner->CommentsRequireLogin = $defaults['CommentsRequireLogin'];
} else { } else {
$this->owner->CommentsRequireLogin = $this->owner->getCommentsOption('require_login') ? 1 : 0; $this->owner->CommentsRequireLogin = $this->owner->getCommentsOption('require_login') ? 1 : 0;
@ -117,17 +119,17 @@ class CommentsExtension extends DataExtension {
* *
* @param FieldList $fields * @param FieldList $fields
*/ */
public function updateSettingsFields(FieldList $fields) { public function updateSettingsFields(FieldList $fields)
{
$options = FieldGroup::create()->setTitle(_t('CommentsExtension.COMMENTOPTIONS', 'Comments')); $options = FieldGroup::create()->setTitle(_t('CommentsExtension.COMMENTOPTIONS', 'Comments'));
// Check if enabled setting should be cms configurable // Check if enabled setting should be cms configurable
if($this->owner->getCommentsOption('enabled_cms')) { if ($this->owner->getCommentsOption('enabled_cms')) {
$options->push(new CheckboxField('ProvideComments', _t('Comment.ALLOWCOMMENTS', 'Allow Comments'))); $options->push(new CheckboxField('ProvideComments', _t('Comment.ALLOWCOMMENTS', 'Allow Comments')));
} }
// Check if we should require users to login to comment // Check if we should require users to login to comment
if($this->owner->getCommentsOption('require_login_cms')) { if ($this->owner->getCommentsOption('require_login_cms')) {
$options->push( $options->push(
new CheckboxField( new CheckboxField(
'CommentsRequireLogin', 'CommentsRequireLogin',
@ -136,8 +138,8 @@ class CommentsExtension extends DataExtension {
); );
} }
if($options->FieldList()->count()) { if ($options->FieldList()->count()) {
if($fields->hasTabSet()) { if ($fields->hasTabSet()) {
$fields->addFieldsToTab('Root.Settings', $options); $fields->addFieldsToTab('Root.Settings', $options);
} else { } else {
$fields->push($options); $fields->push($options);
@ -145,7 +147,7 @@ class CommentsExtension extends DataExtension {
} }
// Check if moderation should be enabled via cms configurable // Check if moderation should be enabled via cms configurable
if($this->owner->getCommentsOption('require_moderation_cms')) { if ($this->owner->getCommentsOption('require_moderation_cms')) {
$moderationField = new DropdownField('ModerationRequired', 'Comment Moderation', array( $moderationField = new DropdownField('ModerationRequired', 'Comment Moderation', array(
'None' => _t('CommentsExtension.MODERATIONREQUIRED_NONE', 'No moderation required'), 'None' => _t('CommentsExtension.MODERATIONREQUIRED_NONE', 'No moderation required'),
'Required' => _t('CommentsExtension.MODERATIONREQUIRED_REQUIRED', 'Moderate all comments'), 'Required' => _t('CommentsExtension.MODERATIONREQUIRED_REQUIRED', 'Moderate all comments'),
@ -154,7 +156,7 @@ class CommentsExtension extends DataExtension {
'Only moderate non-members' 'Only moderate non-members'
), ),
)); ));
if($fields->hasTabSet()) { if ($fields->hasTabSet()) {
$fields->addFieldsToTab('Root.Settings', $moderationField); $fields->addFieldsToTab('Root.Settings', $moderationField);
} else { } else {
$fields->push($moderationField); $fields->push($moderationField);
@ -171,12 +173,13 @@ class CommentsExtension extends DataExtension {
* *
* @return string * @return string
*/ */
public function getModerationRequired() { public function getModerationRequired()
if($this->owner->getCommentsOption('require_moderation_cms')) { {
if ($this->owner->getCommentsOption('require_moderation_cms')) {
return $this->owner->getField('ModerationRequired'); return $this->owner->getField('ModerationRequired');
} elseif($this->owner->getCommentsOption('require_moderation')) { } elseif ($this->owner->getCommentsOption('require_moderation')) {
return 'Required'; return 'Required';
} elseif($this->owner->getCommentsOption('require_moderation_nonmembers')) { } elseif ($this->owner->getCommentsOption('require_moderation_nonmembers')) {
return 'NonMembersOnly'; return 'NonMembersOnly';
} else { } else {
return 'None'; return 'None';
@ -188,8 +191,9 @@ class CommentsExtension extends DataExtension {
* *
* @return boolean * @return boolean
*/ */
public function getCommentsRequireLogin() { public function getCommentsRequireLogin()
if($this->owner->getCommentsOption('require_login_cms')) { {
if ($this->owner->getCommentsOption('require_login_cms')) {
return (bool) $this->owner->getField('CommentsRequireLogin'); return (bool) $this->owner->getField('CommentsRequireLogin');
} else { } else {
return (bool) $this->owner->getCommentsOption('require_login'); return (bool) $this->owner->getCommentsOption('require_login');
@ -202,7 +206,8 @@ class CommentsExtension extends DataExtension {
* *
* @return CommentList * @return CommentList
*/ */
public function AllComments() { public function AllComments()
{
$order = $this->owner->getCommentsOption('order_comments_by'); $order = $this->owner->getCommentsOption('order_comments_by');
$comments = CommentList::create($this->ownerBaseClass) $comments = CommentList::create($this->ownerBaseClass)
->forForeignID($this->owner->ID) ->forForeignID($this->owner->ID)
@ -216,19 +221,20 @@ class CommentsExtension extends DataExtension {
* *
* @return CommentList * @return CommentList
*/ */
public function AllVisibleComments() { public function AllVisibleComments()
{
$list = $this->AllComments(); $list = $this->AllComments();
// Filter spam comments for non-administrators if configured // Filter spam comments for non-administrators if configured
$showSpam = $this->owner->getCommentsOption('frontend_spam') && $this->owner->canModerateComments(); $showSpam = $this->owner->getCommentsOption('frontend_spam') && $this->owner->canModerateComments();
if(!$showSpam) { if (!$showSpam) {
$list = $list->filter('IsSpam', 0); $list = $list->filter('IsSpam', 0);
} }
// Filter un-moderated comments for non-administrators if moderation is enabled // Filter un-moderated comments for non-administrators if moderation is enabled
$showUnmoderated = ($this->owner->ModerationRequired === 'None') $showUnmoderated = ($this->owner->ModerationRequired === 'None')
|| ($this->owner->getCommentsOption('frontend_moderation') && $this->owner->canModerateComments()); || ($this->owner->getCommentsOption('frontend_moderation') && $this->owner->canModerateComments());
if(!$showUnmoderated) { if (!$showUnmoderated) {
$list = $list->filter('Moderated', 1); $list = $list->filter('Moderated', 1);
} }
@ -241,11 +247,12 @@ class CommentsExtension extends DataExtension {
* *
* @return CommentList * @return CommentList
*/ */
public function Comments() { public function Comments()
{
$list = $this->AllVisibleComments(); $list = $this->AllVisibleComments();
// If nesting comments, only show root level // If nesting comments, only show root level
if($this->owner->getCommentsOption('nested_comments')) { if ($this->owner->getCommentsOption('nested_comments')) {
$list = $list->filter('ParentCommentID', 0); $list = $list->filter('ParentCommentID', 0);
} }
@ -259,7 +266,8 @@ class CommentsExtension extends DataExtension {
* *
* @return PaginatedList * @return PaginatedList
*/ */
public function PagedComments() { public function PagedComments()
{
$list = $this->Comments(); $list = $this->Comments();
// Add pagination // Add pagination
@ -279,7 +287,8 @@ class CommentsExtension extends DataExtension {
* *
* @return boolean * @return boolean
*/ */
public function getCommentsConfigured() { public function getCommentsConfigured()
{
Deprecation::notice('2.0', 'getCommentsConfigured is deprecated. Use getCommentsEnabled instead'); Deprecation::notice('2.0', 'getCommentsConfigured is deprecated. Use getCommentsEnabled instead');
return true; // by virtue of all classes with this extension being 'configured' return true; // by virtue of all classes with this extension being 'configured'
} }
@ -289,12 +298,15 @@ class CommentsExtension extends DataExtension {
* *
* @return boolean * @return boolean
*/ */
public function getCommentsEnabled() { public function getCommentsEnabled()
{
// Don't display comments form for pseudo-pages (such as the login form) // Don't display comments form for pseudo-pages (such as the login form)
if(!$this->owner->exists()) return false; if (!$this->owner->exists()) {
return false;
}
// Determine which flag should be used to determine if this is enabled // Determine which flag should be used to determine if this is enabled
if($this->owner->getCommentsOption('enabled_cms')) { if ($this->owner->getCommentsOption('enabled_cms')) {
return $this->owner->ProvideComments; return $this->owner->ProvideComments;
} else { } else {
return $this->owner->getCommentsOption('enabled'); return $this->owner->getCommentsOption('enabled');
@ -306,14 +318,16 @@ class CommentsExtension extends DataExtension {
* *
* @return string * @return string
*/ */
public function getCommentHolderID() { public function getCommentHolderID()
{
return $this->owner->getCommentsOption('comments_holder_id'); return $this->owner->getCommentsOption('comments_holder_id');
} }
/** /**
* @deprecated since version 2.0 * @deprecated since version 2.0
*/ */
public function getPostingRequiresPermission() { public function getPostingRequiresPermission()
{
Deprecation::notice('2.0', 'Use getPostingRequiredPermission instead'); Deprecation::notice('2.0', 'Use getPostingRequiredPermission instead');
return $this->getPostingRequiredPermission(); return $this->getPostingRequiredPermission();
} }
@ -323,11 +337,13 @@ class CommentsExtension extends DataExtension {
* *
* @return string|array Permission or list of permissions, if required * @return string|array Permission or list of permissions, if required
*/ */
public function getPostingRequiredPermission() { public function getPostingRequiredPermission()
{
return $this->owner->getCommentsOption('required_permission'); return $this->owner->getCommentsOption('required_permission');
} }
public function canPost() { public function canPost()
{
Deprecation::notice('2.0', 'Use canPostComment instead'); Deprecation::notice('2.0', 'Use canPostComment instead');
return $this->canPostComment(); return $this->canPostComment();
} }
@ -339,21 +355,30 @@ class CommentsExtension extends DataExtension {
* *
* @return boolean * @return boolean
*/ */
public function canPostComment($member = null) { public function canPostComment($member = null)
{
// Deny if not enabled for this object // Deny if not enabled for this object
if(!$this->owner->CommentsEnabled) return false; if (!$this->owner->CommentsEnabled) {
return false;
}
// Check if member is required // Check if member is required
$requireLogin = $this->owner->CommentsRequireLogin; $requireLogin = $this->owner->CommentsRequireLogin;
if(!$requireLogin) return true; if (!$requireLogin) {
return true;
}
// Check member is logged in // Check member is logged in
$member = $member ?: Member::currentUser(); $member = $member ?: Member::currentUser();
if(!$member) return false; if (!$member) {
return false;
}
// If member required check permissions // If member required check permissions
$requiredPermission = $this->owner->PostingRequiredPermission; $requiredPermission = $this->owner->PostingRequiredPermission;
if($requiredPermission && !Permission::checkMember($member, $requiredPermission)) return false; if ($requiredPermission && !Permission::checkMember($member, $requiredPermission)) {
return false;
}
return true; return true;
} }
@ -365,15 +390,19 @@ class CommentsExtension extends DataExtension {
* *
* @return boolean * @return boolean
*/ */
public function canModerateComments($member = null) { public function canModerateComments($member = null)
{
// Deny if not enabled for this object // Deny if not enabled for this object
if(!$this->owner->CommentsEnabled) return false; if (!$this->owner->CommentsEnabled) {
return false;
}
// Fallback to can-edit // Fallback to can-edit
return $this->owner->canEdit($member); return $this->owner->canEdit($member);
} }
public function getRssLink() { public function getRssLink()
{
Deprecation::notice('2.0', 'Use getCommentRSSLink instead'); Deprecation::notice('2.0', 'Use getCommentRSSLink instead');
return $this->getCommentRSSLink(); return $this->getCommentRSSLink();
} }
@ -383,11 +412,13 @@ class CommentsExtension extends DataExtension {
* *
* @return string * @return string
*/ */
public function getCommentRSSLink() { public function getCommentRSSLink()
{
return Controller::join_links(Director::baseURL(), 'CommentingController/rss'); return Controller::join_links(Director::baseURL(), 'CommentingController/rss');
} }
public function getRssLinkPage() { public function getRssLinkPage()
{
Deprecation::notice('2.0', 'Use getCommentRSSLinkPage instead'); Deprecation::notice('2.0', 'Use getCommentRSSLinkPage instead');
return $this->getCommentRSSLinkPage(); return $this->getCommentRSSLinkPage();
} }
@ -397,7 +428,8 @@ class CommentsExtension extends DataExtension {
* *
* @return string * @return string
*/ */
public function getCommentRSSLinkPage() { public function getCommentRSSLinkPage()
{
return Controller::join_links( return Controller::join_links(
$this->getCommentRSSLink(), $this->ownerBaseClass, $this->owner->ID $this->getCommentRSSLink(), $this->ownerBaseClass, $this->owner->ID
); );
@ -414,10 +446,11 @@ class CommentsExtension extends DataExtension {
* *
* @see docs/en/Extending * @see docs/en/Extending
*/ */
public function CommentsForm() { public function CommentsForm()
{
// Check if enabled // Check if enabled
$enabled = $this->getCommentsEnabled(); $enabled = $this->getCommentsEnabled();
if($enabled && $this->owner->getCommentsOption('include_js')) { if ($enabled && $this->owner->getCommentsOption('include_js')) {
Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js'); Requirements::javascript(THIRDPARTY_DIR . '/jquery/jquery.js');
Requirements::javascript(THIRDPARTY_DIR . '/jquery-entwine/dist/jquery.entwine-dist.js'); Requirements::javascript(THIRDPARTY_DIR . '/jquery-entwine/dist/jquery.entwine-dist.js');
Requirements::javascript(THIRDPARTY_DIR . '/jquery-validate/lib/jquery.form.js'); Requirements::javascript(THIRDPARTY_DIR . '/jquery-validate/lib/jquery.form.js');
@ -452,7 +485,8 @@ class CommentsExtension extends DataExtension {
* *
* @return bool * @return bool
*/ */
public function attachedToSiteTree() { public function attachedToSiteTree()
{
$class = $this->ownerBaseClass; $class = $this->ownerBaseClass;
return (is_subclass_of($class, 'SiteTree')) || ($class == 'SiteTree'); return (is_subclass_of($class, 'SiteTree')) || ($class == 'SiteTree');
@ -461,7 +495,8 @@ class CommentsExtension extends DataExtension {
/** /**
* @deprecated 1.0 Please use {@link CommentsExtension->CommentsForm()} * @deprecated 1.0 Please use {@link CommentsExtension->CommentsForm()}
*/ */
public function PageComments() { public function PageComments()
{
// This method is very commonly used, don't throw a warning just yet // This method is very commonly used, don't throw a warning just yet
Deprecation::notice('1.0', '$PageComments is deprecated. Please use $CommentsForm'); Deprecation::notice('1.0', '$PageComments is deprecated. Please use $CommentsForm');
return $this->CommentsForm(); return $this->CommentsForm();
@ -476,15 +511,20 @@ class CommentsExtension extends DataExtension {
* *
* @return mixed Result if the setting is available, or null otherwise * @return mixed Result if the setting is available, or null otherwise
*/ */
public function getCommentsOption($key) { public function getCommentsOption($key)
{
$settings = $this->owner // In case singleton is called on the extension directly $settings = $this->owner // In case singleton is called on the extension directly
? $this->owner->config()->comments ? $this->owner->config()->comments
: Config::inst()->get(__CLASS__, 'comments'); : Config::inst()->get(__CLASS__, 'comments');
$value = null; $value = null;
if(isset($settings[$key])) $value = $settings[$key]; if (isset($settings[$key])) {
$value = $settings[$key];
}
// To allow other extensions to customise this option // To allow other extensions to customise this option
if($this->owner) $this->owner->extend('updateCommentsOption', $key, $value); if ($this->owner) {
$this->owner->extend('updateCommentsOption', $key, $value);
}
return $value; return $value;
} }
@ -493,7 +533,8 @@ class CommentsExtension extends DataExtension {
* *
* @param FieldList $fields * @param FieldList $fields
*/ */
protected function updateModerationFields(FieldList $fields) { protected function updateModerationFields(FieldList $fields)
{
Requirements::css(COMMENTS_DIR . '/css/cms.css'); Requirements::css(COMMENTS_DIR . '/css/cms.css');
$newComments = $this->owner->AllComments()->filter('Moderated', 0); $newComments = $this->owner->AllComments()->filter('Moderated', 0);
@ -527,7 +568,7 @@ class CommentsExtension extends DataExtension {
$approvedCount = '(' . count($approvedComments) . ')'; $approvedCount = '(' . count($approvedComments) . ')';
$spamCount = '(' . count($spamComments) . ')'; $spamCount = '(' . count($spamComments) . ')';
if($fields->hasTabSet()) { if ($fields->hasTabSet()) {
$tabs = new TabSet( $tabs = new TabSet(
'Comments', 'Comments',
new Tab('CommentsNewCommentsTab', _t('CommentAdmin.NewComments', 'New') . ' ' . $newCount, new Tab('CommentsNewCommentsTab', _t('CommentAdmin.NewComments', 'New') . ' ' . $newCount,
@ -548,14 +589,15 @@ class CommentsExtension extends DataExtension {
} }
} }
public function updateCMSFields(FieldList $fields) { public function updateCMSFields(FieldList $fields)
{
// Disable moderation if not permitted // Disable moderation if not permitted
if($this->owner->canModerateComments()) { if ($this->owner->canModerateComments()) {
$this->updateModerationFields($fields); $this->updateModerationFields($fields);
} }
// If this isn't a page we should merge the settings into the CMS fields // If this isn't a page we should merge the settings into the CMS fields
if(!$this->attachedToSiteTree()) { if (!$this->attachedToSiteTree()) {
$this->updateSettingsFields($fields); $this->updateSettingsFields($fields);
} }
} }

View File

@ -20,7 +20,8 @@
* @method Comment ParentComment() Parent comment this is a reply to * @method Comment ParentComment() Parent comment this is a reply to
* @package comments * @package comments
*/ */
class Comment extends DataObject { class Comment extends DataObject
{
/** /**
* @var array * @var array
@ -89,11 +90,12 @@ class Comment extends DataObject {
'Author' => 'Author Member', 'Author' => 'Author Member',
); );
public function onBeforeWrite() { public function onBeforeWrite()
{
parent::onBeforeWrite(); parent::onBeforeWrite();
// Sanitize HTML, because its expected to be passed to the template unescaped later // Sanitize HTML, because its expected to be passed to the template unescaped later
if($this->AllowHtml) { if ($this->AllowHtml) {
$this->Comment = $this->purifyHtml($this->Comment); $this->Comment = $this->purifyHtml($this->Comment);
} }
@ -101,11 +103,12 @@ class Comment extends DataObject {
$this->updateDepth(); $this->updateDepth();
} }
public function onBeforeDelete() { public function onBeforeDelete()
{
parent::onBeforeDelete(); parent::onBeforeDelete();
// Delete all children // Delete all children
foreach($this->ChildComments() as $comment) { foreach ($this->ChildComments() as $comment) {
$comment->delete(); $comment->delete();
} }
} }
@ -113,21 +116,23 @@ class Comment extends DataObject {
/** /**
* @return Comment_SecurityToken * @return Comment_SecurityToken
*/ */
public function getSecurityToken() { public function getSecurityToken()
{
return Injector::inst()->createWithArgs('Comment_SecurityToken', array($this)); return Injector::inst()->createWithArgs('Comment_SecurityToken', array($this));
} }
/** /**
* Migrates the old {@link PageComment} objects to {@link Comment} * Migrates the old {@link PageComment} objects to {@link Comment}
*/ */
public function requireDefaultRecords() { public function requireDefaultRecords()
{
parent::requireDefaultRecords(); parent::requireDefaultRecords();
if(DB::getConn()->hasTable('PageComment')) { if (DB::getConn()->hasTable('PageComment')) {
$comments = DB::query('SELECT * FROM "PageComment"'); $comments = DB::query('SELECT * FROM "PageComment"');
if($comments) { if ($comments) {
while($pageComment = $comments->nextRecord()) { while ($pageComment = $comments->nextRecord()) {
// create a new comment from the older page comment // create a new comment from the older page comment
$comment = new Comment(); $comment = new Comment();
$comment->update($pageComment); $comment->update($pageComment);
@ -135,7 +140,9 @@ class Comment extends DataObject {
// set the variables which have changed // set the variables which have changed
$comment->BaseClass = 'SiteTree'; $comment->BaseClass = 'SiteTree';
$comment->URL = (isset($pageComment['CommenterURL'])) ? $pageComment['CommenterURL'] : ''; $comment->URL = (isset($pageComment['CommenterURL'])) ? $pageComment['CommenterURL'] : '';
if((int) $pageComment['NeedsModeration'] == 0) $comment->Moderated = true; if ((int) $pageComment['NeedsModeration'] == 0) {
$comment->Moderated = true;
}
$comment->write(); $comment->write();
} }
@ -153,8 +160,9 @@ class Comment extends DataObject {
* *
* @return string link to this comment. * @return string link to this comment.
*/ */
public function Link($action = '') { public function Link($action = '')
if($parent = $this->getParent()) { {
if ($parent = $this->getParent()) {
return $parent->Link($action) . '#' . $this->Permalink(); return $parent->Link($action) . '#' . $this->Permalink();
} }
} }
@ -165,7 +173,8 @@ class Comment extends DataObject {
* *
* @return string * @return string
*/ */
public function Permalink() { public function Permalink()
{
$prefix = $this->getOption('comment_permalink_prefix'); $prefix = $this->getOption('comment_permalink_prefix');
return $prefix . $this->ID; return $prefix . $this->ID;
} }
@ -177,7 +186,8 @@ class Comment extends DataObject {
* *
* @return array * @return array
*/ */
public function fieldLabels($includerelations = true) { public function fieldLabels($includerelations = true)
{
$labels = parent::fieldLabels($includerelations); $labels = parent::fieldLabels($includerelations);
$labels['Name'] = _t('Comment.NAME', 'Author Name'); $labels['Name'] = _t('Comment.NAME', 'Author Name');
@ -199,15 +209,15 @@ class Comment extends DataObject {
* *
* @return mixed Result if the setting is available, or null otherwise * @return mixed Result if the setting is available, or null otherwise
*/ */
public function getOption($key) { public function getOption($key)
{
// If possible use the current record // If possible use the current record
$record = $this->getParent(); $record = $this->getParent();
if(!$record && $this->BaseClass) { if (!$record && $this->BaseClass) {
// Otherwise a singleton of that record // Otherwise a singleton of that record
$record = singleton($this->BaseClass); $record = singleton($this->BaseClass);
} } elseif (!$record) {
else if(!$record) {
// Otherwise just use the default options // Otherwise just use the default options
$record = singleton('CommentsExtension'); $record = singleton('CommentsExtension');
} }
@ -220,7 +230,8 @@ class Comment extends DataObject {
* *
* @return DataObject * @return DataObject
*/ */
public function getParent() { public function getParent()
{
return $this->BaseClass && $this->ParentID return $this->BaseClass && $this->ParentID
? DataObject::get_by_id($this->BaseClass, $this->ParentID, true) ? DataObject::get_by_id($this->BaseClass, $this->ParentID, true)
: null; : null;
@ -232,8 +243,9 @@ class Comment extends DataObject {
* *
* @return string * @return string
*/ */
public function getParentTitle() { public function getParentTitle()
if($parent = $this->getParent()) { {
if ($parent = $this->getParent()) {
return $parent->Title ?: ($parent->ClassName . ' #' . $parent->ID); return $parent->Title ?: ($parent->ClassName . ' #' . $parent->ID);
} }
} }
@ -243,13 +255,15 @@ class Comment extends DataObject {
* *
* @return string * @return string
*/ */
public function getParentClassName() { public function getParentClassName()
{
return $this->BaseClass; return $this->BaseClass;
} }
public function castingHelper($field) { public function castingHelper($field)
{
// Safely escape the comment // Safely escape the comment
if($field === 'EscapedComment') { if ($field === 'EscapedComment') {
return $this->AllowHtml ? 'HTMLText' : 'Text'; return $this->AllowHtml ? 'HTMLText' : 'Text';
} }
return parent::castingHelper($field); return parent::castingHelper($field);
@ -260,7 +274,8 @@ class Comment extends DataObject {
* *
* @return string * @return string
*/ */
public function getEscapedComment() { public function getEscapedComment()
{
return $this->Comment; return $this->Comment;
} }
@ -269,7 +284,8 @@ class Comment extends DataObject {
* *
* @return boolean * @return boolean
*/ */
public function isPreview() { public function isPreview()
{
return !$this->exists(); return !$this->exists();
} }
@ -280,7 +296,8 @@ class Comment extends DataObject {
* *
* @return bool * @return bool
*/ */
public function canCreate($member = null) { public function canCreate($member = null)
{
return false; return false;
} }
@ -292,19 +309,20 @@ class Comment extends DataObject {
* *
* @return Boolean * @return Boolean
*/ */
public function canView($member = null) { public function canView($member = null)
{
$member = $this->getMember($member); $member = $this->getMember($member);
$extended = $this->extendedCan('canView', $member); $extended = $this->extendedCan('canView', $member);
if($extended !== null) { if ($extended !== null) {
return $extended; return $extended;
} }
if(Permission::checkMember($member, 'CMS_ACCESS_CommentAdmin')) { if (Permission::checkMember($member, 'CMS_ACCESS_CommentAdmin')) {
return true; return true;
} }
if($parent = $this->getParent()) { if ($parent = $this->getParent()) {
return $parent->canView($member) return $parent->canView($member)
&& $parent->has_extension('CommentsExtension') && $parent->has_extension('CommentsExtension')
&& $parent->CommentsEnabled; && $parent->CommentsEnabled;
@ -320,23 +338,24 @@ class Comment extends DataObject {
* *
* @return Boolean * @return Boolean
*/ */
public function canEdit($member = null) { public function canEdit($member = null)
{
$member = $this->getMember($member); $member = $this->getMember($member);
if(!$member) { if (!$member) {
return false; return false;
} }
$extended = $this->extendedCan('canEdit', $member); $extended = $this->extendedCan('canEdit', $member);
if($extended !== null) { if ($extended !== null) {
return $extended; return $extended;
} }
if(Permission::checkMember($member, 'CMS_ACCESS_CommentAdmin')) { if (Permission::checkMember($member, 'CMS_ACCESS_CommentAdmin')) {
return true; return true;
} }
if($parent = $this->getParent()) { if ($parent = $this->getParent()) {
return $parent->canEdit($member); return $parent->canEdit($member);
} }
@ -350,15 +369,16 @@ class Comment extends DataObject {
* *
* @return Boolean * @return Boolean
*/ */
public function canDelete($member = null) { public function canDelete($member = null)
{
$member = $this->getMember($member); $member = $this->getMember($member);
if(!$member) { if (!$member) {
return false; return false;
} }
$extended = $this->extendedCan('canDelete', $member); $extended = $this->extendedCan('canDelete', $member);
if($extended !== null) { if ($extended !== null) {
return $extended; return $extended;
} }
@ -371,12 +391,13 @@ class Comment extends DataObject {
* @param Member|int|null $member * @param Member|int|null $member
* @return Member|null * @return Member|null
*/ */
protected function getMember($member = null) { protected function getMember($member = null)
if(!$member) { {
if (!$member) {
$member = Member::currentUser(); $member = Member::currentUser();
} }
if(is_numeric($member)) { if (is_numeric($member)) {
$member = DataObject::get_by_id('Member', $member, true); $member = DataObject::get_by_id('Member', $member, true);
} }
@ -388,10 +409,11 @@ class Comment extends DataObject {
* *
* @return string * @return string
*/ */
public function getAuthorName() { public function getAuthorName()
if($this->Name) { {
if ($this->Name) {
return $this->Name; return $this->Name;
} else if($author = $this->Author()) { } elseif ($author = $this->Author()) {
return $author->getName(); return $author->getName();
} }
} }
@ -404,9 +426,14 @@ class Comment extends DataObject {
* *
* @return string * @return string
*/ */
protected function actionLink($action, $member = null) { protected function actionLink($action, $member = null)
if(!$member) $member = Member::currentUser(); {
if(!$member) return false; if (!$member) {
$member = Member::currentUser();
}
if (!$member) {
return false;
}
$url = Controller::join_links( $url = Controller::join_links(
Director::baseURL(), Director::baseURL(),
@ -427,8 +454,9 @@ class Comment extends DataObject {
* *
* @return string * @return string
*/ */
public function DeleteLink($member = null) { public function DeleteLink($member = null)
if($this->canDelete($member)) { {
if ($this->canDelete($member)) {
return $this->actionLink('delete', $member); return $this->actionLink('delete', $member);
} }
} }
@ -440,8 +468,9 @@ class Comment extends DataObject {
* *
* @return string * @return string
*/ */
public function SpamLink($member = null) { public function SpamLink($member = null)
if($this->canEdit($member) && !$this->IsSpam) { {
if ($this->canEdit($member) && !$this->IsSpam) {
return $this->actionLink('spam', $member); return $this->actionLink('spam', $member);
} }
} }
@ -453,8 +482,9 @@ class Comment extends DataObject {
* *
* @return string * @return string
*/ */
public function HamLink($member = null) { public function HamLink($member = null)
if($this->canEdit($member) && $this->IsSpam) { {
if ($this->canEdit($member) && $this->IsSpam) {
return $this->actionLink('ham', $member); return $this->actionLink('ham', $member);
} }
} }
@ -466,8 +496,9 @@ class Comment extends DataObject {
* *
* @return string * @return string
*/ */
public function ApproveLink($member = null) { public function ApproveLink($member = null)
if($this->canEdit($member) && !$this->Moderated) { {
if ($this->canEdit($member) && !$this->Moderated) {
return $this->actionLink('approve', $member); return $this->actionLink('approve', $member);
} }
} }
@ -475,7 +506,8 @@ class Comment extends DataObject {
/** /**
* Mark this comment as spam * Mark this comment as spam
*/ */
public function markSpam() { public function markSpam()
{
$this->IsSpam = true; $this->IsSpam = true;
$this->Moderated = true; $this->Moderated = true;
$this->write(); $this->write();
@ -485,7 +517,8 @@ class Comment extends DataObject {
/** /**
* Mark this comment as approved * Mark this comment as approved
*/ */
public function markApproved() { public function markApproved()
{
$this->IsSpam = false; $this->IsSpam = false;
$this->Moderated = true; $this->Moderated = true;
$this->write(); $this->write();
@ -495,7 +528,8 @@ class Comment extends DataObject {
/** /**
* Mark this comment as unapproved * Mark this comment as unapproved
*/ */
public function markUnapproved() { public function markUnapproved()
{
$this->Moderated = false; $this->Moderated = false;
$this->write(); $this->write();
$this->extend('afterMarkUnapproved'); $this->extend('afterMarkUnapproved');
@ -504,10 +538,11 @@ class Comment extends DataObject {
/** /**
* @return string * @return string
*/ */
public function SpamClass() { public function SpamClass()
if($this->IsSpam) { {
if ($this->IsSpam) {
return 'spam'; return 'spam';
} else if(!$this->Moderated) { } elseif (!$this->Moderated) {
return 'unmoderated'; return 'unmoderated';
} else { } else {
return 'notspam'; return 'notspam';
@ -517,11 +552,12 @@ class Comment extends DataObject {
/** /**
* @return string * @return string
*/ */
public function getTitle() { public function getTitle()
{
$title = sprintf(_t('Comment.COMMENTBY', 'Comment by %s', 'Name'), $this->getAuthorName()); $title = sprintf(_t('Comment.COMMENTBY', 'Comment by %s', 'Name'), $this->getAuthorName());
if($parent = $this->getParent()) { if ($parent = $this->getParent()) {
if($parent->Title) { if ($parent->Title) {
$title .= sprintf(' %s %s', _t('Comment.ON', 'on'), $parent->Title); $title .= sprintf(' %s %s', _t('Comment.ON', 'on'), $parent->Title);
} }
} }
@ -532,7 +568,8 @@ class Comment extends DataObject {
/* /*
* Modify the default fields shown to the user * Modify the default fields shown to the user
*/ */
public function getCMSFields() { public function getCMSFields()
{
$commentField = $this->AllowHtml ? 'HtmlEditorField' : 'TextareaField'; $commentField = $this->AllowHtml ? 'HtmlEditorField' : 'TextareaField';
$fields = new FieldList( $fields = new FieldList(
$this $this
@ -555,7 +592,7 @@ class Comment extends DataObject {
); );
// Show member name if given // Show member name if given
if(($author = $this->Author()) && $author->exists()) { if (($author = $this->Author()) && $author->exists()) {
$fields->insertAfter( $fields->insertAfter(
TextField::create('AuthorMember', $this->fieldLabel('Author'), $author->Title) TextField::create('AuthorMember', $this->fieldLabel('Author'), $author->Title)
->performReadonlyTransformation(), ->performReadonlyTransformation(),
@ -564,7 +601,7 @@ class Comment extends DataObject {
} }
// Show parent comment if given // Show parent comment if given
if(($parent = $this->ParentComment()) && $parent->exists()) { if (($parent = $this->ParentComment()) && $parent->exists()) {
$fields->push(new HeaderField( $fields->push(new HeaderField(
'ParentComment_Title', 'ParentComment_Title',
_t('Comment.ParentComment_Title', 'This comment is a reply to the below') _t('Comment.ParentComment_Title', 'This comment is a reply to the below')
@ -610,7 +647,8 @@ class Comment extends DataObject {
* *
* @return String * @return String
*/ */
public function purifyHtml($dirtyHtml) { public function purifyHtml($dirtyHtml)
{
$purifier = $this->getHtmlPurifierService(); $purifier = $this->getHtmlPurifierService();
return $purifier->purify($dirtyHtml); return $purifier->purify($dirtyHtml);
} }
@ -618,7 +656,8 @@ class Comment extends DataObject {
/** /**
* @return HTMLPurifier (or anything with a "purify()" method) * @return HTMLPurifier (or anything with a "purify()" method)
*/ */
public function getHtmlPurifierService() { public function getHtmlPurifierService()
{
$config = HTMLPurifier_Config::createDefault(); $config = HTMLPurifier_Config::createDefault();
$allowedElements = $this->getOption('html_allowed_elements'); $allowedElements = $this->getOption('html_allowed_elements');
$config->set('HTML.AllowedElements', $allowedElements); $config->set('HTML.AllowedElements', $allowedElements);
@ -639,10 +678,11 @@ class Comment extends DataObject {
* *
* @return string * @return string
*/ */
public function Gravatar() { public function Gravatar()
{
$gravatar = ''; $gravatar = '';
$use_gravatar = $this->getOption('use_gravatar'); $use_gravatar = $this->getOption('use_gravatar');
if($use_gravatar) { if ($use_gravatar) {
$gravatar = 'http://www.gravatar.com/avatar/' . md5(strtolower(trim($this->Email))); $gravatar = 'http://www.gravatar.com/avatar/' . md5(strtolower(trim($this->Email)));
$gravatarsize = $this->getOption('gravatar_size'); $gravatarsize = $this->getOption('gravatar_size');
$gravatardefault = $this->getOption('gravatar_default'); $gravatardefault = $this->getOption('gravatar_default');
@ -658,9 +698,10 @@ class Comment extends DataObject {
* *
* @return boolean * @return boolean
*/ */
public function getRepliesEnabled() { public function getRepliesEnabled()
{
// Check reply option // Check reply option
if(!$this->getOption('nested_comments')) { if (!$this->getOption('nested_comments')) {
return false; return false;
} }
@ -675,9 +716,10 @@ class Comment extends DataObject {
* *
* @return SS_List * @return SS_List
*/ */
public function AllReplies() { public function AllReplies()
{
// No replies if disabled // No replies if disabled
if(!$this->getRepliesEnabled()) { if (!$this->getRepliesEnabled()) {
return new ArrayList(); return new ArrayList();
} }
@ -697,9 +739,10 @@ class Comment extends DataObject {
* *
* @return SS_List * @return SS_List
*/ */
public function Replies() { public function Replies()
{
// No replies if disabled // No replies if disabled
if(!$this->getRepliesEnabled()) { if (!$this->getRepliesEnabled()) {
return new ArrayList(); return new ArrayList();
} }
$list = $this->AllReplies(); $list = $this->AllReplies();
@ -707,7 +750,7 @@ class Comment extends DataObject {
// Filter spam comments for non-administrators if configured // Filter spam comments for non-administrators if configured
$parent = $this->getParent(); $parent = $this->getParent();
$showSpam = $this->getOption('frontend_spam') && $parent && $parent->canModerateComments(); $showSpam = $this->getOption('frontend_spam') && $parent && $parent->canModerateComments();
if(!$showSpam) { if (!$showSpam) {
$list = $list->filter('IsSpam', 0); $list = $list->filter('IsSpam', 0);
} }
@ -729,7 +772,8 @@ class Comment extends DataObject {
* *
* @return PaginatedList * @return PaginatedList
*/ */
public function PagedReplies() { public function PagedReplies()
{
$list = $this->Replies(); $list = $this->Replies();
// Add pagination // Add pagination
@ -746,15 +790,16 @@ class Comment extends DataObject {
* *
* @return Form * @return Form
*/ */
public function ReplyForm() { public function ReplyForm()
{
// Ensure replies are enabled // Ensure replies are enabled
if(!$this->getRepliesEnabled()) { if (!$this->getRepliesEnabled()) {
return null; return null;
} }
// Check parent is available // Check parent is available
$parent = $this->getParent(); $parent = $this->getParent();
if(!$parent || !$parent->exists()) { if (!$parent || !$parent->exists()) {
return null; return null;
} }
@ -770,9 +815,10 @@ class Comment extends DataObject {
/** /**
* Refresh of this comment in the hierarchy * Refresh of this comment in the hierarchy
*/ */
public function updateDepth() { public function updateDepth()
{
$parent = $this->ParentComment(); $parent = $this->ParentComment();
if($parent && $parent->exists()) { if ($parent && $parent->exists()) {
$parent->updateDepth(); $parent->updateDepth();
$this->Depth = $parent->Depth + 1; $this->Depth = $parent->Depth + 1;
} else { } else {
@ -785,15 +831,17 @@ class Comment extends DataObject {
/** /**
* Provides the ability to generate cryptographically secure tokens for comment moderation * Provides the ability to generate cryptographically secure tokens for comment moderation
*/ */
class Comment_SecurityToken { class Comment_SecurityToken
{
private $secret = null; private $secret = null;
/** /**
* @param Comment $comment Comment to generate this token for * @param Comment $comment Comment to generate this token for
*/ */
public function __construct($comment) { public function __construct($comment)
if(!$comment->SecretToken) { {
if (!$comment->SecretToken) {
$comment->SecretToken = $this->generate(); $comment->SecretToken = $this->generate();
$comment->write(); $comment->write();
} }
@ -807,7 +855,8 @@ class Comment_SecurityToken {
* *
* @return string * @return string
*/ */
protected function getToken($salt) { protected function getToken($salt)
{
return hash_pbkdf2('sha256', $this->secret, $salt, 1000, 30); return hash_pbkdf2('sha256', $this->secret, $salt, 1000, 30);
} }
@ -823,7 +872,8 @@ class Comment_SecurityToken {
* *
* @return string Generated salt specific to this member * @return string Generated salt specific to this member
*/ */
protected function memberSalt($salt, $member) { protected function memberSalt($salt, $member)
{
// Fallback to salting with ID in case the member has not one set // Fallback to salting with ID in case the member has not one set
return $salt . ($member->Salt ?: $member->ID); return $salt . ($member->Salt ?: $member->ID);
} }
@ -834,7 +884,8 @@ class Comment_SecurityToken {
* *
* @return string * @return string
*/ */
public function addToUrl($url, $member) { public function addToUrl($url, $member)
{
$salt = $this->generate(15); // New random salt; Will be passed into url $salt = $this->generate(15); // New random salt; Will be passed into url
// Generate salt specific to this member // Generate salt specific to this member
$memberSalt = $this->memberSalt($salt, $member); $memberSalt = $this->memberSalt($salt, $member);
@ -854,9 +905,12 @@ class Comment_SecurityToken {
* *
* @return boolean * @return boolean
*/ */
public function checkRequest($request) { public function checkRequest($request)
{
$member = Member::currentUser(); $member = Member::currentUser();
if(!$member) return false; if (!$member) {
return false;
}
$salt = $request->getVar('s'); $salt = $request->getVar('s');
$memberSalt = $this->memberSalt($salt, $member); $memberSalt = $this->memberSalt($salt, $member);
@ -874,10 +928,13 @@ class Comment_SecurityToken {
* *
* @return string * @return string
*/ */
protected function generate($length = null) { protected function generate($length = null)
{
$generator = new RandomGenerator(); $generator = new RandomGenerator();
$result = $generator->randomToken('sha256'); $result = $generator->randomToken('sha256');
if($length !== null) return substr($result, 0, $length); if ($length !== null) {
return substr($result, 0, $length);
}
return $result; return $result;
} }
} }

View File

@ -7,18 +7,21 @@
* *
* @author dmooyman * @author dmooyman
*/ */
class CommentList extends HasManyList { class CommentList extends HasManyList
{
/** /**
* Retrieve the name of the class this relation is filtered by * Retrieve the name of the class this relation is filtered by
* *
* @return string * @return string
*/ */
public function getForeignClass() { public function getForeignClass()
{
return $this->dataQuery->getQueryParam('Foreign.Class'); return $this->dataQuery->getQueryParam('Foreign.Class');
} }
public function __construct($parentClassName) { public function __construct($parentClassName)
{
parent::__construct('Comment', 'ParentID'); parent::__construct('Comment', 'ParentID');
@ -38,18 +41,19 @@ class CommentList extends HasManyList {
* *
* @param Comment $item The comment to be added * @param Comment $item The comment to be added
*/ */
public function add($item) { public function add($item)
{
// Check item given // Check item given
if(is_numeric($item)) { if (is_numeric($item)) {
$item = Comment::get()->byID($item); $item = Comment::get()->byID($item);
} }
if(!($item instanceof Comment)) { if (!($item instanceof Comment)) {
throw new InvalidArgumentException("CommentList::add() expecting a Comment object, or ID value"); throw new InvalidArgumentException("CommentList::add() expecting a Comment object, or ID value");
} }
// Validate foreignID // Validate foreignID
$foreignID = $this->getForeignID(); $foreignID = $this->getForeignID();
if(!$foreignID || is_array($foreignID)) { if (!$foreignID || is_array($foreignID)) {
throw new InvalidArgumentException("CommentList::add() can't be called until a single foreign ID is set"); throw new InvalidArgumentException("CommentList::add() can't be called until a single foreign ID is set");
} }
@ -62,12 +66,13 @@ class CommentList extends HasManyList {
* *
* @param Comment $item The Comment to be removed * @param Comment $item The Comment to be removed
*/ */
public function remove($item) { public function remove($item)
{
// Check item given // Check item given
if(is_numeric($item)) { if (is_numeric($item)) {
$item = Comment::get()->byID($item); $item = Comment::get()->byID($item);
} }
if(!($item instanceof Comment)) { if (!($item instanceof Comment)) {
throw new InvalidArgumentException("CommentList::remove() expecting a Comment object, or ID", throw new InvalidArgumentException("CommentList::remove() expecting a Comment object, or ID",
E_USER_ERROR); E_USER_ERROR);
} }
@ -75,11 +80,13 @@ class CommentList extends HasManyList {
// Don't remove item with unrelated class key // Don't remove item with unrelated class key
$foreignClass = $this->getForeignClass(); $foreignClass = $this->getForeignClass();
$classNames = ClassInfo::subclassesFor($foreignClass); $classNames = ClassInfo::subclassesFor($foreignClass);
if(!in_array($item->BaseClass, $classNames)) return; if (!in_array($item->BaseClass, $classNames)) {
return;
}
// Don't remove item which doesn't belong to this list // Don't remove item which doesn't belong to this list
$foreignID = $this->getForeignID(); $foreignID = $this->getForeignID();
if( empty($foreignID) if (empty($foreignID)
|| (is_array($foreignID) && in_array($item->ParentID, $foreignID)) || (is_array($foreignID) && in_array($item->ParentID, $foreignID))
|| $foreignID == $item->ParentID || $foreignID == $item->ParentID
) { ) {

View File

@ -1,7 +1,9 @@
<?php <?php
class CommentAdminTest extends SapphireTest { class CommentAdminTest extends SapphireTest
public function testProvidePermissions() { {
public function testProvidePermissions()
{
$commentAdmin = new CommentAdmin(); $commentAdmin = new CommentAdmin();
$locale = i18n::get_locale(); $locale = i18n::get_locale();
@ -26,7 +28,8 @@ class CommentAdminTest extends SapphireTest {
$this->assertEquals($expected, $commentAdmin->providePermissions()); $this->assertEquals($expected, $commentAdmin->providePermissions());
} }
public function testGetEditForm() { public function testGetEditForm()
{
$commentAdmin = new CommentAdmin(); $commentAdmin = new CommentAdmin();
$this->logInWithPermission('CMS_ACCESS_CommentAdmin'); $this->logInWithPermission('CMS_ACCESS_CommentAdmin');
$form = $commentAdmin->getEditForm(); $form = $commentAdmin->getEditForm();
@ -38,12 +41,15 @@ class CommentAdminTest extends SapphireTest {
); );
$this->assertEquals($expected, $names); $this->assertEquals($expected, $names);
if($member = Member::currentUser()) $member->logOut(); if ($member = Member::currentUser()) {
$member->logOut();
}
$form = $commentAdmin->getEditForm(); $form = $commentAdmin->getEditForm();
} }
private function getFormFieldNames($form) { private function getFormFieldNames($form)
{
$result = array(); $result = array();
$fields = $form->Fields(); $fields = $form->Fields();
$tab = $fields->findOrMakeTab('Root'); $tab = $fields->findOrMakeTab('Root');
@ -53,5 +59,4 @@ class CommentAdminTest extends SapphireTest {
} }
return $result; return $result;
} }
} }

View File

@ -1,6 +1,7 @@
<?php <?php
class CommentListTest extends FunctionalTest { class CommentListTest extends FunctionalTest
{
public static $fixture_file = 'comments/tests/CommentsTest.yml'; public static $fixture_file = 'comments/tests/CommentsTest.yml';
@ -10,7 +11,8 @@ class CommentListTest extends FunctionalTest {
'CommentableItemDisabled' 'CommentableItemDisabled'
); );
public function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
Config::nest(); Config::nest();
@ -34,12 +36,14 @@ class CommentListTest extends FunctionalTest {
)); ));
} }
public function tearDown() { public function tearDown()
{
Config::unnest(); Config::unnest();
parent::tearDown(); parent::tearDown();
} }
public function testGetForeignClass() { public function testGetForeignClass()
{
$item = $this->objFromFixture('CommentableItem', 'first'); $item = $this->objFromFixture('CommentableItem', 'first');
// This is the class the Comments are related to // This is the class the Comments are related to
@ -47,7 +51,8 @@ class CommentListTest extends FunctionalTest {
$item->Comments()->getForeignClass()); $item->Comments()->getForeignClass());
} }
public function testAddNonComment() { public function testAddNonComment()
{
$item = $this->objFromFixture('CommentableItem', 'first'); $item = $this->objFromFixture('CommentableItem', 'first');
$comments = $item->Comments(); $comments = $item->Comments();
$this->assertEquals(4, $comments->count()); $this->assertEquals(4, $comments->count());
@ -63,7 +68,8 @@ class CommentListTest extends FunctionalTest {
} }
} }
public function testAddComment() { public function testAddComment()
{
$item = $this->objFromFixture('CommentableItem', 'first'); $item = $this->objFromFixture('CommentableItem', 'first');
$firstComment = $this->objFromFixture('Comment', 'firstComA'); $firstComment = $this->objFromFixture('Comment', 'firstComA');
$comments = $item->Comments();//->sort('Created'); $comments = $item->Comments();//->sort('Created');
@ -99,7 +105,8 @@ class CommentListTest extends FunctionalTest {
$list->add($newComment); $list->add($newComment);
} }
public function testRemoveComment() { public function testRemoveComment()
{
// remove by comment // remove by comment
$item = $this->objFromFixture('CommentableItem', 'first'); $item = $this->objFromFixture('CommentableItem', 'first');
$this->assertEquals(4, $item->Comments()->count()); $this->assertEquals(4, $item->Comments()->count());
@ -114,7 +121,8 @@ class CommentListTest extends FunctionalTest {
$this->assertEquals(2, $item->Comments()->count()); $this->assertEquals(2, $item->Comments()->count());
} }
public function testRemoveNonComment() { public function testRemoveNonComment()
{
$item = $this->objFromFixture('CommentableItem', 'first'); $item = $this->objFromFixture('CommentableItem', 'first');
$this->assertEquals(4, $item->Comments()->count()); $this->assertEquals(4, $item->Comments()->count());
$comments = $item->Comments(); $comments = $item->Comments();
@ -134,5 +142,4 @@ class CommentListTest extends FunctionalTest {
); );
} }
} }
} }

View File

@ -1,17 +1,20 @@
<?php <?php
class CommentTestHelper { class CommentTestHelper
{
/* /*
This only works if the last section is not a field group, e.g. a Comments This only works if the last section is not a field group, e.g. a Comments
field group inside of a Root.Settings tab will not work field group inside of a Root.Settings tab will not work
*/ */
public static function assertFieldsForTab($context, $tabName, $expected, $fields) { public static function assertFieldsForTab($context, $tabName, $expected, $fields)
{
$tab = $fields->findOrMakeTab($tabName); $tab = $fields->findOrMakeTab($tabName);
$fields = $tab->FieldList(); $fields = $tab->FieldList();
CommentTestHelper::assertFieldNames($context, $expected, $fields); CommentTestHelper::assertFieldNames($context, $expected, $fields);
} }
public static function assertFieldNames($context, $expected, $fields) { public static function assertFieldNames($context, $expected, $fields)
{
$actual = array(); $actual = array();
foreach ($fields as $field) { foreach ($fields as $field) {
if (get_class($field) == 'FieldGroup') { if (get_class($field) == 'FieldGroup') {

View File

@ -4,7 +4,8 @@
* @package comments * @package comments
* @subpackage tests * @subpackage tests
*/ */
class CommentingControllerTest extends FunctionalTest { class CommentingControllerTest extends FunctionalTest
{
public static $fixture_file = 'CommentsTest.yml'; public static $fixture_file = 'CommentsTest.yml';
@ -14,8 +15,9 @@ class CommentingControllerTest extends FunctionalTest {
protected $securityEnabled; protected $securityEnabled;
public function tearDown() { public function tearDown()
if($this->securityEnabled) { {
if ($this->securityEnabled) {
SecurityToken::enable(); SecurityToken::enable();
} else { } else {
SecurityToken::disable(); SecurityToken::disable();
@ -23,12 +25,14 @@ class CommentingControllerTest extends FunctionalTest {
parent::tearDown(); parent::tearDown();
} }
public function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
$this->securityEnabled = SecurityToken::is_enabled(); $this->securityEnabled = SecurityToken::is_enabled();
} }
public function testApprove() { public function testApprove()
{
SecurityToken::disable(); SecurityToken::disable();
// mark a comment as spam then approve it // mark a comment as spam then approve it
@ -49,10 +53,10 @@ class CommentingControllerTest extends FunctionalTest {
// try and approve a non existent comment // try and approve a non existent comment
$response = $this->get('CommentingController/approve/100000'); $response = $this->get('CommentingController/approve/100000');
$this->assertEquals(404, $response->getStatusCode()); $this->assertEquals(404, $response->getStatusCode());
} }
public function testSetGetOwnerController() { public function testSetGetOwnerController()
{
$commController = new CommentingController(); $commController = new CommentingController();
$commController->setOwnerController(Controller::curr()); $commController->setOwnerController(Controller::curr());
$this->assertEquals(Controller::curr(), $commController->getOwnerController()); $this->assertEquals(Controller::curr(), $commController->getOwnerController());
@ -60,7 +64,8 @@ class CommentingControllerTest extends FunctionalTest {
$this->assertNull($commController->getOwnerController()); $this->assertNull($commController->getOwnerController());
} }
public function testHam() { public function testHam()
{
SecurityToken::disable(); SecurityToken::disable();
// mark a comment as spam then ham it // mark a comment as spam then ham it
@ -81,10 +86,10 @@ class CommentingControllerTest extends FunctionalTest {
// try and ham a non existent comment // try and ham a non existent comment
$response = $this->get('CommentingController/ham/100000'); $response = $this->get('CommentingController/ham/100000');
$this->assertEquals(404, $response->getStatusCode()); $this->assertEquals(404, $response->getStatusCode());
} }
public function testSpam() { public function testSpam()
{
// mark a comment as approved then spam it // mark a comment as approved then spam it
$this->logInWithPermission('CMS_ACCESS_CommentAdmin'); $this->logInWithPermission('CMS_ACCESS_CommentAdmin');
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
@ -103,10 +108,10 @@ class CommentingControllerTest extends FunctionalTest {
// try and spam a non existent comment // try and spam a non existent comment
$response = $this->get('CommentingController/spam/100000'); $response = $this->get('CommentingController/spam/100000');
$this->assertEquals(404, $response->getStatusCode()); $this->assertEquals(404, $response->getStatusCode());
} }
public function testRSS() { public function testRSS()
{
// Delete the newly added children of firstComA so as not to have to recalculate values below // Delete the newly added children of firstComA so as not to have to recalculate values below
$this->objFromFixture('Comment', 'firstComAChild1')->delete(); $this->objFromFixture('Comment', 'firstComAChild1')->delete();
$this->objFromFixture('Comment', 'firstComAChild2')->delete(); $this->objFromFixture('Comment', 'firstComAChild2')->delete();
@ -177,7 +182,8 @@ class CommentingControllerTest extends FunctionalTest {
} }
*/ */
public function testCommentsFormUsePreview() { public function testCommentsFormUsePreview()
{
// test with preview on // test with preview on
Config::inst()->update('CommentableItem', 'comments', array( Config::inst()->update('CommentableItem', 'comments', array(
'use_preview' => true 'use_preview' => true
@ -208,7 +214,8 @@ class CommentingControllerTest extends FunctionalTest {
CommentTestHelper::assertFieldNames($this, $expected, $commentsFields); CommentTestHelper::assertFieldNames($this, $expected, $commentsFields);
} }
public function testCommentsForm() { public function testCommentsForm()
{
// Delete the newly added children of firstComA so as not to change this test // Delete the newly added children of firstComA so as not to change this test
$this->objFromFixture('Comment', 'firstComAChild1')->delete(); $this->objFromFixture('Comment', 'firstComAChild1')->delete();
$this->objFromFixture('Comment', 'firstComAChild2')->delete(); $this->objFromFixture('Comment', 'firstComAChild2')->delete();
@ -268,7 +275,5 @@ class CommentingControllerTest extends FunctionalTest {
'BaseClass' => 'CommentableItem', 'BaseClass' => 'CommentableItem',
'ParentCommentID' => $parentComment->ID 'ParentCommentID' => $parentComment->ID
)), $parentComment->ChildComments()); )), $parentComment->ChildComments());
} }
} }

View File

@ -1,12 +1,15 @@
<?php <?php
class CommentingTest extends SapphireTest { class CommentingTest extends SapphireTest
{
public function setUpOnce() { public function setUpOnce()
{
parent::setUpOnce(); parent::setUpOnce();
} }
public function testDeprecatedMethods() { public function testDeprecatedMethods()
{
$methods = array('add', 'remove', 'has_commenting'); $methods = array('add', 'remove', 'has_commenting');
foreach ($methods as $methodName) { foreach ($methods as $methodName) {
try { try {
@ -20,7 +23,8 @@ class CommentingTest extends SapphireTest {
} }
public function test_set_config_value() { public function test_set_config_value()
{
// public static function set_config_value($class, $key, $value = false) { // public static function set_config_value($class, $key, $value = false) {
Commenting::set_config_value( Commenting::set_config_value(
'CommentableItem', 'CommentableItem',
@ -55,7 +59,8 @@ class CommentingTest extends SapphireTest {
); );
} }
public function test_get_config_value() { public function test_get_config_value()
{
Config::inst()->update('CommentableItem', 'comments', Config::inst()->update('CommentableItem', 'comments',
array( array(
'comments_holder_id' => 'commentable_item' 'comments_holder_id' => 'commentable_item'
@ -84,7 +89,8 @@ class CommentingTest extends SapphireTest {
Commenting::get_config_value('Member', 'comments_holder_id'); Commenting::get_config_value('Member', 'comments_holder_id');
} }
public function test_config_value_equals() { public function test_config_value_equals()
{
Config::inst()->update('CommentableItem', 'comments', Config::inst()->update('CommentableItem', 'comments',
array( array(
'comments_holder_id' => 'some_value' 'comments_holder_id' => 'some_value'
@ -108,7 +114,8 @@ class CommentingTest extends SapphireTest {
); );
} }
public function test_add() { public function test_add()
{
Commenting::add('Member', array('comments_holder_id' => 'test_add_value')); Commenting::add('Member', array('comments_holder_id' => 'test_add_value'));
$config = Config::inst()->get( $config = Config::inst()->get(
@ -136,13 +143,14 @@ class CommentingTest extends SapphireTest {
$this->setExpectedException('InvalidArgumentException', "\$settings needs to be an array or null"); $this->setExpectedException('InvalidArgumentException', "\$settings needs to be an array or null");
Commenting::add('Member', 'illegal format, not an array'); Commenting::add('Member', 'illegal format, not an array');
} }
public function test_can_member_post() { public function test_can_member_post()
{
// logout // logout
if($member = Member::currentUser()) $member->logOut(); if ($member = Member::currentUser()) {
$member->logOut();
}
Config::inst()->update('CommentableItem', 'comments', Config::inst()->update('CommentableItem', 'comments',
array( array(
@ -169,5 +177,4 @@ class CommentingTest extends SapphireTest {
$this->assertTrue(Commenting::can_member_post('CommentableItem')); $this->assertTrue(Commenting::can_member_post('CommentableItem'));
} }
} }

View File

@ -1,6 +1,7 @@
<?php <?php
class CommentsExtensionTest extends SapphireTest { class CommentsExtensionTest extends SapphireTest
{
public static $fixture_file = 'comments/tests/CommentsTest.yml'; public static $fixture_file = 'comments/tests/CommentsTest.yml';
@ -10,7 +11,8 @@ class CommentsExtensionTest extends SapphireTest {
'CommentableItemDisabled' 'CommentableItemDisabled'
); );
public function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
Config::nest(); Config::nest();
@ -38,20 +40,24 @@ class CommentsExtensionTest extends SapphireTest {
)); ));
} }
public function tearDown() { public function tearDown()
{
Config::unnest(); Config::unnest();
parent::tearDown(); parent::tearDown();
} }
public function testPopulateDefaults() { public function testPopulateDefaults()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
public function testUpdateSettingsFields() { public function testUpdateSettingsFields()
{
$this->markTestSkipped('This needs SiteTree installed'); $this->markTestSkipped('This needs SiteTree installed');
} }
public function testGetModerationRequired() { public function testGetModerationRequired()
{
// the 3 options take precedence in this order, executed if true // the 3 options take precedence in this order, executed if true
Config::inst()->update('CommentableItem', 'comments', array( Config::inst()->update('CommentableItem', 'comments', array(
@ -92,7 +98,8 @@ class CommentsExtensionTest extends SapphireTest {
$this->assertEquals('None', $item->getModerationRequired()); $this->assertEquals('None', $item->getModerationRequired());
} }
public function testGetCommentsRequireLogin() { public function testGetCommentsRequireLogin()
{
Config::inst()->update('CommentableItem', 'comments', array( Config::inst()->update('CommentableItem', 'comments', array(
'require_login_cms' => true 'require_login_cms' => true
)); ));
@ -115,26 +122,30 @@ class CommentsExtensionTest extends SapphireTest {
'require_login' => true 'require_login' => true
)); ));
$this->assertTrue($item->getCommentsRequireLogin()); $this->assertTrue($item->getCommentsRequireLogin());
} }
public function testAllComments() { public function testAllComments()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
public function testAllVisibleComments() { public function testAllVisibleComments()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
public function testComments() { public function testComments()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
public function testGetCommentsEnabled() { public function testGetCommentsEnabled()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
public function testGetCommentHolderID() { public function testGetCommentHolderID()
{
$item = $this->objFromFixture('CommentableItem', 'first'); $item = $this->objFromFixture('CommentableItem', 'first');
Config::inst()->update('CommentableItem', 'comments', array( Config::inst()->update('CommentableItem', 'comments', array(
'comments_holder_id' => 'commentid_test1', 'comments_holder_id' => 'commentid_test1',
@ -148,30 +159,35 @@ class CommentsExtensionTest extends SapphireTest {
} }
public function testGetPostingRequiredPermission() { public function testGetPostingRequiredPermission()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
public function testCanModerateComments() { public function testCanModerateComments()
{
// ensure nobody logged in // ensure nobody logged in
if(Member::currentUser()) { Member::currentUser()->logOut(); } if (Member::currentUser()) {
Member::currentUser()->logOut();
}
$item = $this->objFromFixture('CommentableItem', 'first'); $item = $this->objFromFixture('CommentableItem', 'first');
$this->assertFalse($item->canModerateComments()); $this->assertFalse($item->canModerateComments());
$this->logInWithPermission('CMS_ACCESS_CommentAdmin'); $this->logInWithPermission('CMS_ACCESS_CommentAdmin');
$this->assertTrue($item->canModerateComments()); $this->assertTrue($item->canModerateComments());
} }
public function testGetCommentRSSLink() { public function testGetCommentRSSLink()
{
$item = $this->objFromFixture('CommentableItem', 'first'); $item = $this->objFromFixture('CommentableItem', 'first');
$link = $item->getCommentRSSLink(); $link = $item->getCommentRSSLink();
$this->assertEquals('/CommentingController/rss', $link); $this->assertEquals('/CommentingController/rss', $link);
} }
public function testGetCommentRSSLinkPage() { public function testGetCommentRSSLinkPage()
{
$item = $this->objFromFixture('CommentableItem', 'first'); $item = $this->objFromFixture('CommentableItem', 'first');
$page = $item->getCommentRSSLinkPage(); $page = $item->getCommentRSSLinkPage();
$this->assertEquals( $this->assertEquals(
@ -180,7 +196,8 @@ class CommentsExtensionTest extends SapphireTest {
); );
} }
public function testCommentsForm() { public function testCommentsForm()
{
Config::inst()->update('CommentableItem', 'comments', array( Config::inst()->update('CommentableItem', 'comments', array(
'include_js' => false 'include_js' => false
) )
@ -257,11 +274,13 @@ class CommentsExtensionTest extends SapphireTest {
); );
} }
public function testAttachedToSiteTree() { public function testAttachedToSiteTree()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
public function testPagedComments() { public function testPagedComments()
{
$item = $this->objFromFixture('CommentableItem', 'first'); $item = $this->objFromFixture('CommentableItem', 'first');
// Ensure Created times are set, as order not guaranteed if all set to 0 // Ensure Created times are set, as order not guaranteed if all set to 0
$comments = $item->PagedComments()->sort('ID'); $comments = $item->PagedComments()->sort('ID');
@ -299,15 +318,18 @@ class CommentsExtensionTest extends SapphireTest {
$this->assertEquals(4, sizeof($results)); $this->assertEquals(4, sizeof($results));
} }
public function testGetCommentsOption() { public function testGetCommentsOption()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
public function testUpdateModerationFields() { public function testUpdateModerationFields()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
public function testUpdateCMSFields() { public function testUpdateCMSFields()
{
Config::inst()->update('CommentableItem', 'comments', array( Config::inst()->update('CommentableItem', 'comments', array(
'require_login_cms' => false 'require_login_cms' => false
) )
@ -380,7 +402,8 @@ class CommentsExtensionTest extends SapphireTest {
public function testDeprecatedMethods() { public function testDeprecatedMethods()
{
$item = $this->objFromFixture('CommentableItem', 'first'); $item = $this->objFromFixture('CommentableItem', 'first');
$methodNames = array( $methodNames = array(
'getRssLinkPage', 'getRssLinkPage',
@ -403,7 +426,5 @@ class CommentsExtensionTest extends SapphireTest {
} }
// ooh, $this->setExpectedException('ExpectedException', 'Expected Message'); // ooh, $this->setExpectedException('ExpectedException', 'Expected Message');
} }
} }

View File

@ -1,6 +1,7 @@
<?php <?php
class CommentsGridFieldActionTest extends SapphireTest { class CommentsGridFieldActionTest extends SapphireTest
{
/** @var ArrayList */ /** @var ArrayList */
protected $list; protected $list;
@ -11,7 +12,8 @@ class CommentsGridFieldActionTest extends SapphireTest {
/** @var Form */ /** @var Form */
protected $form; protected $form;
public function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
$this->list = new DataList('GridFieldAction_Delete_Team'); $this->list = new DataList('GridFieldAction_Delete_Team');
$config = CommentsGridFieldConfig::create()->addComponent(new GridFieldDeleteAction()); $config = CommentsGridFieldConfig::create()->addComponent(new GridFieldDeleteAction());
@ -19,7 +21,8 @@ class CommentsGridFieldActionTest extends SapphireTest {
$this->form = new Form(new Controller(), 'mockform', new FieldList(array($this->gridField)), new FieldList()); $this->form = new Form(new Controller(), 'mockform', new FieldList(array($this->gridField)), new FieldList());
} }
public function testAugmentColumns() { public function testAugmentColumns()
{
$action = new CommentsGridFieldAction(); $action = new CommentsGridFieldAction();
// an entry called 'Actions' is added to the columns array // an entry called 'Actions' is added to the columns array
@ -34,14 +37,16 @@ class CommentsGridFieldActionTest extends SapphireTest {
$this->assertEquals($expected, $columns); $this->assertEquals($expected, $columns);
} }
public function testGetColumnAttributes() { public function testGetColumnAttributes()
{
$action = new CommentsGridFieldAction(); $action = new CommentsGridFieldAction();
$record = new Comment(); $record = new Comment();
$attrs = $action->getColumnAttributes($this->gridField, $record, 'Comment'); $attrs = $action->getColumnAttributes($this->gridField, $record, 'Comment');
$this->assertEquals(array('class' => 'col-buttons'), $attrs); $this->assertEquals(array('class' => 'col-buttons'), $attrs);
} }
public function testGetColumnMetadata() { public function testGetColumnMetadata()
{
$action = new CommentsGridFieldAction(); $action = new CommentsGridFieldAction();
$result = $action->getColumnMetadata($this->gridField, 'Actions'); $result = $action->getColumnMetadata($this->gridField, 'Actions');
$this->assertEquals(array('title' => ''), $result); $this->assertEquals(array('title' => ''), $result);
@ -49,13 +54,15 @@ class CommentsGridFieldActionTest extends SapphireTest {
$this->assertNull($result); $this->assertNull($result);
} }
public function testGetColumnsHandled() { public function testGetColumnsHandled()
{
$action = new CommentsGridFieldAction(); $action = new CommentsGridFieldAction();
$result = $action->getColumnsHandled($this->gridField); $result = $action->getColumnsHandled($this->gridField);
$this->assertEquals(array('Actions'), $result); $this->assertEquals(array('Actions'), $result);
} }
public function testGetColumnContent() { public function testGetColumnContent()
{
$this->logInWithPermission('CMS_ACCESS_CommentAdmin'); $this->logInWithPermission('CMS_ACCESS_CommentAdmin');
$action = new CommentsGridFieldAction(); $action = new CommentsGridFieldAction();
$record = new Comment(); $record = new Comment();
@ -89,14 +96,16 @@ class CommentsGridFieldActionTest extends SapphireTest {
$this->assertContains($spamAction, $html); $this->assertContains($spamAction, $html);
} }
public function testGetActions() { public function testGetActions()
{
$action = new CommentsGridFieldAction(); $action = new CommentsGridFieldAction();
$result = $action->getActions($this->gridField); $result = $action->getActions($this->gridField);
$this->assertEquals(array('spam', 'approve'), $result); $this->assertEquals(array('spam', 'approve'), $result);
} }
public function testHandleAction() { public function testHandleAction()
{
$action = new CommentsGridFieldAction(); $action = new CommentsGridFieldAction();
$record = new Comment(); $record = new Comment();
$record->Name = 'Name of commeter'; $record->Name = 'Name of commeter';
@ -105,7 +114,7 @@ class CommentsGridFieldActionTest extends SapphireTest {
$recordID = $record->ID; $recordID = $record->ID;
$arguments = array('RecordID' => $recordID); $arguments = array('RecordID' => $recordID);
$data = array(); $data = array();
$result = $action->handleAction($this->gridField, 'spam', $arguments, $data ); $result = $action->handleAction($this->gridField, 'spam', $arguments, $data);
$this->assertEquals(200, Controller::curr()->getResponse()->getStatusCode()); $this->assertEquals(200, Controller::curr()->getResponse()->getStatusCode());
$this->assertEquals( $this->assertEquals(
'Comment marked as spam.', 'Comment marked as spam.',
@ -116,7 +125,7 @@ class CommentsGridFieldActionTest extends SapphireTest {
$this->assertEquals(1, $record->IsSpam); $this->assertEquals(1, $record->IsSpam);
//getStatusDescription //getStatusDescription
$result = $action->handleAction($this->gridField, 'approve', $arguments, $data ); $result = $action->handleAction($this->gridField, 'approve', $arguments, $data);
$this->assertEquals(200, Controller::curr()->getResponse()->getStatusCode()); $this->assertEquals(200, Controller::curr()->getResponse()->getStatusCode());
$this->assertEquals( $this->assertEquals(
'Comment approved.', 'Comment approved.',
@ -129,5 +138,4 @@ class CommentsGridFieldActionTest extends SapphireTest {
error_log(Controller::curr()->getResponse()->getStatusCode()); error_log(Controller::curr()->getResponse()->getStatusCode());
} }
} }

View File

@ -1,12 +1,14 @@
<?php <?php
class CommentsGridFieldBulkActionTest extends SapphireTest { class CommentsGridFieldBulkActionTest extends SapphireTest
public function testSpam() { {
public function testSpam()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
public function testApprove() { public function testApprove()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
} }

View File

@ -1,9 +1,10 @@
<?php <?php
class CommentsGridFieldConfigTest extends SapphireTest { class CommentsGridFieldConfigTest extends SapphireTest
public function test__construct() { {
public function test__construct()
{
$config = new CommentsGridFieldConfigTest(); $config = new CommentsGridFieldConfigTest();
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
} }

View File

@ -1,7 +1,9 @@
<?php <?php
class CommentsGridFieldTest extends SapphireTest { class CommentsGridFieldTest extends SapphireTest
public function testNewRow() { {
public function testNewRow()
{
$gridfield = new CommentsGridField('testfield', 'testfield'); $gridfield = new CommentsGridField('testfield', 'testfield');
// protected function newRow($total, $index, $record, $attributes, $content) { // protected function newRow($total, $index, $record, $attributes, $content) {
$comment = new Comment(); $comment = new Comment();
@ -14,9 +16,7 @@ class CommentsGridFieldTest extends SapphireTest {
$class = new ReflectionClass($gridfield); $class = new ReflectionClass($gridfield);
$method = $class->getMethod('newRow'); $method = $class->getMethod('newRow');
$method->setAccessible(true); $method->setAccessible(true);
} } catch (ReflectionException $e) {
catch (ReflectionException $e) {
$this->fail($e->getMessage()); $this->fail($e->getMessage());
} }
@ -33,8 +33,5 @@ class CommentsGridFieldTest extends SapphireTest {
$params = array(1, 1, $comment, $attr, $comment->Comment); $params = array(1, 1, $comment, $attr, $comment->Comment);
$newRow = $method->invokeArgs($gridfield, $params); $newRow = $method->invokeArgs($gridfield, $params);
$this->assertEquals('<tr class="cssClass spam">This is a comment</tr>', $newRow); $this->assertEquals('<tr class="cssClass spam">This is a comment</tr>', $newRow);
} }
} }

View File

@ -3,7 +3,8 @@
/** /**
* @package comments * @package comments
*/ */
class CommentsTest extends FunctionalTest { class CommentsTest extends FunctionalTest
{
public static $fixture_file = 'comments/tests/CommentsTest.yml'; public static $fixture_file = 'comments/tests/CommentsTest.yml';
@ -13,7 +14,8 @@ class CommentsTest extends FunctionalTest {
'CommentableItemDisabled' 'CommentableItemDisabled'
); );
public function setUp() { public function setUp()
{
parent::setUp(); parent::setUp();
Config::nest(); Config::nest();
@ -37,12 +39,14 @@ class CommentsTest extends FunctionalTest {
)); ));
} }
public function tearDown() { public function tearDown()
{
Config::unnest(); Config::unnest();
parent::tearDown(); parent::tearDown();
} }
public function testCommentsList() { public function testCommentsList()
{
// comments don't require moderation so unmoderated comments can be // comments don't require moderation so unmoderated comments can be
// shown but not spam posts // shown but not spam posts
Config::inst()->update('CommentableItem', 'comments', array( Config::inst()->update('CommentableItem', 'comments', array(
@ -95,7 +99,9 @@ class CommentsTest extends FunctionalTest {
'frontend_moderation' => false, 'frontend_moderation' => false,
'frontend_spam' => true, 'frontend_spam' => true,
)); ));
if($member = Member::currentUser()) $member->logOut(); if ($member = Member::currentUser()) {
$member->logOut();
}
$this->assertEquals(1, $item->Comments()->Count()); $this->assertEquals(1, $item->Comments()->Count());
$this->logInWithPermission('ADMIN'); $this->logInWithPermission('ADMIN');
@ -108,7 +114,9 @@ class CommentsTest extends FunctionalTest {
'frontend_moderation' => true, 'frontend_moderation' => true,
'frontend_spam' => true, 'frontend_spam' => true,
)); ));
if($member = Member::currentUser()) $member->logOut(); if ($member = Member::currentUser()) {
$member->logOut();
}
$this->assertEquals(1, $item->Comments()->Count()); $this->assertEquals(1, $item->Comments()->Count());
$this->logInWithPermission('ADMIN'); $this->logInWithPermission('ADMIN');
@ -118,7 +126,8 @@ class CommentsTest extends FunctionalTest {
/** /**
* Test moderation options configured via the CMS * Test moderation options configured via the CMS
*/ */
public function testCommentCMSModerationList() { public function testCommentCMSModerationList()
{
// comments don't require moderation so unmoderated comments can be // comments don't require moderation so unmoderated comments can be
// shown but not spam posts // shown but not spam posts
Config::inst()->update('CommentableItem', 'comments', array( Config::inst()->update('CommentableItem', 'comments', array(
@ -159,7 +168,8 @@ class CommentsTest extends FunctionalTest {
$this->assertEquals(2, $item->Comments()->Count()); $this->assertEquals(2, $item->Comments()->Count());
} }
public function testCanPostComment() { public function testCanPostComment()
{
Config::inst()->update('CommentableItem', 'comments', array( Config::inst()->update('CommentableItem', 'comments', array(
'require_login' => false, 'require_login' => false,
'require_login_cms' => false, 'require_login_cms' => false,
@ -169,7 +179,9 @@ class CommentsTest extends FunctionalTest {
$item2 = $this->objFromFixture('CommentableItem', 'second'); $item2 = $this->objFromFixture('CommentableItem', 'second');
// Test restriction free commenting // Test restriction free commenting
if($member = Member::currentUser()) $member->logOut(); if ($member = Member::currentUser()) {
$member->logOut();
}
$this->assertFalse($item->CommentsRequireLogin); $this->assertFalse($item->CommentsRequireLogin);
$this->assertTrue($item->canPostComment()); $this->assertTrue($item->canPostComment());
@ -192,7 +204,9 @@ class CommentsTest extends FunctionalTest {
'required_permission' => false, 'required_permission' => false,
)); ));
$this->assertTrue($item->CommentsRequireLogin); $this->assertTrue($item->CommentsRequireLogin);
if($member = Member::currentUser()) $member->logOut(); if ($member = Member::currentUser()) {
$member->logOut();
}
$this->assertFalse($item->canPostComment()); $this->assertFalse($item->canPostComment());
$this->logInWithPermission('ANY_PERMISSION'); $this->logInWithPermission('ANY_PERMISSION');
$this->assertTrue($item->canPostComment()); $this->assertTrue($item->canPostComment());
@ -204,7 +218,9 @@ class CommentsTest extends FunctionalTest {
)); ));
$this->assertFalse($item->CommentsRequireLogin); $this->assertFalse($item->CommentsRequireLogin);
$this->assertTrue($item2->CommentsRequireLogin); $this->assertTrue($item2->CommentsRequireLogin);
if($member = Member::currentUser()) $member->logOut(); if ($member = Member::currentUser()) {
$member->logOut();
}
$this->assertTrue($item->canPostComment()); $this->assertTrue($item->canPostComment());
$this->assertFalse($item2->canPostComment()); $this->assertFalse($item2->canPostComment());
@ -212,11 +228,13 @@ class CommentsTest extends FunctionalTest {
$this->logInWithPermission('ANY_PERMISSION'); $this->logInWithPermission('ANY_PERMISSION');
$this->assertTrue($item->canPostComment()); $this->assertTrue($item->canPostComment());
$this->assertTrue($item2->canPostComment()); $this->assertTrue($item2->canPostComment());
} }
public function testDeleteComment() { public function testDeleteComment()
{
// Test anonymous user // Test anonymous user
if($member = Member::currentUser()) $member->logOut(); if ($member = Member::currentUser()) {
$member->logOut();
}
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
$commentID = $comment->ID; $commentID = $comment->ID;
$this->assertNull($comment->DeleteLink(), 'No permission to see delete link'); $this->assertNull($comment->DeleteLink(), 'No permission to see delete link');
@ -253,9 +271,12 @@ class CommentsTest extends FunctionalTest {
$this->assertFalse($check && $check->exists()); $this->assertFalse($check && $check->exists());
} }
public function testSpamComment() { public function testSpamComment()
{
// Test anonymous user // Test anonymous user
if($member = Member::currentUser()) $member->logOut(); if ($member = Member::currentUser()) {
$member->logOut();
}
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
$commentID = $comment->ID; $commentID = $comment->ID;
$this->assertNull($comment->SpamLink(), 'No permission to see mark as spam link'); $this->assertNull($comment->SpamLink(), 'No permission to see mark as spam link');
@ -295,9 +316,12 @@ class CommentsTest extends FunctionalTest {
$this->assertNull($check->SpamLink()); $this->assertNull($check->SpamLink());
} }
public function testHamComment() { public function testHamComment()
{
// Test anonymous user // Test anonymous user
if($member = Member::currentUser()) $member->logOut(); if ($member = Member::currentUser()) {
$member->logOut();
}
$comment = $this->objFromFixture('Comment', 'secondComC'); $comment = $this->objFromFixture('Comment', 'secondComC');
$commentID = $comment->ID; $commentID = $comment->ID;
$this->assertNull($comment->HamLink(), 'No permission to see mark as ham link'); $this->assertNull($comment->HamLink(), 'No permission to see mark as ham link');
@ -337,9 +361,12 @@ class CommentsTest extends FunctionalTest {
$this->assertNull($check->HamLink()); $this->assertNull($check->HamLink());
} }
public function testApproveComment() { public function testApproveComment()
{
// Test anonymous user // Test anonymous user
if($member = Member::currentUser()) $member->logOut(); if ($member = Member::currentUser()) {
$member->logOut();
}
$comment = $this->objFromFixture('Comment', 'secondComB'); $comment = $this->objFromFixture('Comment', 'secondComB');
$commentID = $comment->ID; $commentID = $comment->ID;
$this->assertNull($comment->ApproveLink(), 'No permission to see approve link'); $this->assertNull($comment->ApproveLink(), 'No permission to see approve link');
@ -379,7 +406,8 @@ class CommentsTest extends FunctionalTest {
$this->assertNull($check->ApproveLink()); $this->assertNull($check->ApproveLink());
} }
public function testCommenterURLWrite() { public function testCommenterURLWrite()
{
$comment = new Comment(); $comment = new Comment();
// We only care about the CommenterURL, so only set that // We only care about the CommenterURL, so only set that
// Check a http and https URL. Add more test urls here as needed. // Check a http and https URL. Add more test urls here as needed.
@ -389,7 +417,7 @@ class CommentsTest extends FunctionalTest {
); );
$url = '://example.com'; $url = '://example.com';
foreach($protocols as $protocol) { foreach ($protocols as $protocol) {
$comment->CommenterURL = $protocol . $url; $comment->CommenterURL = $protocol . $url;
// The protocol should stay as if, assuming it is valid // The protocol should stay as if, assuming it is valid
$comment->write(); $comment->write();
@ -397,8 +425,9 @@ class CommentsTest extends FunctionalTest {
} }
} }
public function testSanitizesWithAllowHtml() { public function testSanitizesWithAllowHtml()
if(!class_exists('HTMLPurifier')) { {
if (!class_exists('HTMLPurifier')) {
$this->markTestSkipped('HTMLPurifier class not found'); $this->markTestSkipped('HTMLPurifier class not found');
return; return;
} }
@ -435,8 +464,9 @@ class CommentsTest extends FunctionalTest {
); );
} }
public function testDefaultTemplateRendersHtmlWithAllowHtml() { public function testDefaultTemplateRendersHtmlWithAllowHtml()
if(!class_exists('HTMLPurifier')) { {
if (!class_exists('HTMLPurifier')) {
$this->markTestSkipped('HTMLPurifier class not found'); $this->markTestSkipped('HTMLPurifier class not found');
} }
@ -468,14 +498,14 @@ class CommentsTest extends FunctionalTest {
'<p>my comment</p>', '<p>my comment</p>',
$html $html
); );
} }
/** /**
* Tests whether comments are enabled or disabled by default * Tests whether comments are enabled or disabled by default
*/ */
public function testDefaultEnabled() { public function testDefaultEnabled()
{
// Ensure values are set via cms (not via config) // Ensure values are set via cms (not via config)
Config::inst()->update('CommentableItem', 'comments', array( Config::inst()->update('CommentableItem', 'comments', array(
'enabled_cms' => true, 'enabled_cms' => true,
@ -527,7 +557,8 @@ class CommentsTest extends FunctionalTest {
/* /*
When a parent comment is deleted, remove the children When a parent comment is deleted, remove the children
*/ */
public function testOnBeforeDelete() { public function testOnBeforeDelete()
{
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
$child = new Comment(); $child = new Comment();
@ -547,11 +578,13 @@ class CommentsTest extends FunctionalTest {
$this->assertFalse(DataObject::get_by_id('Comment', $childCommentID)); $this->assertFalse(DataObject::get_by_id('Comment', $childCommentID));
} }
public function testRequireDefaultRecords() { public function testRequireDefaultRecords()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
public function testLink() { public function testLink()
{
$comment = $this->objFromFixture('Comment', 'thirdComD'); $comment = $this->objFromFixture('Comment', 'thirdComD');
$this->assertEquals('CommentableItem_Controller#comment-'.$comment->ID, $this->assertEquals('CommentableItem_Controller#comment-'.$comment->ID,
$comment->Link()); $comment->Link());
@ -563,7 +596,8 @@ class CommentsTest extends FunctionalTest {
$this->assertEquals('', $comment->Link()); $this->assertEquals('', $comment->Link());
} }
public function testPermalink() { public function testPermalink()
{
$comment = $this->objFromFixture('Comment', 'thirdComD'); $comment = $this->objFromFixture('Comment', 'thirdComD');
$this->assertEquals('comment-' . $comment->ID, $comment->Permalink()); $this->assertEquals('comment-' . $comment->ID, $comment->Permalink());
} }
@ -571,7 +605,8 @@ class CommentsTest extends FunctionalTest {
/* /*
Test field labels in 2 languages Test field labels in 2 languages
*/ */
public function testFieldLabels() { public function testFieldLabels()
{
$locale = i18n::get_locale(); $locale = i18n::get_locale();
i18n::set_locale('fr'); i18n::set_locale('fr');
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
@ -619,18 +654,21 @@ class CommentsTest extends FunctionalTest {
$this->assertEquals($expected, $labels); $this->assertEquals($expected, $labels);
} }
public function testGetOption() { public function testGetOption()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
public function testGetParent() { public function testGetParent()
{
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
$item = $this->objFromFixture('CommentableItem', 'first'); $item = $this->objFromFixture('CommentableItem', 'first');
$parent = $comment->getParent(); $parent = $comment->getParent();
$this->assertEquals($item, $parent); $this->assertEquals($item, $parent);
} }
public function testGetParentTitle() { public function testGetParentTitle()
{
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
$title = $comment->getParentTitle(); $title = $comment->getParentTitle();
$this->assertEquals('First', $title); $this->assertEquals('First', $title);
@ -641,21 +679,25 @@ class CommentsTest extends FunctionalTest {
$this->assertEquals('', $comment->getParentTitle()); $this->assertEquals('', $comment->getParentTitle());
} }
public function testGetParentClassName() { public function testGetParentClassName()
{
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
$className = $comment->getParentClassName(); $className = $comment->getParentClassName();
$this->assertEquals('CommentableItem', $className); $this->assertEquals('CommentableItem', $className);
} }
public function testCastingHelper() { public function testCastingHelper()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
public function testGetEscapedComment() { public function testGetEscapedComment()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
public function testIsPreview() { public function testIsPreview()
{
$comment = new Comment(); $comment = new Comment();
$comment->Name = 'Fred Bloggs'; $comment->Name = 'Fred Bloggs';
$comment->Comment = 'this is a test comment'; $comment->Comment = 'this is a test comment';
@ -664,7 +706,8 @@ class CommentsTest extends FunctionalTest {
$this->assertFalse($comment->isPreview()); $this->assertFalse($comment->isPreview());
} }
public function testCanCreate() { public function testCanCreate()
{
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
// admin can create - this is always false // admin can create - this is always false
@ -676,7 +719,8 @@ class CommentsTest extends FunctionalTest {
$this->assertFalse($comment->canCreate()); $this->assertFalse($comment->canCreate());
} }
public function testCanView() { public function testCanView()
{
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
// admin can view // admin can view
@ -692,7 +736,8 @@ class CommentsTest extends FunctionalTest {
$this->assertFalse($comment->canView()); $this->assertFalse($comment->canView());
} }
public function testCanEdit() { public function testCanEdit()
{
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
// admin can edit // admin can edit
@ -708,7 +753,8 @@ class CommentsTest extends FunctionalTest {
$this->assertFalse($comment->canEdit()); $this->assertFalse($comment->canEdit());
} }
public function testCanDelete() { public function testCanDelete()
{
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
// admin can delete // admin can delete
@ -724,7 +770,8 @@ class CommentsTest extends FunctionalTest {
$this->assertFalse($comment->canDelete()); $this->assertFalse($comment->canDelete());
} }
public function testGetMember() { public function testGetMember()
{
$this->logInAs('visitor'); $this->logInAs('visitor');
$current = Member::currentUser(); $current = Member::currentUser();
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
@ -743,7 +790,8 @@ class CommentsTest extends FunctionalTest {
$this->assertEquals($current, $member); $this->assertEquals($current, $member);
} }
public function testGetAuthorName() { public function testGetAuthorName()
{
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
$this->assertEquals( $this->assertEquals(
'FA', 'FA',
@ -768,11 +816,11 @@ class CommentsTest extends FunctionalTest {
$comment->Name = null; $comment->Name = null;
$comment->AuthorID = 0; $comment->AuthorID = 0;
$this->assertNull($comment->getAuthorName()); $this->assertNull($comment->getAuthorName());
} }
public function testLinks() { public function testLinks()
{
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
$this->logInAs('commentadmin'); $this->logInAs('commentadmin');
@ -808,27 +856,31 @@ class CommentsTest extends FunctionalTest {
); );
} }
public function testMarkSpam() { public function testMarkSpam()
{
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
$comment->markSpam(); $comment->markSpam();
$this->assertTrue($comment->Moderated); $this->assertTrue($comment->Moderated);
$this->assertTrue($comment->IsSpam); $this->assertTrue($comment->IsSpam);
} }
public function testMarkApproved() { public function testMarkApproved()
{
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
$comment->markApproved(); $comment->markApproved();
$this->assertTrue($comment->Moderated); $this->assertTrue($comment->Moderated);
$this->assertFalse($comment->IsSpam); $this->assertFalse($comment->IsSpam);
} }
public function testMarkUnapproved() { public function testMarkUnapproved()
{
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
$comment->markApproved(); $comment->markApproved();
$this->assertTrue($comment->Moderated); $this->assertTrue($comment->Moderated);
} }
public function testSpamClass() { public function testSpamClass()
{
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
$this->assertEquals('notspam', $comment->spamClass()); $this->assertEquals('notspam', $comment->spamClass());
$comment->Moderated = false; $comment->Moderated = false;
@ -837,7 +889,8 @@ class CommentsTest extends FunctionalTest {
$this->assertEquals('spam', $comment->spamClass()); $this->assertEquals('spam', $comment->spamClass());
} }
public function testGetTitle() { public function testGetTitle()
{
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
$this->assertEquals( $this->assertEquals(
'Comment by FA on First', 'Comment by FA on First',
@ -845,7 +898,8 @@ class CommentsTest extends FunctionalTest {
); );
} }
public function testGetCMSFields() { public function testGetCMSFields()
{
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
$fields = $comment->getCMSFields(); $fields = $comment->getCMSFields();
$names = array(); $names = array();
@ -863,7 +917,8 @@ class CommentsTest extends FunctionalTest {
$this->assertEquals($expected, $names); $this->assertEquals($expected, $names);
} }
public function testGetCMSFieldsCommentHasAuthor() { public function testGetCMSFieldsCommentHasAuthor()
{
$member = Member::get()->filter('FirstName', 'visitor')->first(); $member = Member::get()->filter('FirstName', 'visitor')->first();
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
$comment->AuthorID = $member->ID; $comment->AuthorID = $member->ID;
@ -886,7 +941,8 @@ class CommentsTest extends FunctionalTest {
$this->assertEquals($expected, $names); $this->assertEquals($expected, $names);
} }
public function testGetCMSFieldsWithParentComment() { public function testGetCMSFieldsWithParentComment()
{
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
$child = new Comment(); $child = new Comment();
@ -916,7 +972,8 @@ class CommentsTest extends FunctionalTest {
} }
public function testPurifyHtml() { public function testPurifyHtml()
{
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
$dirtyHTML = '<p><script>alert("w00t")</script>my comment</p>'; $dirtyHTML = '<p><script>alert("w00t")</script>my comment</p>';
@ -926,7 +983,8 @@ class CommentsTest extends FunctionalTest {
); );
} }
public function testGravatar() { public function testGravatar()
{
// Turn gravatars on // Turn gravatars on
Config::inst()->update('CommentableItem', 'comments', array( Config::inst()->update('CommentableItem', 'comments', array(
'use_gravatar' => true 'use_gravatar' => true
@ -951,7 +1009,8 @@ class CommentsTest extends FunctionalTest {
); );
} }
public function testGetRepliesEnabled() { public function testGetRepliesEnabled()
{
$comment = $this->objFromFixture('Comment', 'firstComA'); $comment = $this->objFromFixture('Comment', 'firstComA');
Config::inst()->update('CommentableItem', 'comments', array( Config::inst()->update('CommentableItem', 'comments', array(
'nested_comments' => false 'nested_comments' => false
@ -983,11 +1042,10 @@ class CommentsTest extends FunctionalTest {
$comment->markApproved(); $comment->markApproved();
$this->assertTrue($comment->getRepliesEnabled()); $this->assertTrue($comment->getRepliesEnabled());
} }
public function testAllReplies() { public function testAllReplies()
{
Config::inst()->update('CommentableItem', 'comments', array( Config::inst()->update('CommentableItem', 'comments', array(
'nested_comments' => true, 'nested_comments' => true,
'nested_depth' => 4 'nested_depth' => 4
@ -1018,7 +1076,8 @@ class CommentsTest extends FunctionalTest {
$this->assertEquals(0, $comment->allReplies()->count()); $this->assertEquals(0, $comment->allReplies()->count());
} }
public function testReplies() { public function testReplies()
{
CommentableItem::add_extension('CommentsExtension'); CommentableItem::add_extension('CommentsExtension');
$this->logInWithPermission('ADMIN'); $this->logInWithPermission('ADMIN');
Config::inst()->update('CommentableItem', 'comments', array( Config::inst()->update('CommentableItem', 'comments', array(
@ -1085,7 +1144,8 @@ class CommentsTest extends FunctionalTest {
CommentableItem::remove_extension('CommentsExtension'); CommentableItem::remove_extension('CommentsExtension');
} }
public function testPagedReplies() { public function testPagedReplies()
{
Config::inst()->update('CommentableItem', 'comments', array( Config::inst()->update('CommentableItem', 'comments', array(
'nested_comments' => true, 'nested_comments' => true,
'nested_depth' => 4, 'nested_depth' => 4,
@ -1111,7 +1171,8 @@ class CommentsTest extends FunctionalTest {
$this->assertEquals(0, $comment->PagedReplies()->count()); $this->assertEquals(0, $comment->PagedReplies()->count());
} }
public function testReplyForm() { public function testReplyForm()
{
Config::inst()->update('CommentableItem', 'comments', array( Config::inst()->update('CommentableItem', 'comments', array(
'nested_comments' => false, 'nested_comments' => false,
'nested_depth' => 4 'nested_depth' => 4
@ -1154,7 +1215,8 @@ class CommentsTest extends FunctionalTest {
$this->assertNull($form); $this->assertNull($form);
} }
public function testUpdateDepth() { public function testUpdateDepth()
{
Config::inst()->update('CommentableItem', 'comments', array( Config::inst()->update('CommentableItem', 'comments', array(
'nested_comments' => true, 'nested_comments' => true,
'nested_depth' => 4 'nested_depth' => 4
@ -1175,34 +1237,39 @@ class CommentsTest extends FunctionalTest {
$this->assertEquals(4, $reply3->Depth); $this->assertEquals(4, $reply3->Depth);
} }
public function testGetToken() { public function testGetToken()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
public function testMemberSalt() { public function testMemberSalt()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
public function testAddToUrl() { public function testAddToUrl()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
public function testCheckRequest() { public function testCheckRequest()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
public function testGenerate() { public function testGenerate()
{
$this->markTestSkipped('TODO'); $this->markTestSkipped('TODO');
} }
protected static function getMethod($name) { protected static function getMethod($name)
{
$class = new ReflectionClass('Comment'); $class = new ReflectionClass('Comment');
$method = $class->getMethod($name); $method = $class->getMethod($name);
$method->setAccessible(true); $method->setAccessible(true);
return $method; return $method;
} }
} }
@ -1210,7 +1277,8 @@ class CommentsTest extends FunctionalTest {
* @package comments * @package comments
* @subpackage tests * @subpackage tests
*/ */
class CommentableItem extends DataObject implements TestOnly { class CommentableItem extends DataObject implements TestOnly
{
private static $db = array( private static $db = array(
'Title' => 'Varchar' 'Title' => 'Varchar'
@ -1220,34 +1288,46 @@ class CommentableItem extends DataObject implements TestOnly {
'CommentsExtension' 'CommentsExtension'
); );
public function RelativeLink() { public function RelativeLink()
{
return "CommentableItem_Controller"; return "CommentableItem_Controller";
} }
public function canView($member = null) { public function canView($member = null)
{
return true; return true;
} }
// This is needed for canModerateComments // This is needed for canModerateComments
public function canEdit($member = null) { public function canEdit($member = null)
if($member instanceof Member) $memberID = $member->ID; {
else if(is_numeric($member)) $memberID = $member; if ($member instanceof Member) {
else $memberID = Member::currentUserID(); $memberID = $member->ID;
} elseif (is_numeric($member)) {
$memberID = $member;
} else {
$memberID = Member::currentUserID();
}
if($memberID && Permission::checkMember($memberID, array("ADMIN", "CMS_ACCESS_CommentAdmin"))) return true; if ($memberID && Permission::checkMember($memberID, array("ADMIN", "CMS_ACCESS_CommentAdmin"))) {
return true;
}
return false; return false;
} }
public function Link() { public function Link()
{
return $this->RelativeLink(); return $this->RelativeLink();
} }
public function AbsoluteLink() { public function AbsoluteLink()
{
return Director::absoluteURL($this->RelativeLink()); return Director::absoluteURL($this->RelativeLink());
} }
} }
class CommentableItemEnabled extends CommentableItem { class CommentableItemEnabled extends CommentableItem
{
private static $defaults = array( private static $defaults = array(
'ProvideComments' => true, 'ProvideComments' => true,
'ModerationRequired' => 'Required', 'ModerationRequired' => 'Required',
@ -1256,7 +1336,8 @@ class CommentableItemEnabled extends CommentableItem {
} }
class CommentableItemDisabled extends CommentableItem { class CommentableItemDisabled extends CommentableItem
{
private static $defaults = array( private static $defaults = array(
'ProvideComments' => false, 'ProvideComments' => false,
'ModerationRequired' => 'None', 'ModerationRequired' => 'None',
@ -1268,9 +1349,11 @@ class CommentableItemDisabled extends CommentableItem {
* @package comments * @package comments
* @subpackage tests * @subpackage tests
*/ */
class CommentableItem_Controller extends Controller implements TestOnly { class CommentableItem_Controller extends Controller implements TestOnly
{
public function index() { public function index()
{
return CommentableItem::get()->first()->CommentsForm(); return CommentableItem::get()->first()->CommentsForm();
} }
} }