Completed
Pull Request — master (#421)
by Robbie
13:34
created

BlogPost::canPublish()   D

Complexity

Conditions 9
Paths 7

Size

Total Lines 32
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 32
rs 4.909
c 0
b 0
f 0
cc 9
eloc 16
nc 7
nop 1
1
<?php
2
3
namespace SilverStripe\Blog\Model;
4
5
use Page;
6
use SilverStripe\Assets\Image;
7
use SilverStripe\Blog\Forms\BlogAdminSidebar;
8
use SilverStripe\Blog\Model\BlogCategory;
9
use SilverStripe\Blog\Model\BlogPostFilter;
10
use SilverStripe\Blog\Model\BlogTag;
11
use SilverStripe\Control\Controller;
12
use SilverStripe\Forms\DatetimeField;
13
use SilverStripe\Forms\HiddenField;
14
use SilverStripe\Forms\HTMLEditor\HTMLEditorField;
15
use SilverStripe\Forms\ListboxField;
16
use SilverStripe\Forms\TextField;
17
use SilverStripe\Forms\ToggleCompositeField;
18
use SilverStripe\Forms\UploadField;
19
use SilverStripe\ORM\ArrayList;
20
use SilverStripe\ORM\FieldType\DBDatetime;
21
use SilverStripe\ORM\UnsavedRelationList;
22
use SilverStripe\Security\Group;
23
use SilverStripe\Security\Member;
24
use SilverStripe\Security\Permission;
25
use SilverStripe\TagField\TagField;
26
use SilverStripe\View\ArrayData;
27
use SilverStripe\View\Requirements;
28
29
/**
30
 * An individual blog post.
31
 *
32
 * @package silverstripe
33
 * @subpackage blog
34
 *
35
 * @method ManyManyList Categories()
36
 * @method ManyManyList Tags()
37
 * @method ManyManyList Authors()
38
 * @method Blog Parent()
39
 *
40
 * @property string $PublishDate
41
 * @property string $AuthorNames
42
 * @property int $ParentID
43
 */
44
class BlogPost extends Page
45
{
46
    /**
47
     * Same as above, but for list of users that can be
48
     * given credit in the author field for blog posts
49
     * @var string|bool false or group code
50
     */
51
    private static $restrict_authors_to_group = false;
0 ignored issues
show
Unused Code introduced by
The property $restrict_authors_to_group 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...
52
53
    /**
54
     * {@inheritDoc}
55
     * @var string
56
     */
57
    private static $table_name = 'BlogPost';
0 ignored issues
show
Unused Code introduced by
The property $table_name 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...
58
59
    /**
60
     * @var array
61
     */
62
    private static $db = array(
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...
63
        'PublishDate' => 'Datetime',
64
        'AuthorNames' => 'Varchar(1024)',
65
        'Summary'     => 'HTMLText'
66
    );
67
68
    /**
69
     * @var array
70
     */
71
    private static $has_one = array(
0 ignored issues
show
Unused Code introduced by
The property $has_one 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...
72
        'FeaturedImage' => Image::class
73
    );
74
75
    /**
76
     * @var array
77
     */
78
    private static $many_many = array(
0 ignored issues
show
Unused Code introduced by
The property $many_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...
79
        'Categories' => BlogCategory::class,
80
        'Tags'       => BlogTag::class,
81
        'Authors'    => Member::class
82
    );
83
84
    /**
85
     * @var array
86
     */
87
    private static $defaults = array(
0 ignored issues
show
Unused Code introduced by
The property $defaults 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...
88
        'ShowInMenus'     => false,
89
        'InheritSideBar'  => true,
90
        'ProvideComments' => true
91
    );
92
93
    /**
94
     * @var array
95
     */
96
    private static $extensions = array(
0 ignored issues
show
Unused Code introduced by
The property $extensions 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
        BlogPostFilter::class
98
    );
99
100
    /**
101
     * @var array
102
     */
103
    private static $searchable_fields = array(
0 ignored issues
show
Unused Code introduced by
The property $searchable_fields 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...
104
        'Title'
105
    );
106
107
    /**
108
     * @var array
109
     */
110
    private static $summary_fields = array(
0 ignored issues
show
Unused Code introduced by
The property $summary_fields 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...
111
        'Title'
112
    );
113
114
    /**
115
     * @var array
116
     */
117
    private static $casting = array(
0 ignored issues
show
Unused Code introduced by
The property $casting 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...
118
        'Excerpt' => 'HTMLText',
119
        'Date' => 'DBDatetime'
120
    );
121
122
    /**
123
     * @var array
124
     */
125
    private static $allowed_children = array();
0 ignored issues
show
Unused Code introduced by
The property $allowed_children 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...
126
127
    /**
128
     * The default sorting lists BlogPosts with an empty PublishDate at the top.
129
     *
130
     * @var string
131
     */
132
    private static $default_sort = '"PublishDate" IS NULL DESC, "PublishDate" DESC';
0 ignored issues
show
Unused Code introduced by
The property $default_sort 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...
133
134
    /**
135
     * @var bool
136
     */
137
    private static $can_be_root = false;
0 ignored issues
show
Unused Code introduced by
The property $can_be_root 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...
138
139
    /**
140
     * This will display or hide the current class from the SiteTree. This variable can be
141
     * configured using YAML.
142
     *
143
     * @var bool
144
     */
145
    private static $show_in_sitetree = false;
0 ignored issues
show
Unused Code introduced by
The property $show_in_sitetree 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...
146
147
    /**
148
     * Determine the role of the given member.
149
     *
150
     * Call be called via template to determine the current user.
151
     *
152
     * @example "Hello $RoleOf($CurrentMember.ID)"
153
     *
154
     * @param null|int|Member $member
155
     *
156
     * @return null|string
157
     */
158
    public function RoleOf($member = null)
159
    {
160
        $member = $this->getMember($member);
161
162
        if (!$member) {
163
            return null;
164
        }
165
166
        if ($this->isAuthor($member)) {
167
            return _t('BlogPost.AUTHOR', 'Author');
168
        }
169
170
        $parent = $this->Parent();
171
172
        if ($parent instanceof Blog) {
173
            return $parent->RoleOf($member);
174
        }
175
176
        return null;
177
    }
178
179
    /**
180
     * Determine if the given member is an author of this post.
181
     *
182
     * @param null|Member $member
183
     *
184
     * @return bool
185
     */
186 View Code Duplication
    public function isAuthor($member = null)
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...
187
    {
188
        if (!$member || !$member->exists()) {
189
            return false;
190
        }
191
192
        $list = $this->Authors();
193
194
        if ($list instanceof UnsavedRelationList) {
195
            return in_array($member->ID, $list->getIDList());
196
        }
197
198
        return $list->byID($member->ID) !== null;
199
    }
200
201
    /**
202
     * {@inheritdoc}
203
     */
204
    public function getCMSFields()
205
    {
206
        Requirements::css(BLOGGER_DIR . '/css/cms.css');
207
        Requirements::javascript(BLOGGER_DIR . '/js/cms.js');
208
209
        $this->beforeUpdateCMSFields(function ($fields) {
210
            $uploadField = UploadField::create('FeaturedImage', _t('BlogPost.FeaturedImage', 'Featured Image'));
211
            $uploadField->getValidator()->setAllowedExtensions(array('jpg', 'jpeg', 'png', 'gif'));
212
213
            /**
214
             * @var FieldList $fields
215
             */
216
            $fields->insertAfter($uploadField, 'Content');
217
218
            $summary = HtmlEditorField::create('Summary', false);
219
            $summary->setRows(5);
220
            $summary->setDescription(_t(
221
                'BlogPost.SUMMARY_DESCRIPTION',
222
                'If no summary is specified the first 30 words will be used.'
223
            ));
224
225
            $summaryHolder = ToggleCompositeField::create(
226
                'CustomSummary',
227
                _t('BlogPost.CUSTOMSUMMARY', 'Add A Custom Summary'),
228
                array(
229
                    $summary,
230
                )
231
            );
232
            $summaryHolder->setHeadingLevel(4);
233
            $summaryHolder->addExtraClass('custom-summary');
234
235
            $fields->insertAfter($summaryHolder, 'FeaturedImage');
236
237
            $urlSegment = $fields->dataFieldByName('URLSegment');
238
            $urlSegment->setURLPrefix($this->Parent()->RelativeLink());
239
240
            $fields->removeFieldsFromTab('Root.Main', array(
241
                'MenuTitle',
242
                'URLSegment',
243
            ));
244
245
            $authorField = ListboxField::create(
246
                'Authors',
247
                _t('BlogPost.Authors', 'Authors'),
248
                $this->getCandidateAuthors()->map()->toArray()
249
            );
250
251
            $authorNames = TextField::create(
252
                'AuthorNames',
253
                _t('BlogPost.AdditionalCredits', 'Additional Credits'),
254
                null,
255
                1024
256
            )->setDescription(
257
                _t(
258
                    'BlogPost.AdditionalCredits_Description',
259
                    'If some authors of this post don\'t have CMS access, enter their name(s) here. You can separate multiple names with a comma.'
260
                )
261
            );
262
263
            if (!$this->canEditAuthors()) {
264
                $authorField = $authorField->performDisabledTransformation();
265
                $authorNames = $authorNames->performDisabledTransformation();
266
            }
267
268
            $publishDate = DatetimeField::create('PublishDate', _t('BlogPost.PublishDate', 'Publish Date'));
269
            $publishDate->getDateField()->setConfig('showcalendar', true);
270
            if (!$this->PublishDate) {
271
                $publishDate->setDescription(
272
                    _t(
273
                        'BlogPost.PublishDate_Description',
274
                        'Will be set to "now" if published without a value.'
275
                    )
276
                );
277
            }
278
279
            // Get categories and tags
280
            $parent = $this->Parent();
281
            $categories = $parent instanceof Blog
282
                ? $parent->Categories()
283
                : BlogCategory::get();
284
            $tags = $parent instanceof Blog
285
                ? $parent->Tags()
286
                : BlogTag::get();
287
288
            // @todo: Reimplement the sidebar
289
            // $options = BlogAdminSidebar::create(
290
            $fields->addFieldsToTab(
291
                'Root.PostOptions',
292
                [
293
                    $publishDate,
294
                    $urlSegment,
295
                    TagField::create(
296
                        'Categories',
297
                        _t('BlogPost.Categories', 'Categories'),
298
                        $categories,
299
                        $this->Categories()
300
                    )
301
                        ->setCanCreate($this->canCreateCategories())
302
                        ->setShouldLazyLoad(true),
303
                    TagField::create(
304
                        'Tags',
305
                        _t('BlogPost.Tags', 'Tags'),
306
                        $tags,
307
                        $this->Tags()
308
                    )
309
                        ->setCanCreate($this->canCreateTags())
310
                        ->setShouldLazyLoad(true),
311
                    $authorField,
312
                    $authorNames
313
                ]
314
            );
315
            // )->setTitle('Post Options');
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
316
            // $options->setName('blog-admin-sidebar');
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
317
            // $fields->insertBefore($options, 'Root');
0 ignored issues
show
Unused Code Comprehensibility introduced by
73% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
318
        });
319
320
        $fields = parent::getCMSFields();
321
322
        $fields->fieldByName('Root')->setTemplate('TabSet_holder');
323
324
        return $fields;
325
    }
326
327
    /**
328
     * Gets the list of author candidates to be assigned as authors of this blog post.
329
     *
330
     * @return SS_List
331
     */
332
    public function getCandidateAuthors()
333
    {
334
        if ($this->config()->restrict_authors_to_group) {
335
            return Group::get()->filter('Code', $this->config()->restrict_authors_to_group)->first()->Members();
336
        }
337
338
        $list = Member::get();
339
        $this->extend('updateCandidateAuthors', $list);
340
        return $list;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $list; (SilverStripe\ORM\DataList) is incompatible with the return type documented by SilverStripe\Blog\Model\...st::getCandidateAuthors of type SilverStripe\Blog\Model\SS_List.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
341
    }
342
343
    /**
344
     * Determine if this user can edit the authors list.
345
     *
346
     * @param null|int|Member $member
347
     *
348
     * @return bool
349
     */
350
    public function canEditAuthors($member = null)
351
    {
352
        $member = $this->getMember($member);
353
354
        $extended = $this->extendedCan('canEditAuthors', $member);
355
356
        if ($extended !== null) {
357
            return $extended;
358
        }
359
360
        $parent = $this->Parent();
361
362
        if ($parent instanceof Blog && $parent->exists()) {
363
            if ($parent->isEditor($member)) {
364
                return true;
365
            }
366
367
            if ($parent->isWriter($member) && $this->isAuthor($member)) {
368
                return true;
369
            }
370
        }
371
372
        return Permission::checkMember($member, Blog::MANAGE_USERS);
0 ignored issues
show
Bug Compatibility introduced by
The expression \SilverStripe\Security\P...el\Blog::MANAGE_USERS); of type boolean|string adds the type string to the return on line 372 which is incompatible with the return type documented by SilverStripe\Blog\Model\BlogPost::canEditAuthors of type boolean.
Loading history...
373
    }
374
375
    /**
376
     * @param null|int|Member $member
377
     *
378
     * @return null|Member
379
     */
380 View Code Duplication
    protected function getMember($member = null)
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...
381
    {
382
        if (!$member) {
383
            $member = Member::currentUser();
384
        }
385
386
        if (is_numeric($member)) {
387
            $member = Member::get()->byID($member);
388
        }
389
390
        return $member;
391
    }
392
393
    /**
394
     * Determine whether user can create new categories.
395
     *
396
     * @param null|int|Member $member
397
     *
398
     * @return bool
399
     */
400 View Code Duplication
    public function canCreateCategories($member = null)
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...
401
    {
402
        $member = $this->getMember($member);
403
404
        $parent = $this->Parent();
405
406
        if (!$parent || !$parent->exists() || !($parent instanceof Blog)) {
407
            return false;
408
        }
409
410
        if ($parent->isEditor($member)) {
411
            return true;
412
        }
413
414
        return Permission::checkMember($member, 'ADMIN');
415
    }
416
417
    /**
418
     * Determine whether user can create new tags.
419
     *
420
     * @param null|int|Member $member
421
     *
422
     * @return bool
423
     */
424 View Code Duplication
    public function canCreateTags($member = null)
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...
425
    {
426
        $member = $this->getMember($member);
427
428
        $parent = $this->Parent();
429
430
        if (!$parent || !$parent->exists() || !($parent instanceof Blog)) {
431
            return false;
432
        }
433
434
        if ($parent->isEditor($member)) {
435
            return true;
436
        }
437
438
        if ($parent->isWriter($member)) {
439
            return true;
440
        }
441
442
        return Permission::checkMember($member, 'ADMIN');
443
    }
444
445
    /**
446
     * {@inheritdoc}
447
     *
448
     * Update the PublishDate to now if the BlogPost would otherwise be published without a date.
449
     */
450
    public function onBeforePublish()
451
    {
452
        /**
453
         * @var DBDatetime $publishDate
454
         */
455
        $publishDate = $this->dbObject('PublishDate');
456
457
        if (!$publishDate->getValue()) {
458
            $this->PublishDate = DBDatetime::now()->getValue();
459
            $this->write();
460
        }
461
    }
462
463
    /**
464
     * {@inheritdoc}
465
     *
466
     * Sets blog relationship on all categories and tags assigned to this post.
467
     */
468
    public function onAfterWrite()
469
    {
470
        parent::onAfterWrite();
471
472
        foreach ($this->Categories() as $category) {
473
            /**
474
             * @var BlogCategory $category
475
             */
476
            $category->BlogID = $this->ParentID;
477
            $category->write();
478
        }
479
480
        foreach ($this->Tags() as $tag) {
481
            /**
482
             * @var BlogTag $tag
483
             */
484
            $tag->BlogID = $this->ParentID;
485
            $tag->write();
486
        }
487
    }
488
489
    /**
490
     * {@inheritdoc}
491
     */
492
    public function canView($member = null)
493
    {
494
        $member = $this->getMember($member);
495
496
        if (!parent::canView($member)) {
497
            return false;
498
        }
499
500
        if ($this->canEdit($member)) {
501
            return true;
502
        }
503
504
        /**
505
         * @var DBDatetime $publishDate
506
         */
507
        $publishDate = $this->dbObject('PublishDate');
508
        if (!$publishDate->exists()) {
509
            return false;
510
        }
511
512
        return !$publishDate->InFuture();
513
    }
514
515
    /**
516
     * {@inheritdoc}
517
     */
518
    public function canPublish($member = null)
519
    {
520
        $member = $this->getMember($member);
521
522
        if (Permission::checkMember($member, 'ADMIN')) {
523
            return true;
524
        }
525
526
        $extended = $this->extendedCan('canPublish', $member);
527
528
        if ($extended !== null) {
529
            return $extended;
530
        }
531
532
        $parent = $this->Parent();
533
534
        if ($parent instanceof Blog && $parent->exists()) {
535
            if ($parent->isEditor($member)) {
536
                return true;
537
            }
538
539
            if ($parent->isWriter($member) && $this->isAuthor($member)) {
540
                return true;
541
            }
542
543
            if ($parent->isContributor($member)) {
544
                return parent::canEdit($member);
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (canEdit() instead of canPublish()). Are you sure this is correct? If so, you might want to change this to $this->canEdit().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
545
            }
546
        }
547
548
        return $this->canEdit($member);
549
    }
550
551
    /**
552
     * {@inheritdoc}
553
     */
554
    public function canEdit($member = null)
555
    {
556
        $member = $this->getMember($member);
557
558
        if (parent::canEdit($member)) {
559
            return true;
560
        }
561
562
        $parent = $this->Parent();
563
564
        if (!$parent || !$parent->exists() || !($parent instanceof Blog)) {
565
            return false;
566
        }
567
568
        if ($parent->isEditor($member)) {
569
            return true;
570
        }
571
572
        if (!$parent->isWriter($member) && !$parent->isContributor($member)) {
573
            return false;
574
        }
575
576
        return $this->isAuthor($member);
577
    }
578
579
    /**
580
     * Returns the post excerpt.
581
     *
582
     * @param int $wordsToDisplay
583
     *
584
     * @return string
585
     */
586
    public function Excerpt($wordsToDisplay = 30)
587
    {
588
        /** @var HTMLText $content */
589
        $content = $this->dbObject('Content');
590
591
        return $content->Summary($wordsToDisplay);
592
    }
593
594
    /**
595
     * Returns a monthly archive link for the current blog post.
596
     *
597
     * @param string $type
598
     *
599
     * @return string
600
     */
601
    public function getMonthlyArchiveLink($type = 'day')
602
    {
603
        /**
604
         * @var DBDatetime $date
605
         */
606
        $date = $this->dbObject('PublishDate');
607
608
        if ($type != 'year') {
609
            if ($type == 'day') {
610
                return Controller::join_links(
611
                    $this->Parent()->Link('archive'),
612
                    $date->format('Y'),
613
                    $date->format('m'),
614
                    $date->format('d')
615
                );
616
            }
617
618
            return Controller::join_links($this->Parent()->Link('archive'), $date->format('Y'), $date->format('m'));
619
        }
620
621
        return Controller::join_links($this->Parent()->Link('archive'), $date->format('Y'));
622
    }
623
624
    /**
625
     * Returns a yearly archive link for the current blog post.
626
     *
627
     * @return string
628
     */
629
    public function getYearlyArchiveLink()
630
    {
631
        /**
632
         * @var DBDatetime $date
633
         */
634
        $date = $this->dbObject('PublishDate');
635
636
        return Controller::join_links($this->Parent()->Link('archive'), $date->format('Y'));
637
    }
638
639
    /**
640
     * Resolves static and dynamic authors linked to this post.
641
     *
642
     * @return ArrayList
643
     */
644
    public function getCredits()
645
    {
646
        $list = ArrayList::create();
647
648
        $list->merge($this->getDynamicCredits());
649
        $list->merge($this->getStaticCredits());
650
651
        return $list->sort('Name');
652
    }
653
654
    /**
655
     * Resolves dynamic authors linked to this post.
656
     *
657
     * @return ArrayList
658
     */
659
    protected function getDynamicCredits()
660
    {
661
        // Find best page to host user profiles
662
        $parent = $this->Parent();
663
        if (! ($parent instanceof Blog)) {
664
            $parent = Blog::get()->first();
665
        }
666
667
        // If there is no parent blog, return list undecorated
668
        if (!$parent) {
669
            $items = $this->Authors()->toArray();
670
            return new ArrayList($items);
671
        }
672
673
        // Update all authors
674
        $items = new ArrayList();
675
        foreach ($this->Authors() as $author) {
676
            // Add link for each author
677
            $author = $author->customise(array(
678
                'URL' => $parent->ProfileLink($author->URLSegment),
679
            ));
680
            $items->push($author);
681
        }
682
683
        return $items;
684
    }
685
686
    /**
687
     * Resolves static authors linked to this post.
688
     *
689
     * @return ArrayList
690
     */
691
    protected function getStaticCredits()
692
    {
693
        $items = new ArrayList();
694
695
        $authors = array_filter(preg_split('/\s*,\s*/', $this->AuthorNames));
696
697
        foreach ($authors as $author) {
698
            $item = new ArrayData(array(
699
                'Name' => $author,
700
            ));
701
702
            $items->push($item);
703
        }
704
705
        return $items;
706
    }
707
708
    /**
709
     * Sets the label for BlogPost.Title to 'Post Title' (Rather than 'Page name').
710
     *
711
     * @param bool $includeRelations
712
     *
713
     * @return array
714
     */
715
    public function fieldLabels($includeRelations = true)
716
    {
717
        $labels = parent::fieldLabels($includeRelations);
718
719
        $labels['Title'] = _t('BlogPost.PageTitleLabel', 'Post Title');
720
721
        return $labels;
722
    }
723
724
    /**
725
     * Proxy method for displaying the publish date in rss feeds.
726
     * @see https://github.com/silverstripe/silverstripe-blog/issues/394
727
     *
728
     * @return string|null
729
     */
730
    public function getDate()
731
    {
732
        return !empty($this->PublishDate) ? $this->PublishDate : null;
733
    }
734
735
    /**
736
     * {@inheritdoc}
737
     */
738
    protected function onBeforeWrite()
739
    {
740
        parent::onBeforeWrite();
741
742
        if (!$this->exists() && ($member = Member::currentUser())) {
743
            $this->Authors()->add($member);
744
        }
745
    }
746
}
747