Completed
Push — master ( 187618...8c43e0 )
by Will
12s
created

CommentsExtension::getCommentsOptions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 12
rs 9.4285
cc 2
eloc 7
nc 2
nop 0
1
<?php
2
3
namespace SilverStripe\Comments\Extensions;
4
5
use SilverStripe\Comments\Admin\CommentsGridField;
6
use SilverStripe\Comments\Admin\CommentsGridFieldConfig;
7
use SilverStripe\Comments\Controllers\CommentingController;
8
use SilverStripe\Comments\Model\Comment;
9
use SilverStripe\Control\Controller;
10
use SilverStripe\Control\Director;
11
use SilverStripe\Control\Session;
12
use SilverStripe\Core\Config\Config;
13
use SilverStripe\Core\Manifest\ModuleLoader;
14
use SilverStripe\Dev\Deprecation;
15
use SilverStripe\Forms\CheckboxField;
16
use SilverStripe\Forms\DropdownField;
17
use SilverStripe\Forms\FieldGroup;
18
use SilverStripe\Forms\FieldList;
19
use SilverStripe\Forms\Tab;
20
use SilverStripe\Forms\TabSet;
21
use SilverStripe\ORM\DataExtension;
22
use SilverStripe\ORM\PaginatedList;
23
use SilverStripe\Security\Member;
24
use SilverStripe\Security\Permission;
25
use SilverStripe\View\Requirements;
26
27
/**
28
 * Extension to {@link DataObject} to enable tracking comments.
29
 *
30
 * @package comments
31
 */
32
class CommentsExtension extends DataExtension
33
{
34
    /**
35
     * Default configuration values
36
     *
37
     * enabled:                     Allows commenting to be disabled even if the extension is present
38
     * enabled_cms:                 Allows commenting to be enabled or disabled via the CMS
39
     * require_login:               Boolean, whether a user needs to login (required for required_permission)
40
     * require_login_cms:           Allows require_login to be set via the CMS
41
     * required_permission:         Permission (or array of permissions) required to comment
42
     * include_js:                  Enhance operation by ajax behaviour on moderation links (required for use_preview)
43
     * use_gravatar:                Set to true to show gravatar icons
44
     * gravatar_default:            Theme for 'not found' gravatar {@see http://gravatar.com/site/implement/images}
45
     * gravatar_rating:             Gravatar rating (same as the standard default)
46
     * show_comments_when_disabled: Show older comments when commenting has been disabled.
47
     * order_comments_by:           Default sort order.
48
     * order_replies_by:            Sort order for replies.
49
     * comments_holder_id:          ID for the comments holder
50
     * comment_permalink_prefix:    ID prefix for each comment
51
     * require_moderation:          Require moderation for all comments
52
     * require_moderation_cms:      Ignore other comment moderation config settings and set via CMS
53
     * frontend_moderation:         Display unmoderated comments in the frontend, if the user can moderate them.
54
     * frontend_spam:               Display spam comments in the frontend, if the user can moderate them.
55
     * html_allowed:                Allow for sanitized HTML in comments
56
     * use_preview:                 Preview formatted comment (when allowing HTML)
57
     * nested_comments:             Enable nested comments
58
     * nested_depth:                Max depth of nested comments in levels (where root is 1 depth) 0 means no limit.
59
     *
60
     * @var array
61
     *
62
     * @config
63
     */
64
    private static $comments = [
0 ignored issues
show
Unused Code introduced by
The property $comments is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
65
        'enabled' => true,
66
        'enabled_cms' => false,
67
        'require_login' => false,
68
        'require_login_cms' => false,
69
        'required_permission' => false,
70
        'include_js' => true,
71
        'use_gravatar' => false,
72
        'gravatar_size' => 80,
73
        'gravatar_default' => 'identicon',
74
        'gravatar_rating' => 'g',
75
        'show_comments_when_disabled' => false,
76
        'order_comments_by' => '"Created" DESC',
77
        'order_replies_by' => false,
78
        'comments_per_page' => 10,
79
        'comments_holder_id' => 'comments-holder',
80
        'comment_permalink_prefix' => 'comment-',
81
        'require_moderation' => false,
82
        'require_moderation_nonmembers' => false,
83
        'require_moderation_cms' => false,
84
        'frontend_moderation' => false,
85
        'frontend_spam' => false,
86
        'html_allowed' => false,
87
        'html_allowed_elements' => ['a', 'img', 'i', 'b'],
88
        'use_preview' => false,
89
        'nested_comments' => false,
90
        'nested_depth' => 2,
91
    ];
92
93
    /**
94
     * @var array
95
     */
96
    private static $db = [
0 ignored issues
show
Unused Code introduced by
The property $db is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
97
        'ProvideComments' => 'Boolean',
98
        'ModerationRequired' => 'Enum(\'None,Required,NonMembersOnly\',\'None\')',
99
        'CommentsRequireLogin' => 'Boolean',
100
    ];
101
102
    /**
103
     * {@inheritDoc}
104
     */
105
    private static $has_many = [
0 ignored issues
show
Unused Code introduced by
The property $has_many is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
106
        'Commments' => Comment::class . '.Parent'
107
    ];
108
109
    /**
110
     * CMS configurable options should default to the config values, but respect
111
     * default values specified by the object
112
     */
113
    public function populateDefaults()
114
    {
115
        $defaults = $this->owner->config()->get('defaults');
116
117
        // Set if comments should be enabled by default
118 View Code Duplication
        if (isset($defaults['ProvideComments'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
119
            $this->owner->ProvideComments = $defaults['ProvideComments'];
120
        } else {
121
            $this->owner->ProvideComments = $this->owner->getCommentsOption('enabled') ? 1 : 0;
122
        }
123
124
        // If moderation options should be configurable via the CMS then
125
        if (isset($defaults['ModerationRequired'])) {
126
            $this->owner->ModerationRequired = $defaults['ModerationRequired'];
127
        } elseif ($this->owner->getCommentsOption('require_moderation')) {
128
            $this->owner->ModerationRequired = 'Required';
129
        } elseif ($this->owner->getCommentsOption('require_moderation_nonmembers')) {
130
            $this->owner->ModerationRequired = 'NonMembersOnly';
131
        } else {
132
            $this->owner->ModerationRequired = 'None';
133
        }
134
135
        // Set login required
136 View Code Duplication
        if (isset($defaults['CommentsRequireLogin'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
137
            $this->owner->CommentsRequireLogin = $defaults['CommentsRequireLogin'];
138
        } else {
139
            $this->owner->CommentsRequireLogin = $this->owner->getCommentsOption('require_login') ? 1 : 0;
140
        }
141
    }
142
143
144
    /**
145
     * If this extension is applied to a {@link SiteTree} record then
146
     * append a Provide Comments checkbox to allow authors to trigger
147
     * whether or not to display comments
148
     *
149
     * @todo Allow customization of other {@link Commenting} configuration
150
     *
151
     * @param FieldList $fields
152
     */
153
    public function updateSettingsFields(FieldList $fields)
154
    {
155
        $options = FieldGroup::create()->setTitle(_t('SilverStripe\\Comments\\Extensions\\CommentsExtension.COMMENTOPTIONS', 'Comments'));
156
157
        // Check if enabled setting should be cms configurable
158
        if ($this->owner->getCommentsOption('enabled_cms')) {
159
            $options->push(new CheckboxField('ProvideComments', _t('SilverStripe\\Comments\\Model\\Comment.ALLOWCOMMENTS', 'Allow Comments')));
160
        }
161
162
        // Check if we should require users to login to comment
163
        if ($this->owner->getCommentsOption('require_login_cms')) {
164
            $options->push(
165
                new CheckboxField(
166
                    'CommentsRequireLogin',
167
                    _t('Comments.COMMENTSREQUIRELOGIN', 'Require login to comment')
168
                )
169
            );
170
        }
171
172
        if ($options->FieldList()->count()) {
173
            if ($fields->hasTabSet()) {
174
                $fields->addFieldsToTab('Root.Settings', $options);
0 ignored issues
show
Documentation introduced by
$options is of type object<SilverStripe\Forms\FieldGroup>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
175
            } else {
176
                $fields->push($options);
177
            }
178
        }
179
180
        // Check if moderation should be enabled via cms configurable
181
        if ($this->owner->getCommentsOption('require_moderation_cms')) {
182
            $moderationField = new DropdownField('ModerationRequired', _t('SilverStripe\\Comments\\Extensions\\CommentsExtension.COMMENTMODERATION', 'Comment Moderation'), array(
183
                'None' => _t('SilverStripe\\Comments\\Extensions\\CommentsExtension.MODERATIONREQUIRED_NONE', 'No moderation required'),
184
                'Required' => _t('SilverStripe\\Comments\\Extensions\\CommentsExtension.MODERATIONREQUIRED_REQUIRED', 'Moderate all comments'),
185
                'NonMembersOnly' => _t(
186
                    'SilverStripe\\Comments\\Extensions\\CommentsExtension.MODERATIONREQUIRED_NONMEMBERSONLY',
187
                    'Only moderate non-members'
188
                ),
189
            ));
190
            if ($fields->hasTabSet()) {
191
                $fields->addFieldsToTab('Root.Settings', $moderationField);
0 ignored issues
show
Documentation introduced by
$moderationField is of type object<SilverStripe\Forms\DropdownField>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
192
            } else {
193
                $fields->push($moderationField);
194
            }
195
        }
196
    }
197
198
    /**
199
     * Get comment moderation rules for this parent
200
     *
201
     * None:           No moderation required
202
     * Required:       All comments
203
     * NonMembersOnly: Only anonymous users
204
     *
205
     * @return string
206
     */
207
    public function getModerationRequired()
208
    {
209
        if ($this->owner->getCommentsOption('require_moderation_cms')) {
210
            return $this->owner->getField('ModerationRequired');
211
        } elseif ($this->owner->getCommentsOption('require_moderation')) {
212
            return 'Required';
213
        } elseif ($this->owner->getCommentsOption('require_moderation_nonmembers')) {
214
            return 'NonMembersOnly';
215
        } else {
216
            return 'None';
217
        }
218
    }
219
220
    /**
221
     * Determine if users must be logged in to post comments
222
     *
223
     * @return boolean
224
     */
225
    public function getCommentsRequireLogin()
226
    {
227
        if ($this->owner->getCommentsOption('require_login_cms')) {
228
            return (bool) $this->owner->getField('CommentsRequireLogin');
229
        } else {
230
            return (bool) $this->owner->getCommentsOption('require_login');
231
        }
232
    }
233
234
    /**
235
     * Returns the RelationList of all comments against this object. Can be used as a data source
236
     * for a gridfield with write access.
237
     *
238
     * @return DataList
239
     */
240 View Code Duplication
    public function AllComments()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
241
    {
242
        $order = $this->owner->getCommentsOption('order_comments_by');
243
        $comments = Comment::get()
244
            ->filter('ParentID', $this->owner->ID)
245
            ->sort($order);
246
        $this->owner->extend('updateAllComments', $comments);
247
        return $comments;
248
    }
249
250
    /**
251
     * Returns all comments against this object, with with spam and unmoderated items excluded, for use in the frontend
252
     *
253
     * @return DataList
254
     */
255
    public function AllVisibleComments()
256
    {
257
        $list = $this->AllComments();
258
259
        // Filter spam comments for non-administrators if configured
260
        $showSpam = $this->owner->getCommentsOption('frontend_spam') && $this->owner->canModerateComments();
261
262
        if (!$showSpam) {
263
            $list = $list->filter('IsSpam', 0);
264
        }
265
266
        // Filter un-moderated comments for non-administrators if moderation is enabled
267
        $showUnmoderated = ($this->owner->ModerationRequired === 'None')
268
            || ($this->owner->getCommentsOption('frontend_moderation') && $this->owner->canModerateComments());
269
        if (!$showUnmoderated) {
270
            $list = $list->filter('Moderated', 1);
271
        }
272
273
        $this->owner->extend('updateAllVisibleComments', $list);
274
        return $list;
275
    }
276
277
    /**
278
     * Returns the root level comments, with spam and unmoderated items excluded, for use in the frontend
279
     *
280
     * @return DataList
281
     */
282 View Code Duplication
    public function Comments()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
283
    {
284
        $list = $this->AllVisibleComments();
285
286
        // If nesting comments, only show root level
287
        if ($this->owner->getCommentsOption('nested_comments')) {
288
            $list = $list->filter('ParentCommentID', 0);
289
        }
290
291
        $this->owner->extend('updateComments', $list);
292
        return $list;
293
    }
294
295
    /**
296
     * Returns a paged list of the root level comments, with spam and unmoderated items excluded,
297
     * for use in the frontend
298
     *
299
     * @return PaginatedList
300
     */
301 View Code Duplication
    public function PagedComments()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
302
    {
303
        $list = $this->Comments();
304
305
        // Add pagination
306
        $list = new PaginatedList($list, Controller::curr()->getRequest());
0 ignored issues
show
Documentation introduced by
\SilverStripe\Control\Co...r::curr()->getRequest() is of type object<SilverStripe\Control\HTTPRequest>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
307
        $list->setPaginationGetVar('commentsstart' . $this->owner->ID);
308
        $list->setPageLength($this->owner->getCommentsOption('comments_per_page'));
309
310
        $this->owner->extend('updatePagedComments', $list);
311
        return $list;
312
    }
313
314
    /**
315
     * Determine if comments are enabled for this instance
316
     *
317
     * @return boolean
318
     */
319
    public function getCommentsEnabled()
320
    {
321
        // Don't display comments form for pseudo-pages (such as the login form)
322
        if (!$this->owner->exists()) {
323
            return false;
324
        }
325
326
        // Determine which flag should be used to determine if this is enabled
327
        if ($this->owner->getCommentsOption('enabled_cms')) {
328
            return (bool) $this->owner->ProvideComments;
329
        }
330
331
        return (bool) $this->owner->getCommentsOption('enabled');
332
    }
333
334
    /**
335
     * Get the HTML ID for the comment holder in the template
336
     *
337
     * @return string
338
     */
339
    public function getCommentHolderID()
340
    {
341
        return $this->owner->getCommentsOption('comments_holder_id');
342
    }
343
344
    /**
345
     * Permission codes required in order to post (or empty if none required)
346
     *
347
     * @return string|array Permission or list of permissions, if required
348
     */
349
    public function getPostingRequiredPermission()
350
    {
351
        return $this->owner->getCommentsOption('required_permission');
352
    }
353
354
    /**
355
     * Determine if a user can post comments on this item
356
     *
357
     * @param Member $member Member to check
0 ignored issues
show
Documentation introduced by
Should the type for parameter $member not be Member|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
358
     *
359
     * @return boolean
360
     */
361
    public function canPostComment($member = null)
362
    {
363
        // Deny if not enabled for this object
364
        if (!$this->owner->CommentsEnabled) {
365
            return false;
366
        }
367
368
        if (!$this->owner->canView($member)) {
369
            // deny if current user cannot view the underlying record.
370
            return false;
371
        }
372
373
        // Check if member is required
374
        $requireLogin = $this->owner->CommentsRequireLogin;
375
        if (!$requireLogin) {
376
            return true;
377
        }
378
379
        // Check member is logged in
380
        $member = $member ?: Member::currentUser();
0 ignored issues
show
Deprecated Code introduced by
The method SilverStripe\Security\Member::currentUser() has been deprecated with message: 5.0.0 use Security::getCurrentUser()

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
381
        if (!$member) {
382
            return false;
383
        }
384
385
        // If member required check permissions
386
        $requiredPermission = $this->owner->PostingRequiredPermission;
387
        if ($requiredPermission && !Permission::checkMember($member, $requiredPermission)) {
0 ignored issues
show
Unused Code introduced by
This if statement, and the following return statement can be replaced with return !($requiredPermis... $requiredPermission));.
Loading history...
388
            return false;
389
        }
390
391
        return true;
392
    }
393
394
    /**
395
     * Determine if this member can moderate comments in the CMS
396
     *
397
     * @param Member $member
0 ignored issues
show
Documentation introduced by
Should the type for parameter $member not be Member|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
398
     *
399
     * @return boolean
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
400
     */
401
    public function canModerateComments($member = null)
402
    {
403
        // Deny if not enabled for this object
404
        if (!$this->owner->CommentsEnabled) {
405
            return false;
406
        }
407
408
        // Fallback to can-edit
409
        return $this->owner->canEdit($member);
410
    }
411
412
    /**
413
     * Gets the RSS link to all comments
414
     *
415
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|false?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
416
     */
417
    public function getCommentRSSLink()
418
    {
419
        return Director::absoluteURL('comments/rss');
420
    }
421
422
    /**
423
     * Get the RSS link to all comments on this page
424
     *
425
     * @return string
426
     */
427
    public function getCommentRSSLinkPage()
428
    {
429
        return Controller::join_links(
430
            $this->getCommentRSSLink(),
431
            str_replace('\\', '-', $this->owner->baseClass()),
432
            $this->owner->ID
433
        );
434
    }
435
436
    /**
437
     * Comments interface for the front end. Includes the CommentAddForm and the composition
438
     * of the comments display.
439
     *
440
     * To customize the html see templates/CommentInterface.ss or extend this function with
441
     * your own extension.
442
     *
443
     * @todo Cleanup the passing of all this configuration based functionality
444
     *
445
     * @see  docs/en/Extending
446
     */
447
    public function CommentsForm()
448
    {
449
        // Check if enabled
450
        $enabled = $this->getCommentsEnabled();
451
        if ($enabled && $this->owner->getCommentsOption('include_js')) {
452
            $adminThirdPartyDir = ModuleLoader::getModule('silverstripe/admin')->getRelativePath() . '/thirdparty';
453
            Requirements::javascript($adminThirdPartyDir . '/jquery/jquery.js');
454
            Requirements::javascript($adminThirdPartyDir . '/jquery-entwine/dist/jquery.entwine-dist.js');
455
            Requirements::javascript($adminThirdPartyDir . '/jquery-form/jquery.form.js');
456
            Requirements::javascript('silverstripe/comments:thirdparty/jquery-validate/jquery.validate.min.js');
457
            Requirements::add_i18n_javascript('silverstripe/comments:javascript/lang');
458
            Requirements::javascript('silverstripe/comments:javascript/CommentsInterface.js');
459
        }
460
461
        $controller = CommentingController::create();
462
        $controller->setOwnerRecord($this->owner);
463
        $controller->setParentClass($this->owner->getClassName());
464
        $controller->setOwnerController(Controller::curr());
465
466
        $session = Controller::curr()->getRequest()->getSession();
467
        $moderatedSubmitted = $session->get('CommentsModerated');
468
        $session->clear('CommentsModerated');
469
470
        $form = ($enabled) ? $controller->CommentsForm() : false;
471
472
        // a little bit all over the show but to ensure a slightly easier upgrade for users
473
        // return back the same variables as previously done in comments
474
        return $this
475
            ->owner
476
            ->customise(array(
477
                'AddCommentForm' => $form,
478
                'ModeratedSubmitted' => $moderatedSubmitted,
479
            ))
480
            ->renderWith('CommentsInterface');
481
    }
482
483
    /**
484
     * Returns whether this extension instance is attached to a {@link SiteTree} object
485
     *
486
     * @return bool
487
     */
488
    public function attachedToSiteTree()
489
    {
490
        $class = $this->owner->baseClass();
491
492
        return (is_subclass_of($class, SiteTree::class)) || ($class == SiteTree::class);
493
    }
494
495
    /**
496
     * Get the commenting option for this object.
497
     *
498
     * This can be overridden in any instance or extension to customise the
499
     * option available.
500
     *
501
     * @param string $key
502
     *
503
     * @return mixed Result if the setting is available, or null otherwise
504
     */
505
    public function getCommentsOption($key)
506
    {
507
        $settings = $this->getCommentsOptions();
508
        $value = null;
509
510
        if (isset($settings[$key])) {
511
            $value = $settings[$key];
512
        }
513
514
        // To allow other extensions to customise this option
515
        if ($this->owner) {
516
            $this->owner->extend('updateCommentsOption', $key, $value);
517
        }
518
519
        return $value;
520
    }
521
522
    /**
523
     * @return array
524
     */
525
    public function getCommentsOptions()
526
    {
527
        $settings = [];
0 ignored issues
show
Unused Code introduced by
$settings is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
528
529
        if ($this->owner) {
530
            $settings = $this->owner->config()->get('comments');
531
        } else {
532
            $settings = Config::inst()->get(__CLASS__, 'comments');
533
        }
534
535
        return $settings;
536
    }
537
538
    /**
539
     * Add moderation functions to the current fieldlist
540
     *
541
     * @param FieldList $fields
542
     */
543
    protected function updateModerationFields(FieldList $fields)
544
    {
545
        Requirements::css('silverstripe/comments:css/cms.css');
546
547
        $newComments = $this->owner->AllComments()->filter('Moderated', 0);
548
549
        $newGrid = new CommentsGridField(
550
            'NewComments',
551
            _t('CommentsAdmin.NewComments', 'New'),
552
            $newComments,
553
            CommentsGridFieldConfig::create()
554
        );
555
556
        $approvedComments = $this->owner->AllComments()->filter('Moderated', 1)->filter('IsSpam', 0);
557
558
        $approvedGrid = new CommentsGridField(
559
            'ApprovedComments',
560
            _t('CommentsAdmin.Comments', 'Approved'),
561
            $approvedComments,
562
            CommentsGridFieldConfig::create()
563
        );
564
565
        $spamComments = $this->owner->AllComments()->filter('Moderated', 1)->filter('IsSpam', 1);
566
567
        $spamGrid = new CommentsGridField(
568
            'SpamComments',
569
            _t('CommentsAdmin.SpamComments', 'Spam'),
570
            $spamComments,
571
            CommentsGridFieldConfig::create()
572
        );
573
574
        $newCount = '(' . count($newComments) . ')';
575
        $approvedCount = '(' . count($approvedComments) . ')';
576
        $spamCount = '(' . count($spamComments) . ')';
577
578
        if ($fields->hasTabSet()) {
579
            $tabs = new TabSet(
580
                'Comments',
581
                new Tab(
582
                    'CommentsNewCommentsTab',
583
                    _t('SilverStripe\\Comments\\Admin\\CommentAdmin.NewComments', 'New') . ' ' . $newCount,
584
                    $newGrid
585
                ),
586
                new Tab(
587
                    'CommentsCommentsTab',
588
                    _t('SilverStripe\\Comments\\Admin\\CommentAdmin.Comments', 'Approved') . ' ' . $approvedCount,
589
                    $approvedGrid
590
                ),
591
                new Tab(
592
                    'CommentsSpamCommentsTab',
593
                    _t('SilverStripe\\Comments\\Admin\\CommentAdmin.SpamComments', 'Spam') . ' ' . $spamCount,
594
                    $spamGrid
595
                )
596
            );
597
            $fields->addFieldToTab('Root', $tabs);
598
        } else {
599
            $fields->push($newGrid);
600
            $fields->push($approvedGrid);
601
            $fields->push($spamGrid);
602
        }
603
    }
604
605
    public function updateCMSFields(FieldList $fields)
606
    {
607
        // Disable moderation if not permitted
608
        if ($this->owner->canModerateComments()) {
609
            $this->updateModerationFields($fields);
610
        }
611
612
        // If this isn't a page we should merge the settings into the CMS fields
613
        if (!$this->attachedToSiteTree()) {
614
            $this->updateSettingsFields($fields);
615
        }
616
    }
617
}
618