Completed
Push — master ( 225113...29bb49 )
by Damian
02:11
created

SiteTree::getSettingsFields()   D

Complexity

Conditions 10
Paths 120

Size

Total Lines 137
Code Lines 90

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 137
rs 4.606
c 0
b 0
f 0
cc 10
eloc 90
nc 120
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace SilverStripe\CMS\Model;
4
5
use Page;
6
use SilverStripe\CampaignAdmin\AddToCampaignHandler_FormAction;
7
use SilverStripe\CMS\Controllers\CMSPageEditController;
8
use SilverStripe\CMS\Controllers\ContentController;
9
use SilverStripe\CMS\Controllers\ModelAsController;
10
use SilverStripe\CMS\Controllers\RootURLController;
11
use SilverStripe\CMS\Forms\SiteTreeURLSegmentField;
12
use SilverStripe\Control\ContentNegotiator;
13
use SilverStripe\Control\Controller;
14
use SilverStripe\Control\Director;
15
use SilverStripe\Control\RequestHandler;
16
use SilverStripe\Core\ClassInfo;
17
use SilverStripe\Core\Config\Config;
18
use SilverStripe\Core\Convert;
19
use SilverStripe\Core\Injector\Injector;
20
use SilverStripe\Core\Resettable;
21
use SilverStripe\Dev\Deprecation;
22
use SilverStripe\Forms\CheckboxField;
23
use SilverStripe\Forms\CompositeField;
24
use SilverStripe\Forms\DropdownField;
25
use SilverStripe\Forms\FieldGroup;
26
use SilverStripe\Forms\FieldList;
27
use SilverStripe\Forms\FormAction;
28
use SilverStripe\Forms\GridField\GridField;
29
use SilverStripe\Forms\GridField\GridFieldDataColumns;
30
use SilverStripe\Forms\HTMLEditor\HTMLEditorField;
31
use SilverStripe\Forms\ListboxField;
32
use SilverStripe\Forms\LiteralField;
33
use SilverStripe\Forms\OptionsetField;
34
use SilverStripe\Forms\Tab;
35
use SilverStripe\Forms\TabSet;
36
use SilverStripe\Forms\TextareaField;
37
use SilverStripe\Forms\TextField;
38
use SilverStripe\Forms\ToggleCompositeField;
39
use SilverStripe\Forms\TreeDropdownField;
40
use SilverStripe\i18n\i18n;
41
use SilverStripe\i18n\i18nEntityProvider;
42
use SilverStripe\ORM\ArrayList;
43
use SilverStripe\ORM\CMSPreviewable;
44
use SilverStripe\ORM\DataList;
45
use SilverStripe\ORM\DataObject;
46
use SilverStripe\ORM\DB;
47
use SilverStripe\ORM\HiddenClass;
48
use SilverStripe\ORM\Hierarchy\Hierarchy;
49
use SilverStripe\ORM\ManyManyList;
50
use SilverStripe\ORM\ValidationResult;
51
use SilverStripe\Security\Group;
52
use SilverStripe\Security\InheritedPermissions;
53
use SilverStripe\Security\InheritedPermissionsExtension;
54
use SilverStripe\Security\Member;
55
use SilverStripe\Security\Permission;
56
use SilverStripe\Security\PermissionChecker;
57
use SilverStripe\Security\PermissionProvider;
58
use SilverStripe\Security\Security;
59
use SilverStripe\SiteConfig\SiteConfig;
60
use SilverStripe\Versioned\Versioned;
61
use SilverStripe\View\ArrayData;
62
use SilverStripe\View\HTML;
63
use SilverStripe\View\Parsers\ShortcodeParser;
64
use SilverStripe\View\Parsers\URLSegmentFilter;
65
use SilverStripe\View\SSViewer;
66
use Subsite;
67
68
/**
69
 * Basic data-object representing all pages within the site tree. All page types that live within the hierarchy should
70
 * inherit from this. In addition, it contains a number of static methods for querying the site tree and working with
71
 * draft and published states.
72
 *
73
 * <h2>URLs</h2>
74
 * A page is identified during request handling via its "URLSegment" database column. As pages can be nested, the full
75
 * path of a URL might contain multiple segments. Each segment is stored in its filtered representation (through
76
 * {@link URLSegmentFilter}). The full path is constructed via {@link Link()}, {@link RelativeLink()} and
77
 * {@link AbsoluteLink()}. You can allow these segments to contain multibyte characters through
78
 * {@link URLSegmentFilter::$default_allow_multibyte}.
79
 *
80
 * @property string URLSegment
81
 * @property string Title
82
 * @property string MenuTitle
83
 * @property string Content HTML content of the page.
84
 * @property string MetaDescription
85
 * @property string ExtraMeta
86
 * @property string ShowInMenus
87
 * @property string ShowInSearch
88
 * @property string Sort Integer value denoting the sort order.
89
 * @property string ReportClass
90
 *
91
 * @method ManyManyList ViewerGroups() List of groups that can view this object.
92
 * @method ManyManyList EditorGroups() List of groups that can edit this object.
93
 * @method SiteTree Parent()
94
 *
95
 * @mixin Hierarchy
96
 * @mixin Versioned
97
 * @mixin SiteTreeLinkTracking
98
 * @mixin InheritedPermissionsExtension
99
 */
100
class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvider, CMSPreviewable, Resettable
101
{
102
103
    /**
104
     * Indicates what kind of children this page type can have.
105
     * This can be an array of allowed child classes, or the string "none" -
106
     * indicating that this page type can't have children.
107
     * If a classname is prefixed by "*", such as "*Page", then only that
108
     * class is allowed - no subclasses. Otherwise, the class and all its
109
     * subclasses are allowed.
110
     * To control allowed children on root level (no parent), use {@link $can_be_root}.
111
     *
112
     * Note that this setting is cached when used in the CMS, use the "flush" query parameter to clear it.
113
     *
114
     * @config
115
     * @var array
116
     */
117
    private static $allowed_children = [
118
        self::class
119
    ];
120
121
    /**
122
     * The default child class for this page.
123
     * Note: Value might be cached, see {@link $allowed_chilren}.
124
     *
125
     * @config
126
     * @var string
127
     */
128
    private static $default_child = "Page";
129
130
    /**
131
     * Default value for SiteTree.ClassName enum
132
     * {@see DBClassName::getDefault}
133
     *
134
     * @config
135
     * @var string
136
     */
137
    private static $default_classname = "Page";
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
138
139
    /**
140
     * The default parent class for this page.
141
     * Note: Value might be cached, see {@link $allowed_chilren}.
142
     *
143
     * @config
144
     * @var string
145
     */
146
    private static $default_parent = null;
147
148
    /**
149
     * Controls whether a page can be in the root of the site tree.
150
     * Note: Value might be cached, see {@link $allowed_chilren}.
151
     *
152
     * @config
153
     * @var bool
154
     */
155
    private static $can_be_root = true;
156
157
    /**
158
     * List of permission codes a user can have to allow a user to create a page of this type.
159
     * Note: Value might be cached, see {@link $allowed_chilren}.
160
     *
161
     * @config
162
     * @var array
163
     */
164
    private static $need_permission = null;
165
166
    /**
167
     * If you extend a class, and don't want to be able to select the old class
168
     * in the cms, set this to the old class name. Eg, if you extended Product
169
     * to make ImprovedProduct, then you would set $hide_ancestor to Product.
170
     *
171
     * @config
172
     * @var string
173
     */
174
    private static $hide_ancestor = null;
175
176
    private static $db = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
177
        "URLSegment" => "Varchar(255)",
178
        "Title" => "Varchar(255)",
179
        "MenuTitle" => "Varchar(100)",
180
        "Content" => "HTMLText",
181
        "MetaDescription" => "Text",
182
        "ExtraMeta" => "HTMLFragment(['whitelist' => ['meta', 'link']])",
183
        "ShowInMenus" => "Boolean",
184
        "ShowInSearch" => "Boolean",
185
        "Sort" => "Int",
186
        "HasBrokenFile" => "Boolean",
187
        "HasBrokenLink" => "Boolean",
188
        "ReportClass" => "Varchar",
189
    );
190
191
    private static $indexes = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
192
        "URLSegment" => true,
193
    );
194
195
    private static $has_many = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
196
        "VirtualPages" => "SilverStripe\\CMS\\Model\\VirtualPage.CopyContentFrom"
197
    );
198
199
    private static $owned_by = array(
200
        "VirtualPages"
201
    );
202
203
    private static $casting = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
204
        "Breadcrumbs" => "HTMLFragment",
205
        "LastEdited" => "Datetime",
206
        "Created" => "Datetime",
207
        'Link' => 'Text',
208
        'RelativeLink' => 'Text',
209
        'AbsoluteLink' => 'Text',
210
        'CMSEditLink' => 'Text',
211
        'TreeTitle' => 'HTMLFragment',
212
        'MetaTags' => 'HTMLFragment',
213
    );
214
215
    private static $defaults = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
216
        "ShowInMenus" => 1,
217
        "ShowInSearch" => 1,
218
    );
219
220
    private static $table_name = 'SiteTree';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
221
222
    private static $versioning = array(
223
        "Stage",  "Live"
224
    );
225
226
    private static $default_sort = "\"Sort\"";
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
227
228
    /**
229
     * If this is false, the class cannot be created in the CMS by regular content authors, only by ADMINs.
230
     * @var boolean
231
     * @config
232
     */
233
    private static $can_create = true;
234
235
    /**
236
     * Icon to use in the CMS page tree. This should be the full filename, relative to the webroot.
237
     * Also supports custom CSS rule contents (applied to the correct selector for the tree UI implementation).
238
     *
239
     * @see CMSMain::generateTreeStylingCSS()
240
     * @config
241
     * @var string
242
     */
243
    private static $icon = null;
244
245
    private static $extensions = [
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
246
        Hierarchy::class,
247
        Versioned::class,
248
        SiteTreeLinkTracking::class,
249
        InheritedPermissionsExtension::class,
250
    ];
251
252
    private static $searchable_fields = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
253
        'Title',
254
        'Content',
255
    );
256
257
    private static $field_labels = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
258
        'URLSegment' => 'URL'
259
    );
260
261
    /**
262
     * @config
263
     */
264
    private static $nested_urls = true;
265
266
    /**
267
     * @config
268
    */
269
    private static $create_default_pages = true;
270
271
    /**
272
     * This controls whether of not extendCMSFields() is called by getCMSFields.
273
     */
274
    private static $runCMSFieldsExtensions = true;
275
276
    /**
277
     * @config
278
     * @var boolean
279
     */
280
    private static $enforce_strict_hierarchy = true;
281
282
    /**
283
     * The value used for the meta generator tag. Leave blank to omit the tag.
284
     *
285
     * @config
286
     * @var string
287
     */
288
    private static $meta_generator = 'SilverStripe - http://silverstripe.org';
289
290
    protected $_cache_statusFlags = null;
291
292
    /**
293
     * Plural form for SiteTree / Page classes. Not inherited by subclasses.
294
     *
295
     * @config
296
     * @var string
297
     */
298
    private static $base_plural_name = 'Pages';
299
300
    /**
301
     * Plural form for SiteTree / Page classes. Not inherited by subclasses.
302
     *
303
     * @config
304
     * @var string
305
     */
306
    private static $base_singular_name = 'Page';
307
308
    /**
309
     * Description of the class functionality, typically shown to a user
310
     * when selecting which page type to create. Translated through {@link provideI18nEntities()}.
311
     *
312
     * @see SiteTree::classDescription()
313
     * @see SiteTree::i18n_classDescription()
314
     *
315
     * @config
316
     * @var string
317
     */
318
    private static $description = null;
319
320
    /**
321
     * Description for Page and SiteTree classes, but not inherited by subclasses.
322
     * override SiteTree::$description in subclasses instead.
323
     *
324
     * @see SiteTree::classDescription()
325
     * @see SiteTree::i18n_classDescription()
326
     *
327
     * @config
328
     * @var string
329
     */
330
    private static $base_description = 'Generic content page';
331
332
    /**
333
     * Fetches the {@link SiteTree} object that maps to a link.
334
     *
335
     * If you have enabled {@link SiteTree::config()->nested_urls} on this site, then you can use a nested link such as
336
     * "about-us/staff/", and this function will traverse down the URL chain and grab the appropriate link.
337
     *
338
     * Note that if no model can be found, this method will fall over to a extended alternateGetByLink method provided
339
     * by a extension attached to {@link SiteTree}
340
     *
341
     * @param string $link  The link of the page to search for
342
     * @param bool   $cache True (default) to use caching, false to force a fresh search from the database
343
     * @return SiteTree
344
     */
345
    public static function get_by_link($link, $cache = true)
346
    {
347
        if (trim($link, '/')) {
348
            $link = trim(Director::makeRelative($link), '/');
349
        } else {
350
            $link = RootURLController::get_homepage_link();
351
        }
352
353
        $parts = preg_split('|/+|', $link);
354
355
        // Grab the initial root level page to traverse down from.
356
        $URLSegment = array_shift($parts);
357
        $conditions = array('"SiteTree"."URLSegment"' => rawurlencode($URLSegment));
358
        if (self::config()->nested_urls) {
359
            $conditions[] = array('"SiteTree"."ParentID"' => 0);
360
        }
361
        /** @var SiteTree $sitetree */
362
        $sitetree = DataObject::get_one(self::class, $conditions, $cache);
363
364
        /// Fall back on a unique URLSegment for b/c.
365
        if (!$sitetree
366
            && self::config()->nested_urls
367
            && $sitetree = DataObject::get_one(self::class, array(
368
                '"SiteTree"."URLSegment"' => $URLSegment
369
            ), $cache)
370
        ) {
371
            return $sitetree;
372
        }
373
374
        // Attempt to grab an alternative page from extensions.
375
        if (!$sitetree) {
376
            $parentID = self::config()->nested_urls ? 0 : null;
377
378 View Code Duplication
            if ($alternatives = static::singleton()->extend('alternateGetByLink', $URLSegment, $parentID)) {
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...
379
                foreach ($alternatives as $alternative) {
380
                    if ($alternative) {
381
                        $sitetree = $alternative;
382
                    }
383
                }
384
            }
385
386
            if (!$sitetree) {
387
                return null;
388
            }
389
        }
390
391
        // Check if we have any more URL parts to parse.
392
        if (!self::config()->nested_urls || !count($parts)) {
393
            return $sitetree;
394
        }
395
396
        // Traverse down the remaining URL segments and grab the relevant SiteTree objects.
397
        foreach ($parts as $segment) {
398
            $next = DataObject::get_one(
399
                self::class,
400
                array(
401
                    '"SiteTree"."URLSegment"' => $segment,
402
                    '"SiteTree"."ParentID"' => $sitetree->ID
403
                ),
404
                $cache
405
            );
406
407
            if (!$next) {
408
                $parentID = (int) $sitetree->ID;
409
410 View Code Duplication
                if ($alternatives = static::singleton()->extend('alternateGetByLink', $segment, $parentID)) {
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...
411
                    foreach ($alternatives as $alternative) {
412
                        if ($alternative) {
413
                            $next = $alternative;
414
                        }
415
                    }
416
                }
417
418
                if (!$next) {
419
                    return null;
420
                }
421
            }
422
423
            $sitetree->destroy();
424
            $sitetree = $next;
425
        }
426
427
        return $sitetree;
428
    }
429
430
    /**
431
     * Return a subclass map of SiteTree that shouldn't be hidden through {@link SiteTree::$hide_ancestor}
432
     *
433
     * @return array
434
     */
435
    public static function page_type_classes()
436
    {
437
        $classes = ClassInfo::getValidSubClasses();
438
439
        $baseClassIndex = array_search(self::class, $classes);
440
        if ($baseClassIndex !== false) {
441
            unset($classes[$baseClassIndex]);
442
        }
443
444
        $kill_ancestors = array();
445
446
        // figure out if there are any classes we don't want to appear
447
        foreach ($classes as $class) {
448
            $instance = singleton($class);
449
450
            // do any of the progeny want to hide an ancestor?
451
            if ($ancestor_to_hide = $instance->stat('hide_ancestor')) {
452
                // note for killing later
453
                $kill_ancestors[] = $ancestor_to_hide;
454
            }
455
        }
456
457
        // If any of the descendents don't want any of the elders to show up, cruelly render the elders surplus to
458
        // requirements
459
        if ($kill_ancestors) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $kill_ancestors of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
460
            $kill_ancestors = array_unique($kill_ancestors);
461
            foreach ($kill_ancestors as $mark) {
462
                // unset from $classes
463
                $idx = array_search($mark, $classes, true);
464
                if ($idx !== false) {
465
                    unset($classes[$idx]);
466
                }
467
            }
468
        }
469
470
        return $classes;
471
    }
472
473
    /**
474
     * Replace a "[sitetree_link id=n]" shortcode with a link to the page with the corresponding ID.
475
     *
476
     * @param array      $arguments
477
     * @param string     $content
478
     * @param ShortcodeParser $parser
479
     * @return string
480
     */
481
    public static function link_shortcode_handler($arguments, $content = null, $parser = null)
482
    {
483
        if (!isset($arguments['id']) || !is_numeric($arguments['id'])) {
484
            return null;
485
        }
486
487
        /** @var SiteTree $page */
488
        if (!($page = DataObject::get_by_id(self::class, $arguments['id']))         // Get the current page by ID.
489
            && !($page = Versioned::get_latest_version(self::class, $arguments['id'])) // Attempt link to old version.
490
        ) {
491
             return null; // There were no suitable matches at all.
492
        }
493
494
        /** @var SiteTree $page */
495
        $link = Convert::raw2att($page->Link());
496
497
        if ($content) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $content of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
498
            return sprintf('<a href="%s">%s</a>', $link, $parser->parse($content));
0 ignored issues
show
Bug introduced by
It seems like $parser is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
499
        } else {
500
            return $link;
501
        }
502
    }
503
504
    /**
505
     * Return the link for this {@link SiteTree} object, with the {@link Director::baseURL()} included.
506
     *
507
     * @param string $action Optional controller action (method).
508
     *                       Note: URI encoding of this parameter is applied automatically through template casting,
509
     *                       don't encode the passed parameter. Please use {@link Controller::join_links()} instead to
510
     *                       append GET parameters.
511
     * @return string
512
     */
513
    public function Link($action = null)
514
    {
515
        return Controller::join_links(Director::baseURL(), $this->RelativeLink($action));
516
    }
517
518
    /**
519
     * Get the absolute URL for this page, including protocol and host.
520
     *
521
     * @param string $action See {@link Link()}
522
     * @return string
523
     */
524
    public function AbsoluteLink($action = null)
525
    {
526
        if ($this->hasMethod('alternateAbsoluteLink')) {
527
            return $this->alternateAbsoluteLink($action);
0 ignored issues
show
Bug introduced by
The method alternateAbsoluteLink() does not exist on SilverStripe\CMS\Model\SiteTree. Did you maybe mean AbsoluteLink()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
528
        } else {
529
            return Director::absoluteURL($this->Link($action));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression \SilverStripe\Control\Di...($this->Link($action)); of type string|false adds false to the return on line 529 which is incompatible with the return type documented by SilverStripe\CMS\Model\SiteTree::AbsoluteLink of type string. It seems like you forgot to handle an error condition.
Loading history...
530
        }
531
    }
532
533
    /**
534
     * Base link used for previewing. Defaults to absolute URL, in order to account for domain changes, e.g. on multi
535
     * site setups. Does not contain hints about the stage, see {@link SilverStripeNavigator} for details.
536
     *
537
     * @param string $action See {@link Link()}
538
     * @return string
539
     */
540
    public function PreviewLink($action = null)
541
    {
542
        if ($this->hasMethod('alternatePreviewLink')) {
543
            Deprecation::notice('5.0', 'Use updatePreviewLink or override PreviewLink method');
544
            return $this->alternatePreviewLink($action);
0 ignored issues
show
Bug introduced by
The method alternatePreviewLink() does not exist on SilverStripe\CMS\Model\SiteTree. Did you maybe mean PreviewLink()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
545
        }
546
547
        $link = $this->AbsoluteLink($action);
548
        $this->extend('updatePreviewLink', $link, $action);
549
        return $link;
550
    }
551
552
    public function getMimeType()
553
    {
554
        return 'text/html';
555
    }
556
557
    /**
558
     * Return the link for this {@link SiteTree} object relative to the SilverStripe root.
559
     *
560
     * By default, if this page is the current home page, and there is no action specified then this will return a link
561
     * to the root of the site. However, if you set the $action parameter to TRUE then the link will not be rewritten
562
     * and returned in its full form.
563
     *
564
     * @uses RootURLController::get_homepage_link()
565
     *
566
     * @param string $action See {@link Link()}
567
     * @return string
568
     */
569
    public function RelativeLink($action = null)
570
    {
571
        if ($this->ParentID && self::config()->nested_urls) {
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
572
            $parent = $this->Parent();
573
            // If page is removed select parent from version history (for archive page view)
574
            if ((!$parent || !$parent->exists()) && !$this->isOnDraft()) {
0 ignored issues
show
Documentation Bug introduced by
The method isOnDraft does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
575
                $parent = Versioned::get_latest_version(self::class, $this->ParentID);
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
576
            }
577
            $base = $parent->RelativeLink($this->URLSegment);
578
        } elseif (!$action && $this->URLSegment == RootURLController::get_homepage_link()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $action of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
579
            // Unset base for root-level homepages.
580
            // Note: Homepages with action parameters (or $action === true)
581
            // need to retain their URLSegment.
582
            $base = null;
583
        } else {
584
            $base = $this->URLSegment;
585
        }
586
587
        $this->extend('updateRelativeLink', $base, $action);
588
589
        // Legacy support: If $action === true, retain URLSegment for homepages,
590
        // but don't append any action
591
        if ($action === true) {
592
            $action = null;
593
        }
594
595
        return Controller::join_links($base, '/', $action);
596
    }
597
598
    /**
599
     * Get the absolute URL for this page on the Live site.
600
     *
601
     * @param bool $includeStageEqualsLive Whether to append the URL with ?stage=Live to force Live mode
602
     * @return string
603
     */
604
    public function getAbsoluteLiveLink($includeStageEqualsLive = true)
605
    {
606
        $oldReadingMode = Versioned::get_reading_mode();
607
        Versioned::set_stage(Versioned::LIVE);
608
        /** @var SiteTree $live */
609
        $live = Versioned::get_one_by_stage(self::class, Versioned::LIVE, array(
610
            '"SiteTree"."ID"' => $this->ID
611
        ));
612
        if ($live) {
613
            $link = $live->AbsoluteLink();
614
            if ($includeStageEqualsLive) {
615
                $link = Controller::join_links($link, '?stage=Live');
616
            }
617
        } else {
618
            $link = null;
619
        }
620
621
        Versioned::set_reading_mode($oldReadingMode);
622
        return $link;
623
    }
624
625
    /**
626
     * Generates a link to edit this page in the CMS.
627
     *
628
     * @return string
629
     */
630
    public function CMSEditLink()
631
    {
632
        $link = Controller::join_links(
633
            CMSPageEditController::singleton()->Link('show'),
634
            $this->ID
635
        );
636
        return Director::absoluteURL($link);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression \SilverStripe\Control\Di...or::absoluteURL($link); of type string|false adds false to the return on line 636 which is incompatible with the return type declared by the interface SilverStripe\ORM\CMSPreviewable::CMSEditLink of type string. It seems like you forgot to handle an error condition.
Loading history...
637
    }
638
639
640
    /**
641
     * Return a CSS identifier generated from this page's link.
642
     *
643
     * @return string The URL segment
644
     */
645
    public function ElementName()
646
    {
647
        return str_replace('/', '-', trim($this->RelativeLink(true), '/'));
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

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...
648
    }
649
650
    /**
651
     * Returns true if this is the currently active page being used to handle this request.
652
     *
653
     * @return bool
654
     */
655
    public function isCurrent()
656
    {
657
        $currentPage = Director::get_current_page();
658
        if ($currentPage instanceof ContentController) {
659
            $currentPage = $currentPage->data();
660
        }
661
        if ($currentPage instanceof SiteTree) {
662
            return $currentPage === $this || $currentPage->ID === $this->ID;
663
        }
664
        return false;
665
    }
666
667
    /**
668
     * Check if this page is in the currently active section (e.g. it is either current or one of its children is
669
     * currently being viewed).
670
     *
671
     * @return bool
672
     */
673
    public function isSection()
674
    {
675
        return $this->isCurrent() || (
676
            Director::get_current_page() instanceof SiteTree && in_array($this->ID, Director::get_current_page()->getAncestors()->column())
677
        );
678
    }
679
680
    /**
681
     * Check if the parent of this page has been removed (or made otherwise unavailable), and is still referenced by
682
     * this child. Any such orphaned page may still require access via the CMS, but should not be shown as accessible
683
     * to external users.
684
     *
685
     * @return bool
686
     */
687
    public function isOrphaned()
688
    {
689
        // Always false for root pages
690
        if (empty($this->ParentID)) {
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
691
            return false;
692
        }
693
694
        // Parent must exist and not be an orphan itself
695
        $parent = $this->Parent();
696
        return !$parent || !$parent->exists() || $parent->isOrphaned();
697
    }
698
699
    /**
700
     * Return "link" or "current" depending on if this is the {@link SiteTree::isCurrent()} current page.
701
     *
702
     * @return string
703
     */
704
    public function LinkOrCurrent()
705
    {
706
        return $this->isCurrent() ? 'current' : 'link';
707
    }
708
709
    /**
710
     * Return "link" or "section" depending on if this is the {@link SiteTree::isSeciton()} current section.
711
     *
712
     * @return string
713
     */
714
    public function LinkOrSection()
715
    {
716
        return $this->isSection() ? 'section' : 'link';
717
    }
718
719
    /**
720
     * Return "link", "current" or "section" depending on if this page is the current page, or not on the current page
721
     * but in the current section.
722
     *
723
     * @return string
724
     */
725
    public function LinkingMode()
726
    {
727
        if ($this->isCurrent()) {
728
            return 'current';
729
        } elseif ($this->isSection()) {
730
            return 'section';
731
        } else {
732
            return 'link';
733
        }
734
    }
735
736
    /**
737
     * Check if this page is in the given current section.
738
     *
739
     * @param string $sectionName Name of the section to check
740
     * @return bool True if we are in the given section
741
     */
742
    public function InSection($sectionName)
743
    {
744
        $page = Director::get_current_page();
745
        while ($page && $page->exists()) {
746
            if ($sectionName == $page->URLSegment) {
747
                return true;
748
            }
749
            $page = $page->Parent();
750
        }
751
        return false;
752
    }
753
754
    /**
755
     * Reset Sort on duped page
756
     *
757
     * @param SiteTree $original
758
     * @param bool $doWrite
759
     */
760
    public function onBeforeDuplicate($original, $doWrite)
0 ignored issues
show
Unused Code introduced by
The parameter $original is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $doWrite is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
761
    {
762
        $this->Sort = 0;
763
    }
764
765
    /**
766
     * Duplicates each child of this node recursively and returns the top-level duplicate node.
767
     *
768
     * @return static The duplicated object
769
     */
770
    public function duplicateWithChildren()
771
    {
772
        /** @var SiteTree $clone */
773
        $clone = $this->duplicate();
774
        $children = $this->AllChildren();
0 ignored issues
show
Documentation Bug introduced by
The method AllChildren does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
775
776
        if ($children) {
777
            /** @var SiteTree $child */
778
            $sort = 0;
779
            foreach ($children as $child) {
780
                $childClone = $child->duplicateWithChildren();
781
                $childClone->ParentID = $clone->ID;
782
                //retain sort order by manually setting sort values
783
                $childClone->Sort = ++$sort;
784
                $childClone->write();
785
            }
786
        }
787
788
        return $clone;
789
    }
790
791
    /**
792
     * Duplicate this node and its children as a child of the node with the given ID
793
     *
794
     * @param int $id ID of the new node's new parent
795
     */
796
    public function duplicateAsChild($id)
797
    {
798
        /** @var SiteTree $newSiteTree */
799
        $newSiteTree = $this->duplicate();
800
        $newSiteTree->ParentID = $id;
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
801
        $newSiteTree->Sort = 0;
802
        $newSiteTree->write();
803
    }
804
805
    /**
806
     * Return a breadcrumb trail to this page. Excludes "hidden" pages (with ShowInMenus=0) by default.
807
     *
808
     * @param int $maxDepth The maximum depth to traverse.
809
     * @param boolean $unlinked Whether to link page titles.
810
     * @param boolean|string $stopAtPageType ClassName of a page to stop the upwards traversal.
811
     * @param boolean $showHidden Include pages marked with the attribute ShowInMenus = 0
812
     * @return string The breadcrumb trail.
813
     */
814
    public function Breadcrumbs($maxDepth = 20, $unlinked = false, $stopAtPageType = false, $showHidden = false)
815
    {
816
        $pages = $this->getBreadcrumbItems($maxDepth, $stopAtPageType, $showHidden);
817
        $template = new SSViewer('BreadcrumbsTemplate');
818
        return $template->process($this->customise(new ArrayData(array(
819
            "Pages" => $pages,
820
            "Unlinked" => $unlinked
821
        ))));
822
    }
823
824
825
    /**
826
     * Returns a list of breadcrumbs for the current page.
827
     *
828
     * @param int $maxDepth The maximum depth to traverse.
829
     * @param boolean|string $stopAtPageType ClassName of a page to stop the upwards traversal.
830
     * @param boolean $showHidden Include pages marked with the attribute ShowInMenus = 0
831
     *
832
     * @return ArrayList
833
    */
834
    public function getBreadcrumbItems($maxDepth = 20, $stopAtPageType = false, $showHidden = false)
835
    {
836
        $page = $this;
837
        $pages = array();
838
839
        while ($page
840
            && $page->exists()
841
            && (!$maxDepth || count($pages) < $maxDepth)
842
            && (!$stopAtPageType || $page->ClassName != $stopAtPageType)
843
        ) {
844
            if ($showHidden || $page->ShowInMenus || ($page->ID == $this->ID)) {
845
                $pages[] = $page;
846
            }
847
848
            $page = $page->Parent();
849
        }
850
851
        return new ArrayList(array_reverse($pages));
852
    }
853
854
855
    /**
856
     * Make this page a child of another page.
857
     *
858
     * If the parent page does not exist, resolve it to a valid ID before updating this page's reference.
859
     *
860
     * @param SiteTree|int $item Either the parent object, or the parent ID
861
     */
862
    public function setParent($item)
863
    {
864
        if (is_object($item)) {
865
            if (!$item->exists()) {
866
                $item->write();
867
            }
868
            $this->setField("ParentID", $item->ID);
869
        } else {
870
            $this->setField("ParentID", $item);
871
        }
872
    }
873
874
    /**
875
     * Get the parent of this page.
876
     *
877
     * @return SiteTree Parent of this page
878
     */
879
    public function getParent()
880
    {
881
        if ($parentID = $this->getField("ParentID")) {
882
            return DataObject::get_by_id(self::class, $parentID);
883
        }
884
        return null;
885
    }
886
887
    /**
888
     * Return a string of the form "parent - page" or "grandparent - parent - page" using page titles
889
     *
890
     * @param int $level The maximum amount of levels to traverse.
891
     * @param string $separator Seperating string
892
     * @return string The resulting string
893
     */
894
    public function NestedTitle($level = 2, $separator = " - ")
895
    {
896
        $item = $this;
897
        $parts = [];
898
        while ($item && $level > 0) {
899
            $parts[] = $item->Title;
900
            $item = $item->getParent();
901
            $level--;
902
        }
903
        return implode($separator, array_reverse($parts));
904
    }
905
906
    /**
907
     * This function should return true if the current user can execute this action. It can be overloaded to customise
908
     * the security model for an application.
909
     *
910
     * Slightly altered from parent behaviour in {@link DataObject->can()}:
911
     * - Checks for existence of a method named "can<$perm>()" on the object
912
     * - Calls decorators and only returns for FALSE "vetoes"
913
     * - Falls back to {@link Permission::check()}
914
     * - Does NOT check for many-many relations named "Can<$perm>"
915
     *
916
     * @uses DataObjectDecorator->can()
917
     *
918
     * @param string $perm The permission to be checked, such as 'View'
919
     * @param Member $member The member whose permissions need checking. Defaults to the currently logged in user.
920
     * @param array $context Context argument for canCreate()
921
     * @return bool True if the the member is allowed to do the given action
922
     */
923
    public function can($perm, $member = null, $context = array())
924
    {
925
        if (!$member) {
926
            $member = Security::getCurrentUser();
927
        }
928
929
        if ($member && Permission::checkMember($member, "ADMIN")) {
930
            return true;
931
        }
932
933
        if (is_string($perm) && method_exists($this, 'can' . ucfirst($perm))) {
934
            $method = 'can' . ucfirst($perm);
935
            return $this->$method($member);
936
        }
937
938
        $results = $this->extend('can', $member);
939
        if ($results && is_array($results)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $results of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
940
            if (!min($results)) {
941
                return false;
942
            }
943
        }
944
945
        return ($member && Permission::checkMember($member, $perm));
946
    }
947
948
    /**
949
     * This function should return true if the current user can add children to this page. It can be overloaded to
950
     * customise the security model for an application.
951
     *
952
     * Denies permission if any of the following conditions is true:
953
     * - alternateCanAddChildren() on a extension returns false
954
     * - canEdit() is not granted
955
     * - There are no classes defined in {@link $allowed_children}
956
     *
957
     * @uses SiteTreeExtension->canAddChildren()
958
     * @uses canEdit()
959
     * @uses $allowed_children
960
     *
961
     * @param Member|int $member
962
     * @return bool True if the current user can add children
963
     */
964
    public function canAddChildren($member = null)
965
    {
966
        // Disable adding children to archived pages
967
        if (!$this->isOnDraft()) {
0 ignored issues
show
Documentation Bug introduced by
The method isOnDraft does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
968
            return false;
969
        }
970
971
        if (!$member) {
972
            $member = Security::getCurrentUser();
973
        }
974
975
        // Standard mechanism for accepting permission changes from extensions
976
        $extended = $this->extendedCan('canAddChildren', $member);
0 ignored issues
show
Bug introduced by
It seems like $member can also be of type null; however, SilverStripe\ORM\DataObject::extendedCan() does only seem to accept object<SilverStripe\Security\Member>|integer, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
977
        if ($extended !== null) {
978
            return $extended;
979
        }
980
981
        // Default permissions
982
        if ($member && Permission::checkMember($member, "ADMIN")) {
983
            return true;
984
        }
985
986
        return $this->canEdit($member) && $this->stat('allowed_children') !== 'none';
0 ignored issues
show
Bug introduced by
It seems like $member defined by parameter $member on line 964 can also be of type integer; however, SilverStripe\CMS\Model\SiteTree::canEdit() does only seem to accept object<SilverStripe\Security\Member>|null, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
987
    }
988
989
    /**
990
     * This function should return true if the current user can view this page. It can be overloaded to customise the
991
     * security model for an application.
992
     *
993
     * Denies permission if any of the following conditions is true:
994
     * - canView() on any extension returns false
995
     * - "CanViewType" directive is set to "Inherit" and any parent page return false for canView()
996
     * - "CanViewType" directive is set to "LoggedInUsers" and no user is logged in
997
     * - "CanViewType" directive is set to "OnlyTheseUsers" and user is not in the given groups
998
     *
999
     * @uses DataExtension->canView()
1000
     * @uses ViewerGroups()
1001
     *
1002
     * @param Member $member
1003
     * @return bool True if the current user can view this page
1004
     */
1005
    public function canView($member = null)
1006
    {
1007
        if (!$member) {
1008
            $member = Security::getCurrentUser();
1009
        }
1010
1011
        // Standard mechanism for accepting permission changes from extensions
1012
        $extended = $this->extendedCan('canView', $member);
0 ignored issues
show
Bug introduced by
It seems like $member can be null; however, extendedCan() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1013
        if ($extended !== null) {
1014
            return $extended;
1015
        }
1016
1017
        // admin override
1018
        if ($member && Permission::checkMember($member, array("ADMIN", "SITETREE_VIEW_ALL"))) {
1019
            return true;
1020
        }
1021
1022
        // Orphaned pages (in the current stage) are unavailable, except for admins via the CMS
1023
        if ($this->isOrphaned()) {
1024
            return false;
1025
        }
1026
1027
        // Note: getInheritedPermissions() is disused in this instance
1028
        // to allow parent canView extensions to influence subpage canView()
1029
1030
        // check for empty spec
1031
        if (!$this->CanViewType || $this->CanViewType === InheritedPermissions::ANYONE) {
0 ignored issues
show
Documentation introduced by
The property CanViewType does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1032
            return true;
1033
        }
1034
1035
        // check for inherit
1036
        if ($this->CanViewType === InheritedPermissions::INHERIT) {
0 ignored issues
show
Documentation introduced by
The property CanViewType does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1037
            if ($this->ParentID) {
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1038
                return $this->Parent()->canView($member);
1039
            } else {
1040
                return $this->getSiteConfig()->canViewPages($member);
1041
            }
1042
        }
1043
1044
        // check for any logged-in users
1045
        if ($this->CanViewType === InheritedPermissions::LOGGED_IN_USERS && $member && $member->ID) {
0 ignored issues
show
Documentation introduced by
The property CanViewType does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1046
            return true;
1047
        }
1048
1049
        // check for specific groups
1050
        if ($this->CanViewType === InheritedPermissions::ONLY_THESE_USERS
0 ignored issues
show
Documentation introduced by
The property CanViewType does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1051
            && $member
1052
            && $member->inGroups($this->ViewerGroups())
1053
        ) {
1054
            return true;
1055
        }
1056
1057
        return false;
1058
    }
1059
1060
    /**
1061
     * Check if this page can be published
1062
     *
1063
     * @param Member $member
1064
     * @return bool
1065
     */
1066 View Code Duplication
    public function canPublish($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...
1067
    {
1068
        if (!$member) {
1069
            $member = Security::getCurrentUser();
1070
        }
1071
1072
        // Check extension
1073
        $extended = $this->extendedCan('canPublish', $member);
0 ignored issues
show
Bug introduced by
It seems like $member can be null; however, extendedCan() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1074
        if ($extended !== null) {
1075
            return $extended;
1076
        }
1077
1078
        if (Permission::checkMember($member, "ADMIN")) {
1079
            return true;
1080
        }
1081
1082
        // Default to relying on edit permission
1083
        return $this->canEdit($member);
1084
    }
1085
1086
    /**
1087
     * This function should return true if the current user can delete this page. It can be overloaded to customise the
1088
     * security model for an application.
1089
     *
1090
     * Denies permission if any of the following conditions is true:
1091
     * - canDelete() returns false on any extension
1092
     * - canEdit() returns false
1093
     * - any descendant page returns false for canDelete()
1094
     *
1095
     * @uses canDelete()
1096
     * @uses SiteTreeExtension->canDelete()
1097
     * @uses canEdit()
1098
     *
1099
     * @param Member $member
1100
     * @return bool True if the current user can delete this page
1101
     */
1102
    public function canDelete($member = null)
1103
    {
1104
        if (!$member) {
1105
            $member = Security::getCurrentUser();
1106
        }
1107
1108
        // Standard mechanism for accepting permission changes from extensions
1109
        $extended = $this->extendedCan('canDelete', $member);
0 ignored issues
show
Bug introduced by
It seems like $member can be null; however, extendedCan() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1110
        if ($extended !== null) {
1111
            return $extended;
1112
        }
1113
1114
        if (!$member) {
1115
            return false;
1116
        }
1117
1118
        // Default permission check
1119
        if (Permission::checkMember($member, array("ADMIN", "SITETREE_EDIT_ALL"))) {
1120
            return true;
1121
        }
1122
1123
        // Check inherited permissions
1124
        return static::getPermissionChecker()
1125
            ->canDelete($this->ID, $member);
1126
    }
1127
1128
    /**
1129
     * This function should return true if the current user can create new pages of this class, regardless of class. It
1130
     * can be overloaded to customise the security model for an application.
1131
     *
1132
     * By default, permission to create at the root level is based on the SiteConfig configuration, and permission to
1133
     * create beneath a parent is based on the ability to edit that parent page.
1134
     *
1135
     * Use {@link canAddChildren()} to control behaviour of creating children under this page.
1136
     *
1137
     * @uses $can_create
1138
     * @uses DataExtension->canCreate()
1139
     *
1140
     * @param Member $member
1141
     * @param array $context Optional array which may contain array('Parent' => $parentObj)
1142
     *                       If a parent page is known, it will be checked for validity.
1143
     *                       If omitted, it will be assumed this is to be created as a top level page.
1144
     * @return bool True if the current user can create pages on this class.
1145
     */
1146
    public function canCreate($member = null, $context = array())
1147
    {
1148
        if (!$member) {
1149
            $member = Security::getCurrentUser();
1150
        }
1151
1152
        // Check parent (custom canCreate option for SiteTree)
1153
        // Block children not allowed for this parent type
1154
        $parent = isset($context['Parent']) ? $context['Parent'] : null;
1155
        if ($parent && !in_array(static::class, $parent->allowedChildren())) {
1156
            return false;
1157
        }
1158
1159
        // Standard mechanism for accepting permission changes from extensions
1160
        $extended = $this->extendedCan(__FUNCTION__, $member, $context);
0 ignored issues
show
Bug introduced by
It seems like $member can be null; however, extendedCan() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1161
        if ($extended !== null) {
1162
            return $extended;
1163
        }
1164
1165
        // Check permission
1166
        if ($member && Permission::checkMember($member, "ADMIN")) {
1167
            return true;
1168
        }
1169
1170
        // Fall over to inherited permissions
1171
        if ($parent && $parent->exists()) {
1172
            return $parent->canAddChildren($member);
1173
        } else {
1174
            // This doesn't necessarily mean we are creating a root page, but that
1175
            // we don't know if there is a parent, so default to this permission
1176
            return SiteConfig::current_site_config()->canCreateTopLevel($member);
1177
        }
1178
    }
1179
1180
    /**
1181
     * This function should return true if the current user can edit this page. It can be overloaded to customise the
1182
     * security model for an application.
1183
     *
1184
     * Denies permission if any of the following conditions is true:
1185
     * - canEdit() on any extension returns false
1186
     * - canView() return false
1187
     * - "CanEditType" directive is set to "Inherit" and any parent page return false for canEdit()
1188
     * - "CanEditType" directive is set to "LoggedInUsers" and no user is logged in or doesn't have the
1189
     *   CMS_Access_CMSMAIN permission code
1190
     * - "CanEditType" directive is set to "OnlyTheseUsers" and user is not in the given groups
1191
     *
1192
     * @uses canView()
1193
     * @uses EditorGroups()
1194
     * @uses DataExtension->canEdit()
1195
     *
1196
     * @param Member $member Set to false if you want to explicitly test permissions without a valid user (useful for
1197
     *                       unit tests)
1198
     * @return bool True if the current user can edit this page
1199
     */
1200 View Code Duplication
    public function canEdit($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...
1201
    {
1202
        if (!$member) {
1203
            $member = Security::getCurrentUser();
1204
        }
1205
1206
        // Standard mechanism for accepting permission changes from extensions
1207
        $extended = $this->extendedCan('canEdit', $member);
0 ignored issues
show
Bug introduced by
It seems like $member can be null; however, extendedCan() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
1208
        if ($extended !== null) {
1209
            return $extended;
1210
        }
1211
1212
        // Default permissions
1213
        if (Permission::checkMember($member, "SITETREE_EDIT_ALL")) {
1214
            return true;
1215
        }
1216
1217
        // Check inherited permissions
1218
        return static::getPermissionChecker()
1219
            ->canEdit($this->ID, $member);
1220
    }
1221
1222
    /**
1223
     * Stub method to get the site config, unless the current class can provide an alternate.
1224
     *
1225
     * @return SiteConfig
1226
     */
1227
    public function getSiteConfig()
1228
    {
1229
        $configs = $this->invokeWithExtensions('alternateSiteConfig');
1230
        foreach (array_filter($configs) as $config) {
1231
            return $config;
1232
        }
1233
1234
        return SiteConfig::current_site_config();
1235
    }
1236
1237
    /**
1238
     * @return PermissionChecker
1239
     */
1240
    public static function getPermissionChecker()
1241
    {
1242
        return Injector::inst()->get(PermissionChecker::class.'.sitetree');
1243
    }
1244
1245
    /**
1246
     * Collate selected descendants of this page.
1247
     *
1248
     * {@link $condition} will be evaluated on each descendant, and if it is succeeds, that item will be added to the
1249
     * $collator array.
1250
     *
1251
     * @param string $condition The PHP condition to be evaluated. The page will be called $item
1252
     * @param array  $collator  An array, passed by reference, to collect all of the matching descendants.
1253
     * @return bool
1254
     */
1255
    public function collateDescendants($condition, &$collator)
1256
    {
1257
        $children = $this->Children();
0 ignored issues
show
Bug introduced by
The method Children() does not exist on SilverStripe\CMS\Model\SiteTree. Did you maybe mean duplicateWithChildren()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
1258
        if ($children) {
1259
            foreach ($children as $item) {
1260
                if (eval("return $condition;")) {
1261
                    $collator[] = $item;
1262
                }
1263
                /** @var SiteTree $item */
1264
                $item->collateDescendants($condition, $collator);
1265
            }
1266
            return true;
1267
        }
1268
        return false;
1269
    }
1270
1271
    /**
1272
     * Return the title, description, keywords and language metatags.
1273
     *
1274
     * @todo Move <title> tag in separate getter for easier customization and more obvious usage
1275
     *
1276
     * @param bool $includeTitle Show default <title>-tag, set to false for custom templating
1277
     * @return string The XHTML metatags
1278
     */
1279
    public function MetaTags($includeTitle = true)
1280
    {
1281
        $tags = array();
1282
        if ($includeTitle && strtolower($includeTitle) != 'false') {
1283
            $tags[] = HTML::createTag('title', array(), $this->obj('Title')->forTemplate());
1284
        }
1285
1286
        $generator = trim(Config::inst()->get(self::class, 'meta_generator'));
1287
        if (!empty($generator)) {
1288
            $tags[] = HTML::createTag('meta', array(
1289
                'name' => 'generator',
1290
                'content' => $generator,
1291
            ));
1292
        }
1293
1294
        $charset = ContentNegotiator::config()->uninherited('encoding');
1295
        $tags[] = HTML::createTag('meta', array(
1296
            'http-equiv' => 'Content-Type',
1297
            'content' => 'text/html; charset=' . $charset,
1298
        ));
1299
        if ($this->MetaDescription) {
1300
            $tags[] = HTML::createTag('meta', array(
1301
                'name' => 'description',
1302
                'content' => $this->MetaDescription,
1303
            ));
1304
        }
1305
1306
        if (Permission::check('CMS_ACCESS_CMSMain')
1307
            && $this->ID > 0
1308
        ) {
1309
            $tags[] = HTML::createTag('meta', array(
1310
                'name' => 'x-page-id',
1311
                'content' => $this->obj('ID')->forTemplate(),
1312
            ));
1313
            $tags[] = HTML::createTag('meta', array(
1314
                'name' => 'x-cms-edit-link',
1315
                'content' => $this->obj('CMSEditLink')->forTemplate(),
1316
            ));
1317
        }
1318
1319
        $tags = implode("\n", $tags);
1320
        if ($this->ExtraMeta) {
1321
            $tags .= $this->obj('ExtraMeta')->forTemplate();
1322
        }
1323
1324
        $this->extend('MetaTags', $tags);
1325
1326
        return $tags;
1327
    }
1328
1329
    /**
1330
     * Returns the object that contains the content that a user would associate with this page.
1331
     *
1332
     * Ordinarily, this is just the page itself, but for example on RedirectorPages or VirtualPages ContentSource() will
1333
     * return the page that is linked to.
1334
     *
1335
     * @return $this
1336
     */
1337
    public function ContentSource()
1338
    {
1339
        return $this;
1340
    }
1341
1342
    /**
1343
     * Add default records to database.
1344
     *
1345
     * This function is called whenever the database is built, after the database tables have all been created. Overload
1346
     * this to add default records when the database is built, but make sure you call parent::requireDefaultRecords().
1347
     */
1348
    public function requireDefaultRecords()
1349
    {
1350
        parent::requireDefaultRecords();
1351
1352
        // default pages
1353
        if (static::class == self::class && $this->config()->create_default_pages) {
1354
            if (!SiteTree::get_by_link(RootURLController::config()->default_homepage_link)) {
1355
                $homepage = new Page();
1356
                $homepage->Title = _t(__CLASS__.'.DEFAULTHOMETITLE', 'Home');
1357
                $homepage->Content = _t(__CLASS__.'.DEFAULTHOMECONTENT', '<p>Welcome to SilverStripe! This is the default homepage. You can edit this page by opening <a href="admin/">the CMS</a>.</p><p>You can now access the <a href="http://docs.silverstripe.org">developer documentation</a>, or begin the <a href="http://www.silverstripe.org/learn/lessons">SilverStripe lessons</a>.</p>');
1358
                $homepage->URLSegment = RootURLController::config()->default_homepage_link;
1359
                $homepage->Sort = 1;
1360
                $homepage->write();
1361
                $homepage->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
1362
                $homepage->flushCache();
1363
                DB::alteration_message('Home page created', 'created');
1364
            }
1365
1366
            if (DB::query("SELECT COUNT(*) FROM \"SiteTree\"")->value() == 1) {
1367
                $aboutus = new Page();
1368
                $aboutus->Title = _t(__CLASS__.'.DEFAULTABOUTTITLE', 'About Us');
1369
                $aboutus->Content = _t(
1370
                    'SilverStripe\\CMS\\Model\\SiteTree.DEFAULTABOUTCONTENT',
1371
                    '<p>You can fill this page out with your own content, or delete it and create your own pages.</p>'
1372
                );
1373
                $aboutus->Sort = 2;
1374
                $aboutus->write();
1375
                $aboutus->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
1376
                $aboutus->flushCache();
1377
                DB::alteration_message('About Us page created', 'created');
1378
1379
                $contactus = new Page();
1380
                $contactus->Title = _t(__CLASS__.'.DEFAULTCONTACTTITLE', 'Contact Us');
1381
                $contactus->Content = _t(
1382
                    'SilverStripe\\CMS\\Model\\SiteTree.DEFAULTCONTACTCONTENT',
1383
                    '<p>You can fill this page out with your own content, or delete it and create your own pages.</p>'
1384
                );
1385
                $contactus->Sort = 3;
1386
                $contactus->write();
1387
                $contactus->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
1388
                $contactus->flushCache();
1389
                DB::alteration_message('Contact Us page created', 'created');
1390
            }
1391
        }
1392
    }
1393
1394
    protected function onBeforeWrite()
1395
    {
1396
        parent::onBeforeWrite();
1397
1398
        // If Sort hasn't been set, make this page come after it's siblings
1399
        if (!$this->Sort) {
1400
            $parentID = ($this->ParentID) ? $this->ParentID : 0;
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1401
            $this->Sort = DB::prepared_query(
1402
                "SELECT MAX(\"Sort\") + 1 FROM \"SiteTree\" WHERE \"ParentID\" = ?",
1403
                array($parentID)
1404
            )->value();
1405
        }
1406
1407
        // If there is no URLSegment set, generate one from Title
1408
        $defaultSegment = $this->generateURLSegment(_t(
1409
            'SilverStripe\\CMS\\Controllers\\CMSMain.NEWPAGE',
1410
            'New {pagetype}',
1411
            array('pagetype' => $this->i18n_singular_name())
1412
        ));
1413
        if ((!$this->URLSegment || $this->URLSegment == $defaultSegment) && $this->Title) {
1414
            $this->URLSegment = $this->generateURLSegment($this->Title);
1415
        } elseif ($this->isChanged('URLSegment', 2)) {
1416
            // Do a strict check on change level, to avoid double encoding caused by
1417
            // bogus changes through forceChange()
1418
            $filter = URLSegmentFilter::create();
1419
            $this->URLSegment = $filter->filter($this->URLSegment);
1420
            // If after sanitising there is no URLSegment, give it a reasonable default
1421
            if (!$this->URLSegment) {
1422
                $this->URLSegment = "page-$this->ID";
1423
            }
1424
        }
1425
1426
        // Ensure that this object has a non-conflicting URLSegment value.
1427
        $count = 2;
1428
        while (!$this->validURLSegment()) {
1429
            $this->URLSegment = preg_replace('/-[0-9]+$/', null, $this->URLSegment) . '-' . $count;
1430
            $count++;
1431
        }
1432
1433
        $this->syncLinkTracking();
1434
1435
        // Check to see if we've only altered fields that shouldn't affect versioning
1436
        $fieldsIgnoredByVersioning = array('HasBrokenLink', 'Status', 'HasBrokenFile', 'ToDo', 'VersionID', 'SaveCount');
1437
        $changedFields = array_keys($this->getChangedFields(true, 2));
1438
1439
        // This more rigorous check is inline with the test that write() does to decide whether or not to write to the
1440
        // DB. We use that to avoid cluttering the system with a migrateVersion() call that doesn't get used
1441
        $oneChangedFields = array_keys($this->getChangedFields(true, 1));
1442
1443
        if ($oneChangedFields && !array_diff($changedFields, $fieldsIgnoredByVersioning)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $oneChangedFields of type array<integer|string> is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1444
            // This will have the affect of preserving the versioning
1445
            $this->migrateVersion($this->Version);
0 ignored issues
show
Bug introduced by
The property Version does not seem to exist. Did you mean versioning?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
Documentation Bug introduced by
The method migrateVersion does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
1446
        }
1447
    }
1448
1449
    /**
1450
     * Trigger synchronisation of link tracking
1451
     *
1452
     * {@see SiteTreeLinkTracking::augmentSyncLinkTracking}
1453
     */
1454
    public function syncLinkTracking()
1455
    {
1456
        $this->extend('augmentSyncLinkTracking');
1457
    }
1458
1459
    public function onBeforeDelete()
1460
    {
1461
        parent::onBeforeDelete();
1462
1463
        // If deleting this page, delete all its children.
1464
        if (SiteTree::config()->enforce_strict_hierarchy && $children = $this->AllChildren()) {
0 ignored issues
show
Documentation Bug introduced by
The method AllChildren does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
1465
            foreach ($children as $child) {
1466
                /** @var SiteTree $child */
1467
                $child->delete();
1468
            }
1469
        }
1470
    }
1471
1472
    public function onAfterDelete()
1473
    {
1474
        $this->updateDependentPages();
1475
        parent::onAfterDelete();
1476
    }
1477
1478
    public function flushCache($persistent = true)
1479
    {
1480
        parent::flushCache($persistent);
1481
        $this->_cache_statusFlags = null;
1482
    }
1483
1484
    public function validate()
1485
    {
1486
        $result = parent::validate();
1487
1488
        // Allowed children validation
1489
        $parent = $this->getParent();
1490
        if ($parent && $parent->exists()) {
1491
            // No need to check for subclasses or instanceof, as allowedChildren() already
1492
            // deconstructs any inheritance trees already.
1493
            $allowed = $parent->allowedChildren();
1494
            $subject = ($this instanceof VirtualPage && $this->CopyContentFromID)
0 ignored issues
show
Bug introduced by
The property CopyContentFromID does not seem to exist. Did you mean Content?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1495
                ? $this->CopyContentFrom()
0 ignored issues
show
Documentation Bug introduced by
The method CopyContentFrom does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
1496
                : $this;
1497
            if (!in_array($subject->ClassName, $allowed)) {
1498
                $result->addError(
1499
                    _t(
1500
                        'SilverStripe\\CMS\\Model\\SiteTree.PageTypeNotAllowed',
1501
                        'Page type "{type}" not allowed as child of this parent page',
1502
                        array('type' => $subject->i18n_singular_name())
1503
                    ),
1504
                    ValidationResult::TYPE_ERROR,
1505
                    'ALLOWED_CHILDREN'
1506
                );
1507
            }
1508
        }
1509
1510
        // "Can be root" validation
1511
        if (!$this->stat('can_be_root') && !$this->ParentID) {
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1512
            $result->addError(
1513
                _t(
1514
                    'SilverStripe\\CMS\\Model\\SiteTree.PageTypNotAllowedOnRoot',
1515
                    'Page type "{type}" is not allowed on the root level',
1516
                    array('type' => $this->i18n_singular_name())
1517
                ),
1518
                ValidationResult::TYPE_ERROR,
1519
                'CAN_BE_ROOT'
1520
            );
1521
        }
1522
1523
        return $result;
1524
    }
1525
1526
    /**
1527
     * Returns true if this object has a URLSegment value that does not conflict with any other objects. This method
1528
     * checks for:
1529
     *  - A page with the same URLSegment that has a conflict
1530
     *  - Conflicts with actions on the parent page
1531
     *  - A conflict caused by a root page having the same URLSegment as a class name
1532
     *
1533
     * @return bool
1534
     */
1535
    public function validURLSegment()
1536
    {
1537
        if (self::config()->nested_urls && $parent = $this->Parent()) {
1538
            if ($controller = ModelAsController::controller_for($parent)) {
1539
                if ($controller instanceof Controller && $controller->hasAction($this->URLSegment)) {
1540
                    return false;
1541
                }
1542
            }
1543
        }
1544
1545
        if (!self::config()->nested_urls || !$this->ParentID) {
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1546
            if (class_exists($this->URLSegment) && is_subclass_of($this->URLSegment, RequestHandler::class)) {
0 ignored issues
show
Bug introduced by
Due to PHP Bug #53727, is_subclass_of might return inconsistent results on some PHP versions if \SilverStripe\Control\RequestHandler::class can be an interface. If so, you could instead use ReflectionClass::implementsInterface.
Loading history...
1547
                return false;
1548
            }
1549
        }
1550
1551
        // Filters by url, id, and parent
1552
        $filter = array('"SiteTree"."URLSegment"' => $this->URLSegment);
1553
        if ($this->ID) {
1554
            $filter['"SiteTree"."ID" <> ?'] = $this->ID;
1555
        }
1556
        if (self::config()->nested_urls) {
1557
            $filter['"SiteTree"."ParentID"'] = $this->ParentID ? $this->ParentID : 0;
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1558
        }
1559
1560
        // If any of the extensions return `0` consider the segment invalid
1561
        $extensionResponses = array_filter(
1562
            (array)$this->extend('augmentValidURLSegment'),
1563
            function ($response) {
1564
                return !is_null($response);
1565
            }
1566
        );
1567
        if ($extensionResponses) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $extensionResponses of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1568
            return min($extensionResponses);
1569
        }
1570
1571
        // Check existence
1572
        return !DataObject::get(self::class, $filter)->exists();
1573
    }
1574
1575
    /**
1576
     * Generate a URL segment based on the title provided.
1577
     *
1578
     * If {@link Extension}s wish to alter URL segment generation, they can do so by defining
1579
     * updateURLSegment(&$url, $title).  $url will be passed by reference and should be modified. $title will contain
1580
     * the title that was originally used as the source of this generated URL. This lets extensions either start from
1581
     * scratch, or incrementally modify the generated URL.
1582
     *
1583
     * @param string $title Page title
1584
     * @return string Generated url segment
1585
     */
1586
    public function generateURLSegment($title)
1587
    {
1588
        $filter = URLSegmentFilter::create();
1589
        $t = $filter->filter($title);
1590
1591
        // Fallback to generic page name if path is empty (= no valid, convertable characters)
1592
        if (!$t || $t == '-' || $t == '-1') {
1593
            $t = "page-$this->ID";
1594
        }
1595
1596
        // Hook for extensions
1597
        $this->extend('updateURLSegment', $t, $title);
1598
1599
        return $t;
1600
    }
1601
1602
    /**
1603
     * Gets the URL segment for the latest draft version of this page.
1604
     *
1605
     * @return string
1606
     */
1607
    public function getStageURLSegment()
1608
    {
1609
        $stageRecord = Versioned::get_one_by_stage(self::class, Versioned::DRAFT, array(
1610
            '"SiteTree"."ID"' => $this->ID
1611
        ));
1612
        return ($stageRecord) ? $stageRecord->URLSegment : null;
1613
    }
1614
1615
    /**
1616
     * Gets the URL segment for the currently published version of this page.
1617
     *
1618
     * @return string
1619
     */
1620
    public function getLiveURLSegment()
1621
    {
1622
        $liveRecord = Versioned::get_one_by_stage(self::class, Versioned::LIVE, array(
1623
            '"SiteTree"."ID"' => $this->ID
1624
        ));
1625
        return ($liveRecord) ? $liveRecord->URLSegment : null;
1626
    }
1627
1628
    /**
1629
     * Returns the pages that depend on this page. This includes virtual pages, pages that link to it, etc.
1630
     *
1631
     * @param bool $includeVirtuals Set to false to exlcude virtual pages.
1632
     * @return ArrayList
1633
     */
1634
    public function DependentPages($includeVirtuals = true)
1635
    {
1636
        if (class_exists('Subsite')) {
1637
            $origDisableSubsiteFilter = Subsite::$disable_subsite_filter;
1638
            Subsite::disable_subsite_filter(true);
1639
        }
1640
1641
        // Content links
1642
        $items = new ArrayList();
1643
1644
        // We merge all into a regular SS_List, because DataList doesn't support merge
1645
        if ($contentLinks = $this->BackLinkTracking()) {
0 ignored issues
show
Documentation Bug introduced by
The method BackLinkTracking does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
1646
            $linkList = new ArrayList();
1647
            foreach ($contentLinks as $item) {
1648
                $item->DependentLinkType = 'Content link';
1649
                $linkList->push($item);
1650
            }
1651
            $items->merge($linkList);
1652
        }
1653
1654
        // Virtual pages
1655
        if ($includeVirtuals) {
1656
            $virtuals = $this->VirtualPages();
1657
            if ($virtuals) {
1658
                $virtualList = new ArrayList();
1659
                foreach ($virtuals as $item) {
1660
                    $item->DependentLinkType = 'Virtual page';
1661
                    $virtualList->push($item);
1662
                }
1663
                $items->merge($virtualList);
1664
            }
1665
        }
1666
1667
        // Redirector pages
1668
        $redirectors = RedirectorPage::get()->where(array(
1669
            '"RedirectorPage"."RedirectionType"' => 'Internal',
1670
            '"RedirectorPage"."LinkToID"' => $this->ID
1671
        ));
1672
        if ($redirectors) {
1673
            $redirectorList = new ArrayList();
1674
            foreach ($redirectors as $item) {
1675
                $item->DependentLinkType = 'Redirector page';
1676
                $redirectorList->push($item);
1677
            }
1678
            $items->merge($redirectorList);
1679
        }
1680
1681
        if (class_exists('Subsite')) {
1682
            Subsite::disable_subsite_filter($origDisableSubsiteFilter);
0 ignored issues
show
Bug introduced by
The variable $origDisableSubsiteFilter does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1683
        }
1684
1685
        return $items;
1686
    }
1687
1688
    /**
1689
     * Return all virtual pages that link to this page.
1690
     *
1691
     * @return DataList
1692
     */
1693
    public function VirtualPages()
1694
    {
1695
        $pages = parent::VirtualPages();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class SilverStripe\ORM\DataObject as the method VirtualPages() does only exist in the following sub-classes of SilverStripe\ORM\DataObject: SilverStripe\CMS\Model\SiteTree. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
1696
1697
        // Disable subsite filter for these pages
1698
        if ($pages instanceof DataList) {
1699
            return $pages->setDataQueryParam('Subsite.filter', false);
1700
        } else {
1701
            return $pages;
1702
        }
1703
    }
1704
1705
    /**
1706
     * Returns a FieldList with which to create the main editing form.
1707
     *
1708
     * You can override this in your child classes to add extra fields - first get the parent fields using
1709
     * parent::getCMSFields(), then use addFieldToTab() on the FieldList.
1710
     *
1711
     * See {@link getSettingsFields()} for a different set of fields concerned with configuration aspects on the record,
1712
     * e.g. access control.
1713
     *
1714
     * @return FieldList The fields to be displayed in the CMS
1715
     */
1716
    public function getCMSFields()
1717
    {
1718
        // Status / message
1719
        // Create a status message for multiple parents
1720
        if ($this->ID && is_numeric($this->ID)) {
1721
            $linkedPages = $this->VirtualPages();
1722
1723
            $parentPageLinks = array();
1724
1725
            if ($linkedPages->count() > 0) {
1726
                /** @var VirtualPage $linkedPage */
1727
                foreach ($linkedPages as $linkedPage) {
1728
                    $parentPage = $linkedPage->Parent();
1729
                    if ($parentPage && $parentPage->exists()) {
1730
                        $link = Convert::raw2att($parentPage->CMSEditLink());
1731
                        $title = Convert::raw2xml($parentPage->Title);
1732
                    } else {
1733
                        $link = CMSPageEditController::singleton()->Link('show');
1734
                        $title = _t(__CLASS__.'.TOPLEVEL', 'Site Content (Top Level)');
1735
                    }
1736
                    $parentPageLinks[] = "<a class=\"cmsEditlink\" href=\"{$link}\">{$title}</a>";
1737
                }
1738
1739
                $lastParent = array_pop($parentPageLinks);
1740
                $parentList = "'$lastParent'";
1741
1742
                if (count($parentPageLinks)) {
1743
                    $parentList = "'" . implode("', '", $parentPageLinks) . "' and "
1744
                        . $parentList;
1745
                }
1746
1747
                $statusMessage[] = _t(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$statusMessage was never initialized. Although not strictly required by PHP, it is generally a good practice to add $statusMessage = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
1748
                    'SilverStripe\\CMS\\Model\\SiteTree.APPEARSVIRTUALPAGES',
1749
                    "This content also appears on the virtual pages in the {title} sections.",
1750
                    array('title' => $parentList)
1751
                );
1752
            }
1753
        }
1754
1755
        if ($this->HasBrokenLink || $this->HasBrokenFile) {
0 ignored issues
show
Documentation introduced by
The property HasBrokenLink does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Documentation introduced by
The property HasBrokenFile does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
1756
            $statusMessage[] = _t(__CLASS__.'.HASBROKENLINKS', "This page has broken links.");
0 ignored issues
show
Bug introduced by
The variable $statusMessage does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1757
        }
1758
1759
        $dependentNote = '';
1760
        $dependentTable = new LiteralField('DependentNote', '<p></p>');
1761
1762
        // Create a table for showing pages linked to this one
1763
        $dependentPages = $this->DependentPages();
1764
        $dependentPagesCount = $dependentPages->count();
1765
        if ($dependentPagesCount) {
1766
            $dependentColumns = array(
1767
                'Title' => $this->fieldLabel('Title'),
1768
                'AbsoluteLink' => _t(__CLASS__.'.DependtPageColumnURL', 'URL'),
1769
                'DependentLinkType' => _t(__CLASS__.'.DependtPageColumnLinkType', 'Link type'),
1770
            );
1771
            if (class_exists('Subsite')) {
1772
                $dependentColumns['Subsite.Title'] = singleton('Subsite')->i18n_singular_name();
1773
            }
1774
1775
            $dependentNote = new LiteralField('DependentNote', '<p>' . _t(__CLASS__.'.DEPENDENT_NOTE', 'The following pages depend on this page. This includes virtual pages, redirector pages, and pages with content links.') . '</p>');
1776
            $dependentTable = GridField::create(
1777
                'DependentPages',
1778
                false,
1779
                $dependentPages
1780
            );
1781
            /** @var GridFieldDataColumns $dataColumns */
1782
            $dataColumns = $dependentTable->getConfig()->getComponentByType('SilverStripe\\Forms\\GridField\\GridFieldDataColumns');
1783
            $dataColumns
1784
                ->setDisplayFields($dependentColumns)
1785
                ->setFieldFormatting(array(
1786
                    'Title' => function ($value, &$item) {
1787
                        return sprintf(
1788
                            '<a href="admin/pages/edit/show/%d">%s</a>',
1789
                            (int)$item->ID,
1790
                            Convert::raw2xml($item->Title)
1791
                        );
1792
                    },
1793
                    'AbsoluteLink' => function ($value, &$item) {
0 ignored issues
show
Unused Code introduced by
The parameter $item is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1794
                        return sprintf(
1795
                            '<a href="%s" target="_blank">%s</a>',
1796
                            Convert::raw2xml($value),
1797
                            Convert::raw2xml($value)
1798
                        );
1799
                    }
1800
                ));
1801
        }
1802
1803
        $baseLink = Controller::join_links(
1804
            Director::absoluteBaseURL(),
1805
            (self::config()->nested_urls && $this->ParentID ? $this->Parent()->RelativeLink(true) : null)
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Documentation introduced by
true is of type boolean, but the function expects a string|null.

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...
1806
        );
1807
1808
        $urlsegment = SiteTreeURLSegmentField::create("URLSegment", $this->fieldLabel('URLSegment'))
1809
            ->setURLPrefix($baseLink)
1810
            ->setDefaultURL($this->generateURLSegment(_t(
1811
                'SilverStripe\\CMS\\Controllers\\CMSMain.NEWPAGE',
1812
                'New {pagetype}',
1813
                array('pagetype' => $this->i18n_singular_name())
1814
            )));
1815
        $helpText = (self::config()->nested_urls && $this->Children()->count())
0 ignored issues
show
Bug introduced by
The method Children() does not exist on SilverStripe\CMS\Model\SiteTree. Did you maybe mean duplicateWithChildren()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
1816
            ? $this->fieldLabel('LinkChangeNote')
1817
            : '';
1818
        if (!Config::inst()->get('SilverStripe\\View\\Parsers\\URLSegmentFilter', 'default_allow_multibyte')) {
1819
            $helpText .= _t('SilverStripe\\CMS\\Forms\\SiteTreeURLSegmentField.HelpChars', ' Special characters are automatically converted or removed.');
1820
        }
1821
        $urlsegment->setHelpText($helpText);
1822
1823
        $fields = new FieldList(
1824
            $rootTab = new TabSet(
1825
                "Root",
1826
                $tabMain = new Tab(
1827
                    'Main',
1828
                    new TextField("Title", $this->fieldLabel('Title')),
1829
                    $urlsegment,
1830
                    new TextField("MenuTitle", $this->fieldLabel('MenuTitle')),
1831
                    $htmlField = new HTMLEditorField("Content", _t(__CLASS__.'.HTMLEDITORTITLE', "Content", 'HTML editor title')),
1832
                    ToggleCompositeField::create(
1833
                        'Metadata',
1834
                        _t(__CLASS__.'.MetadataToggle', 'Metadata'),
1835
                        array(
1836
                            $metaFieldDesc = new TextareaField("MetaDescription", $this->fieldLabel('MetaDescription')),
1837
                            $metaFieldExtra = new TextareaField("ExtraMeta", $this->fieldLabel('ExtraMeta'))
1838
                        )
1839
                    )->setHeadingLevel(4)
1840
                ),
1841
                $tabDependent = new Tab(
1842
                    'Dependent',
1843
                    $dependentNote,
1844
                    $dependentTable
1845
                )
1846
            )
1847
        );
1848
        $htmlField->addExtraClass('stacked');
1849
1850
        // Help text for MetaData on page content editor
1851
        $metaFieldDesc
1852
            ->setRightTitle(
1853
                _t(
1854
                    'SilverStripe\\CMS\\Model\\SiteTree.METADESCHELP',
1855
                    "Search engines use this content for displaying search results (although it will not influence their ranking)."
1856
                )
1857
            )
1858
            ->addExtraClass('help');
1859
        $metaFieldExtra
1860
            ->setRightTitle(
1861
                _t(
1862
                    'SilverStripe\\CMS\\Model\\SiteTree.METAEXTRAHELP',
1863
                    "HTML tags for additional meta information. For example &lt;meta name=\"customName\" content=\"your custom content here\" /&gt;"
1864
                )
1865
            )
1866
            ->addExtraClass('help');
1867
1868
        // Conditional dependent pages tab
1869
        if ($dependentPagesCount) {
1870
            $tabDependent->setTitle(_t(__CLASS__.'.TABDEPENDENT', "Dependent pages") . " ($dependentPagesCount)");
1871
        } else {
1872
            $fields->removeFieldFromTab('Root', 'Dependent');
1873
        }
1874
1875
        $tabMain->setTitle(_t(__CLASS__.'.TABCONTENT', "Main Content"));
1876
1877
        if ($this->ObsoleteClassName) {
0 ignored issues
show
Bug introduced by
The property ObsoleteClassName does not seem to exist. Did you mean ClassName?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1878
            $obsoleteWarning = _t(
1879
                'SilverStripe\\CMS\\Model\\SiteTree.OBSOLETECLASS',
1880
                "This page is of obsolete type {type}. Saving will reset its type and you may lose data",
1881
                array('type' => $this->ObsoleteClassName)
0 ignored issues
show
Bug introduced by
The property ObsoleteClassName does not seem to exist. Did you mean ClassName?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
1882
            );
1883
1884
            $fields->addFieldToTab(
1885
                "Root.Main",
1886
                new LiteralField("ObsoleteWarningHeader", "<p class=\"message warning\">$obsoleteWarning</p>"),
1887
                "Title"
1888
            );
1889
        }
1890
1891
        if (file_exists(BASE_PATH . '/install.php')) {
1892
            $fields->addFieldToTab("Root.Main", new LiteralField(
1893
                "InstallWarningHeader",
1894
                "<p class=\"message warning\">" . _t(
1895
                    "SilverStripe\\CMS\\Model\\SiteTree.REMOVE_INSTALL_WARNING",
1896
                    "Warning: You should remove install.php from this SilverStripe install for security reasons."
1897
                )
1898
                . "</p>"
1899
            ), "Title");
1900
        }
1901
1902
        if (self::$runCMSFieldsExtensions) {
1903
            $this->extend('updateCMSFields', $fields);
1904
        }
1905
1906
        return $fields;
1907
    }
1908
1909
1910
    /**
1911
     * Returns fields related to configuration aspects on this record, e.g. access control. See {@link getCMSFields()}
1912
     * for content-related fields.
1913
     *
1914
     * @return FieldList
1915
     */
1916
    public function getSettingsFields()
1917
    {
1918
        $mapFn = function ($groups = []) {
1919
            $map = [];
1920
            foreach ($groups as $group) {
1921
                // Listboxfield values are escaped, use ASCII char instead of &raquo;
1922
                $map[$group->ID] = $group->getBreadcrumbs(' > ');
1923
            }
1924
            asort($map);
1925
            return $map;
1926
        };
1927
        $groupsMap = $mapFn(Group::get());
1928
        $viewAllGroupsMap = $mapFn(Permission::get_groups_by_permission(['SITETREE_VIEW_ALL', 'ADMIN']));
1929
        $editAllGroupsMap = $mapFn(Permission::get_groups_by_permission(['SITETREE_EDIT_ALL', 'ADMIN']));
1930
1931
        $fields = new FieldList(
1932
            $rootTab = new TabSet(
1933
                "Root",
1934
                $tabBehaviour = new Tab(
1935
                    'Settings',
1936
                    new DropdownField(
1937
                        "ClassName",
1938
                        $this->fieldLabel('ClassName'),
1939
                        $this->getClassDropdown()
1940
                    ),
1941
                    $parentTypeSelector = new CompositeField(
1942
                        $parentType = new OptionsetField("ParentType", _t("SilverStripe\\CMS\\Model\\SiteTree.PAGELOCATION", "Page location"), array(
1943
                            "root" => _t("SilverStripe\\CMS\\Model\\SiteTree.PARENTTYPE_ROOT", "Top-level page"),
1944
                            "subpage" => _t("SilverStripe\\CMS\\Model\\SiteTree.PARENTTYPE_SUBPAGE", "Sub-page underneath a parent page"),
1945
                        )),
1946
                        $parentIDField = new TreeDropdownField("ParentID", $this->fieldLabel('ParentID'), self::class, 'ID', 'MenuTitle')
1947
                    ),
1948
                    $visibility = new FieldGroup(
1949
                        new CheckboxField("ShowInMenus", $this->fieldLabel('ShowInMenus')),
1950
                        new CheckboxField("ShowInSearch", $this->fieldLabel('ShowInSearch'))
1951
                    ),
1952
                    $viewersOptionsField = new OptionsetField(
1953
                        "CanViewType",
1954
                        _t(__CLASS__.'.ACCESSHEADER', "Who can view this page?")
1955
                    ),
1956
                    $viewerGroupsField = ListboxField::create("ViewerGroups", _t(__CLASS__.'.VIEWERGROUPS', "Viewer Groups"))
1957
                        ->setSource($groupsMap)
1958
                        ->setAttribute(
1959
                            'data-placeholder',
1960
                            _t(__CLASS__.'.GroupPlaceholder', 'Click to select group')
1961
                        ),
1962
                    $editorsOptionsField = new OptionsetField(
1963
                        "CanEditType",
1964
                        _t(__CLASS__.'.EDITHEADER', "Who can edit this page?")
1965
                    ),
1966
                    $editorGroupsField = ListboxField::create("EditorGroups", _t(__CLASS__.'.EDITORGROUPS', "Editor Groups"))
1967
                        ->setSource($groupsMap)
1968
                        ->setAttribute(
1969
                            'data-placeholder',
1970
                            _t(__CLASS__.'.GroupPlaceholder', 'Click to select group')
1971
                        )
1972
                )
1973
            )
1974
        );
1975
1976
        $parentType->addExtraClass('noborder');
1977
        $visibility->setTitle($this->fieldLabel('Visibility'));
1978
1979
1980
        // This filter ensures that the ParentID dropdown selection does not show this node,
1981
        // or its descendents, as this causes vanishing bugs
1982
        $parentIDField->setFilterFunction(function ($node) {
1983
            return $node->ID != $this->ID;
1984
        });
1985
        $parentTypeSelector->addExtraClass('parentTypeSelector');
1986
1987
        $tabBehaviour->setTitle(_t(__CLASS__.'.TABBEHAVIOUR', "Behavior"));
1988
1989
        // Make page location fields read-only if the user doesn't have the appropriate permission
1990
        if (!Permission::check("SITETREE_REORGANISE")) {
1991
            $fields->makeFieldReadonly('ParentType');
1992
            if ($this->getParentType() === 'root') {
1993
                $fields->removeByName('ParentID');
1994
            } else {
1995
                $fields->makeFieldReadonly('ParentID');
1996
            }
1997
        }
1998
1999
        $viewersOptionsSource = [
2000
            InheritedPermissions::INHERIT => _t(__CLASS__.'.INHERIT', "Inherit from parent page"),
2001
            InheritedPermissions::ANYONE => _t(__CLASS__.'.ACCESSANYONE', "Anyone"),
2002
            InheritedPermissions::LOGGED_IN_USERS => _t(__CLASS__.'.ACCESSLOGGEDIN', "Logged-in users"),
2003
            InheritedPermissions::ONLY_THESE_USERS => _t(
2004
                __CLASS__.'.ACCESSONLYTHESE',
2005
                "Only these people (choose from list)"
2006
            ),
2007
        ];
2008
        $viewersOptionsField->setSource($viewersOptionsSource);
2009
2010
        // Editors have same options, except no "Anyone"
2011
        $editorsOptionsSource = $viewersOptionsSource;
2012
        unset($editorsOptionsSource[InheritedPermissions::ANYONE]);
2013
        $editorsOptionsField->setSource($editorsOptionsSource);
2014
2015
        if ($viewAllGroupsMap) {
2016
            $viewerGroupsField->setDescription(_t(
2017
                'SilverStripe\\CMS\\Model\\SiteTree.VIEWER_GROUPS_FIELD_DESC',
2018
                'Groups with global view permissions: {groupList}',
2019
                ['groupList' => implode(', ', array_values($viewAllGroupsMap))]
2020
            ));
2021
        }
2022
2023
        if ($editAllGroupsMap) {
2024
            $editorGroupsField->setDescription(_t(
2025
                'SilverStripe\\CMS\\Model\\SiteTree.EDITOR_GROUPS_FIELD_DESC',
2026
                'Groups with global edit permissions: {groupList}',
2027
                ['groupList' => implode(', ', array_values($editAllGroupsMap))]
2028
            ));
2029
        }
2030
2031
        if (!Permission::check('SITETREE_GRANT_ACCESS')) {
2032
            $fields->makeFieldReadonly($viewersOptionsField);
2033
            if ($this->CanEditType === InheritedPermissions::ONLY_THESE_USERS) {
0 ignored issues
show
Documentation introduced by
The property CanEditType does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
2034
                $fields->makeFieldReadonly($viewerGroupsField);
2035
            } else {
2036
                $fields->removeByName('ViewerGroups');
2037
            }
2038
2039
            $fields->makeFieldReadonly($editorsOptionsField);
2040
            if ($this->CanEditType === InheritedPermissions::ONLY_THESE_USERS) {
0 ignored issues
show
Documentation introduced by
The property CanEditType does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
2041
                $fields->makeFieldReadonly($editorGroupsField);
2042
            } else {
2043
                $fields->removeByName('EditorGroups');
2044
            }
2045
        }
2046
2047
        if (self::$runCMSFieldsExtensions) {
2048
            $this->extend('updateSettingsFields', $fields);
2049
        }
2050
2051
        return $fields;
2052
    }
2053
2054
    /**
2055
     * @param bool $includerelations A boolean value to indicate if the labels returned should include relation fields
2056
     * @return array
2057
     */
2058
    public function fieldLabels($includerelations = true)
2059
    {
2060
        $cacheKey = static::class . '_' . $includerelations;
2061
        if (!isset(self::$_cache_field_labels[$cacheKey])) {
2062
            $labels = parent::fieldLabels($includerelations);
2063
            $labels['Title'] = _t(__CLASS__.'.PAGETITLE', "Page name");
2064
            $labels['MenuTitle'] = _t(__CLASS__.'.MENUTITLE', "Navigation label");
2065
            $labels['MetaDescription'] = _t(__CLASS__.'.METADESC', "Meta Description");
2066
            $labels['ExtraMeta'] = _t(__CLASS__.'.METAEXTRA', "Custom Meta Tags");
2067
            $labels['ClassName'] = _t(__CLASS__.'.PAGETYPE', "Page type", 'Classname of a page object');
2068
            $labels['ParentType'] = _t(__CLASS__.'.PARENTTYPE', "Page location");
2069
            $labels['ParentID'] = _t(__CLASS__.'.PARENTID', "Parent page");
2070
            $labels['ShowInMenus'] =_t(__CLASS__.'.SHOWINMENUS', "Show in menus?");
2071
            $labels['ShowInSearch'] = _t(__CLASS__.'.SHOWINSEARCH', "Show in search?");
2072
            $labels['ViewerGroups'] = _t(__CLASS__.'.VIEWERGROUPS', "Viewer Groups");
2073
            $labels['EditorGroups'] = _t(__CLASS__.'.EDITORGROUPS', "Editor Groups");
2074
            $labels['URLSegment'] = _t(__CLASS__.'.URLSegment', 'URL Segment', 'URL for this page');
2075
            $labels['Content'] = _t(__CLASS__.'.Content', 'Content', 'Main HTML Content for a page');
2076
            $labels['CanViewType'] = _t(__CLASS__.'.Viewers', 'Viewers Groups');
2077
            $labels['CanEditType'] = _t(__CLASS__.'.Editors', 'Editors Groups');
2078
            $labels['Comments'] = _t(__CLASS__.'.Comments', 'Comments');
2079
            $labels['Visibility'] = _t(__CLASS__.'.Visibility', 'Visibility');
2080
            $labels['LinkChangeNote'] = _t(
2081
                'SilverStripe\\CMS\\Model\\SiteTree.LINKCHANGENOTE',
2082
                'Changing this page\'s link will also affect the links of all child pages.'
2083
            );
2084
2085
            if ($includerelations) {
2086
                $labels['Parent'] = _t(__CLASS__.'.has_one_Parent', 'Parent Page', 'The parent page in the site hierarchy');
2087
                $labels['LinkTracking'] = _t(__CLASS__.'.many_many_LinkTracking', 'Link Tracking');
2088
                $labels['ImageTracking'] = _t(__CLASS__.'.many_many_ImageTracking', 'Image Tracking');
2089
                $labels['BackLinkTracking'] = _t(__CLASS__.'.many_many_BackLinkTracking', 'Backlink Tracking');
2090
            }
2091
2092
            self::$_cache_field_labels[$cacheKey] = $labels;
2093
        }
2094
2095
        return self::$_cache_field_labels[$cacheKey];
2096
    }
2097
2098
    /**
2099
     * Get the actions available in the CMS for this page - eg Save, Publish.
2100
     *
2101
     * Frontend scripts and styles know how to handle the following FormFields:
2102
     * - top-level FormActions appear as standalone buttons
2103
     * - top-level CompositeField with FormActions within appear as grouped buttons
2104
     * - TabSet & Tabs appear as a drop ups
2105
     * - FormActions within the Tab are restyled as links
2106
     * - major actions can provide alternate states for richer presentation (see ssui.button widget extension)
2107
     *
2108
     * @return FieldList The available actions for this page.
2109
     */
2110
    public function getCMSActions()
2111
    {
2112
        // Get status of page
2113
        $isOnDraft = $this->isOnDraft();
0 ignored issues
show
Documentation Bug introduced by
The method isOnDraft does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
2114
        $isPublished = $this->isPublished();
0 ignored issues
show
Documentation Bug introduced by
The method isPublished does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
2115
        $stagesDiffer = $this->stagesDiffer(Versioned::DRAFT, Versioned::LIVE);
0 ignored issues
show
Documentation Bug introduced by
The method stagesDiffer does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
2116
2117
        // Check permissions
2118
        $canPublish = $this->canPublish();
2119
        $canUnpublish = $this->canUnpublish();
0 ignored issues
show
Documentation Bug introduced by
The method canUnpublish does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
2120
        $canEdit = $this->canEdit();
2121
2122
        // Major actions appear as buttons immediately visible as page actions.
2123
        $majorActions = CompositeField::create()->setName('MajorActions');
2124
        $majorActions->setFieldHolderTemplate(get_class($majorActions) . '_holder_buttongroup');
2125
2126
        // Minor options are hidden behind a drop-up and appear as links (although they are still FormActions).
2127
        $rootTabSet = new TabSet('ActionMenus');
2128
        $moreOptions = new Tab(
2129
            'MoreOptions',
2130
            _t(__CLASS__.'.MoreOptions', 'More options', 'Expands a view for more buttons')
2131
        );
2132
        $moreOptions->addExtraClass('popover-actions-simulate');
2133
        $rootTabSet->push($moreOptions);
2134
        $rootTabSet->addExtraClass('ss-ui-action-tabset action-menus noborder');
2135
2136
        // Render page information into the "more-options" drop-up, on the top.
2137
        $liveRecord = Versioned::get_by_stage(self::class, Versioned::LIVE)->byID($this->ID);
2138
        $infoTemplate = SSViewer::get_templates_by_class(static::class, '_Information', self::class);
2139
        $moreOptions->push(
2140
            new LiteralField(
2141
                'Information',
2142
                $this->customise(array(
2143
                    'Live' => $liveRecord,
2144
                    'ExistsOnLive' => $isPublished
2145
                ))->renderWith($infoTemplate)
2146
            )
2147
        );
2148
2149
        // Add to campaign option if not-archived and has publish permission
2150
        if (($isPublished || $isOnDraft) && $canPublish) {
2151
            $moreOptions->push(
2152
                AddToCampaignHandler_FormAction::create()
2153
                    ->removeExtraClass('btn-primary')
2154
                    ->addExtraClass('btn-secondary')
2155
            );
2156
        }
2157
2158
        // "readonly"/viewing version that isn't the current version of the record
2159
        $stageRecord = Versioned::get_by_stage(static::class, Versioned::DRAFT)->byID($this->ID);
2160
        /** @skipUpgrade */
2161
        if ($stageRecord && $stageRecord->Version != $this->Version) {
0 ignored issues
show
Bug introduced by
The property Version does not seem to exist. Did you mean versioning?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
2162
            $moreOptions->push(FormAction::create('email', _t('SilverStripe\\CMS\\Controllers\\CMSMain.EMAIL', 'Email')));
2163
            $moreOptions->push(FormAction::create('rollback', _t('SilverStripe\\CMS\\Controllers\\CMSMain.ROLLBACK', 'Roll back to this version')));
2164
            $actions = new FieldList(array($majorActions, $rootTabSet));
2165
2166
            // getCMSActions() can be extended with updateCMSActions() on a extension
2167
            $this->extend('updateCMSActions', $actions);
2168
            return $actions;
2169
        }
2170
2171
        // "unpublish"
2172 View Code Duplication
        if ($isPublished && $canPublish && $isOnDraft && $canUnpublish) {
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...
2173
            $moreOptions->push(
2174
                FormAction::create('unpublish', _t(__CLASS__.'.BUTTONUNPUBLISH', 'Unpublish'), 'delete')
2175
                    ->setDescription(_t(__CLASS__.'.BUTTONUNPUBLISHDESC', 'Remove this page from the published site'))
2176
                    ->addExtraClass('btn-secondary')
2177
            );
2178
        }
2179
2180
        // "rollback"
2181 View Code Duplication
        if ($isOnDraft && $isPublished && $canEdit && $stagesDiffer) {
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...
2182
            $moreOptions->push(
2183
                FormAction::create('rollback', _t(__CLASS__.'.BUTTONCANCELDRAFT', 'Cancel draft changes'))
2184
                    ->setDescription(_t(
2185
                        'SilverStripe\\CMS\\Model\\SiteTree.BUTTONCANCELDRAFTDESC',
2186
                        'Delete your draft and revert to the currently published page'
2187
                    ))
2188
                    ->addExtraClass('btn-secondary')
2189
            );
2190
        }
2191
2192
        // "restore"
2193
        if ($canEdit && !$isOnDraft && $isPublished) {
2194
            $majorActions->push(FormAction::create('revert', _t('SilverStripe\\CMS\\Controllers\\CMSMain.RESTORE', 'Restore')));
2195
        }
2196
2197
        // Check if we can restore a deleted page
2198
        // Note: It would be nice to have a canRestore() permission at some point
2199
        if ($canEdit && !$isOnDraft && !$isPublished) {
2200
            // Determine if we should force a restore to root (where once it was a subpage)
2201
            $restoreToRoot = $this->isParentArchived();
2202
2203
            // "restore"
2204
            $title = $restoreToRoot
2205
                ? _t('SilverStripe\\CMS\\Controllers\\CMSMain.RESTORE_TO_ROOT', 'Restore draft at top level')
2206
                : _t('SilverStripe\\CMS\\Controllers\\CMSMain.RESTORE', 'Restore draft');
2207
            $description = $restoreToRoot
2208
                ? _t('SilverStripe\\CMS\\Controllers\\CMSMain.RESTORE_TO_ROOT_DESC', 'Restore the archived version to draft as a top level page')
2209
                : _t('SilverStripe\\CMS\\Controllers\\CMSMain.RESTORE_DESC', 'Restore the archived version to draft');
2210
            $majorActions->push(
2211
                FormAction::create('restore', $title)
2212
                    ->setDescription($description)
2213
                    ->setAttribute('data-to-root', $restoreToRoot)
0 ignored issues
show
Documentation introduced by
$restoreToRoot is of type boolean, but the function expects a string.

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...
2214
                    ->setAttribute('data-icon', 'decline')
2215
            );
2216
        }
2217
2218
        // If a page is on any stage it can be archived
2219
        if (($isOnDraft || $isPublished) && $this->canArchive()) {
0 ignored issues
show
Documentation Bug introduced by
The method canArchive does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
2220
            $title = $isPublished
2221
                ? _t('SilverStripe\\CMS\\Controllers\\CMSMain.UNPUBLISH_AND_ARCHIVE', 'Unpublish and archive')
2222
                : _t('SilverStripe\\CMS\\Controllers\\CMSMain.ARCHIVE', 'Archive');
2223
            $moreOptions->push(
2224
                FormAction::create('archive', $title)
2225
                    ->addExtraClass('delete btn btn-secondary')
2226
                    ->setDescription(_t(
2227
                        'SilverStripe\\CMS\\Model\\SiteTree.BUTTONDELETEDESC',
2228
                        'Remove from draft/live and send to archive'
2229
                    ))
2230
            );
2231
        }
2232
2233
        // "save", supports an alternate state that is still clickable, but notifies the user that the action is not needed.
2234
        if ($canEdit && $isOnDraft) {
2235
            $majorActions->push(
2236
                FormAction::create('save', _t(__CLASS__.'.BUTTONSAVED', 'Saved'))
2237
                    ->addExtraClass('btn-secondary-outline font-icon-check-mark')
2238
                    ->setAttribute('data-btn-alternate', 'btn action btn-primary font-icon-save')
2239
                    ->setUseButtonTag(true)
2240
                    ->setAttribute('data-text-alternate', _t('SilverStripe\\CMS\\Controllers\\CMSMain.SAVEDRAFT', 'Save draft'))
2241
            );
2242
        }
2243
2244
        if ($canPublish && $isOnDraft) {
2245
            // "publish", as with "save", it supports an alternate state to show when action is needed.
2246
            $majorActions->push(
2247
                $publish = FormAction::create('publish', _t(__CLASS__.'.BUTTONPUBLISHED', 'Published'))
2248
                    ->addExtraClass('btn-secondary-outline font-icon-check-mark')
2249
                    ->setAttribute('data-btn-alternate', 'btn action btn-primary font-icon-rocket')
2250
                    ->setUseButtonTag(true)
2251
                    ->setAttribute('data-text-alternate', _t(__CLASS__.'.BUTTONSAVEPUBLISH', 'Save & publish'))
2252
            );
2253
2254
            // Set up the initial state of the button to reflect the state of the underlying SiteTree object.
2255
            if ($stagesDiffer) {
2256
                $publish->addExtraClass('btn-primary font-icon-rocket');
2257
                $publish->setTitle(_t(__CLASS__.'.BUTTONSAVEPUBLISH', 'Save & publish'));
2258
                $publish->removeExtraClass('btn-secondary-outline font-icon-check-mark');
2259
            }
2260
        }
2261
2262
        $actions = new FieldList(array($majorActions, $rootTabSet));
2263
2264
        // Hook for extensions to add/remove actions.
2265
        $this->extend('updateCMSActions', $actions);
2266
2267
        return $actions;
2268
    }
2269
2270
    public function onAfterPublish()
2271
    {
2272
        // Force live sort order to match stage sort order
2273
        DB::prepared_query(
2274
            'UPDATE "SiteTree_Live"
2275
			SET "Sort" = (SELECT "SiteTree"."Sort" FROM "SiteTree" WHERE "SiteTree_Live"."ID" = "SiteTree"."ID")
2276
			WHERE EXISTS (SELECT "SiteTree"."Sort" FROM "SiteTree" WHERE "SiteTree_Live"."ID" = "SiteTree"."ID") AND "ParentID" = ?',
2277
            array($this->ParentID)
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
2278
        );
2279
    }
2280
2281
    /**
2282
     * Update draft dependant pages
2283
     */
2284
    public function onAfterRevertToLive()
2285
    {
2286
        // Use an alias to get the updates made by $this->publish
2287
        /** @var SiteTree $stageSelf */
2288
        $stageSelf = Versioned::get_by_stage(self::class, Versioned::DRAFT)->byID($this->ID);
2289
        $stageSelf->writeWithoutVersion();
0 ignored issues
show
Documentation Bug introduced by
The method writeWithoutVersion does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
2290
2291
        // Need to update pages linking to this one as no longer broken
2292
        foreach ($stageSelf->DependentPages() as $page) {
2293
            /** @var SiteTree $page */
2294
            $page->writeWithoutVersion();
0 ignored issues
show
Documentation Bug introduced by
The method writeWithoutVersion does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
2295
        }
2296
    }
2297
2298
    /**
2299
     * Determine if this page references a parent which is archived, and not available in stage
2300
     *
2301
     * @return bool True if there is an archived parent
2302
     */
2303
    protected function isParentArchived()
2304
    {
2305
        if ($parentID = $this->ParentID) {
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
2306
            /** @var SiteTree $parentPage */
2307
            $parentPage = Versioned::get_latest_version(self::class, $parentID);
2308
            if (!$parentPage || !$parentPage->isOnDraft()) {
0 ignored issues
show
Documentation Bug introduced by
The method isOnDraft does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
2309
                return true;
2310
            }
2311
        }
2312
        return false;
2313
    }
2314
2315
    /**
2316
     * Restore the content in the active copy of this SiteTree page to the stage site.
2317
     *
2318
     * @return self
2319
     */
2320
    public function doRestoreToStage()
2321
    {
2322
        $this->invokeWithExtensions('onBeforeRestoreToStage', $this);
2323
2324
        // Ensure that the parent page is restored, otherwise restore to root
2325
        if ($this->isParentArchived()) {
2326
            $this->ParentID = 0;
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
2327
        }
2328
2329
        // if no record can be found on draft stage (meaning it has been "deleted from draft" before),
2330
        // create an empty record
2331
        if (!DB::prepared_query("SELECT \"ID\" FROM \"SiteTree\" WHERE \"ID\" = ?", array($this->ID))->value()) {
2332
            $conn = DB::get_conn();
2333
            if (method_exists($conn, 'allowPrimaryKeyEditing')) {
2334
                $conn->allowPrimaryKeyEditing(self::class, true);
0 ignored issues
show
Bug introduced by
The method allowPrimaryKeyEditing() does not seem to exist on object<SilverStripe\ORM\Connect\Database>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
2335
            }
2336
            DB::prepared_query("INSERT INTO \"SiteTree\" (\"ID\") VALUES (?)", array($this->ID));
2337
            if (method_exists($conn, 'allowPrimaryKeyEditing')) {
2338
                $conn->allowPrimaryKeyEditing(self::class, false);
0 ignored issues
show
Bug introduced by
The method allowPrimaryKeyEditing() does not seem to exist on object<SilverStripe\ORM\Connect\Database>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
2339
            }
2340
        }
2341
2342
        $oldReadingMode = Versioned::get_reading_mode();
2343
        Versioned::set_stage(Versioned::DRAFT);
2344
        $this->forceChange();
2345
        $this->write();
2346
2347
        /** @var SiteTree $result */
2348
        $result = DataObject::get_by_id(self::class, $this->ID);
2349
2350
        Versioned::set_reading_mode($oldReadingMode);
2351
2352
        // Need to update pages linking to this one as no longer broken
2353
        $this->updateDependentPages();
2354
2355
        $this->invokeWithExtensions('onAfterRestoreToStage', $this);
2356
2357
        return $result;
2358
    }
2359
2360
    /**
2361
     * Check if this page is new - that is, if it has yet to have been written to the database.
2362
     *
2363
     * @return bool
2364
     */
2365
    public function isNew()
2366
    {
2367
        /**
2368
         * This check was a problem for a self-hosted site, and may indicate a bug in the interpreter on their server,
2369
         * or a bug here. Changing the condition from empty($this->ID) to !$this->ID && !$this->record['ID'] fixed this.
2370
         */
2371
        if (empty($this->ID)) {
2372
            return true;
2373
        }
2374
2375
        if (is_numeric($this->ID)) {
2376
            return false;
2377
        }
2378
2379
        return stripos($this->ID, 'new') === 0;
2380
    }
2381
2382
    /**
2383
     * Get the class dropdown used in the CMS to change the class of a page. This returns the list of options in the
2384
     * dropdown as a Map from class name to singular name. Filters by {@link SiteTree->canCreate()}, as well as
2385
     * {@link SiteTree::$needs_permission}.
2386
     *
2387
     * @return array
2388
     */
2389
    protected function getClassDropdown()
2390
    {
2391
        $classes = self::page_type_classes();
2392
        $currentClass = null;
2393
2394
        $result = array();
2395
        foreach ($classes as $class) {
2396
            $instance = singleton($class);
2397
2398
            // if the current page type is this the same as the class type always show the page type in the list
2399
            if ($this->ClassName != $instance->ClassName) {
2400
                if ($instance instanceof HiddenClass) {
2401
                    continue;
2402
                }
2403
                if (!$instance->canCreate(null, array('Parent' => $this->ParentID ? $this->Parent() : null))) {
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
2404
                    continue;
2405
                }
2406
            }
2407
2408
            if ($perms = $instance->stat('need_permission')) {
2409
                if (!$this->can($perms)) {
2410
                    continue;
2411
                }
2412
            }
2413
2414
            $pageTypeName = $instance->i18n_singular_name();
2415
2416
            $currentClass = $class;
2417
            $result[$class] = $pageTypeName;
2418
2419
            // If we're in translation mode, the link between the translated pagetype title and the actual classname
2420
            // might not be obvious, so we add it in parantheses. Example: class "RedirectorPage" has the title
2421
            // "Weiterleitung" in German, so it shows up as "Weiterleitung (RedirectorPage)"
2422
            if (i18n::getData()->langFromLocale(i18n::get_locale()) != 'en') {
2423
                $result[$class] = $result[$class] .  " ({$class})";
2424
            }
2425
        }
2426
2427
        // sort alphabetically, and put current on top
2428
        asort($result);
2429
        if ($currentClass) {
2430
            $currentPageTypeName = $result[$currentClass];
2431
            unset($result[$currentClass]);
2432
            $result = array_reverse($result);
2433
            $result[$currentClass] = $currentPageTypeName;
2434
            $result = array_reverse($result);
2435
        }
2436
2437
        return $result;
2438
    }
2439
2440
    /**
2441
     * Returns an array of the class names of classes that are allowed to be children of this class.
2442
     *
2443
     * @return string[]
2444
     */
2445
    public function allowedChildren()
2446
    {
2447
        // Get config based on old FIRST_SET rules
2448
        $candidates = null;
2449
        $class = get_class($this);
2450
        while ($class) {
2451
            if (Config::inst()->exists($class, 'allowed_children', Config::UNINHERITED)) {
2452
                $candidates = Config::inst()->get($class, 'allowed_children', Config::UNINHERITED);
2453
                break;
2454
            }
2455
            $class = get_parent_class($class);
2456
        }
2457
        if (!$candidates || $candidates === 'none' || $candidates === 'SiteTree_root') {
2458
            return [];
2459
        }
2460
2461
        // Parse candidate list
2462
        $allowedChildren = [];
2463
        foreach ($candidates as $candidate) {
2464
            // If a classname is prefixed by "*", such as "*Page", then only that class is allowed - no subclasses.
2465
            // Otherwise, the class and all its subclasses are allowed.
2466
            if (substr($candidate, 0, 1) == '*') {
2467
                $allowedChildren[] = substr($candidate, 1);
2468
            } elseif ($subclasses = ClassInfo::subclassesFor($candidate)) {
2469
                foreach ($subclasses as $subclass) {
2470
                    if ($subclass == 'SiteTree_root' || singleton($subclass) instanceof HiddenClass) {
2471
                        continue;
2472
                    }
2473
                    $allowedChildren[] = $subclass;
2474
                }
2475
            }
2476
        }
2477
        return $allowedChildren;
2478
    }
2479
2480
    /**
2481
     * Returns the class name of the default class for children of this page.
2482
     *
2483
     * @return string
2484
     */
2485
    public function defaultChild()
2486
    {
2487
        $default = $this->stat('default_child');
2488
        $allowed = $this->allowedChildren();
2489
        if ($allowed) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $allowed of type string[] is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
2490
            if (!$default || !in_array($default, $allowed)) {
2491
                $default = reset($allowed);
2492
            }
2493
            return $default;
2494
        }
2495
        return null;
2496
    }
2497
2498
    /**
2499
     * Returns the class name of the default class for the parent of this page.
2500
     *
2501
     * @return string
2502
     */
2503
    public function defaultParent()
2504
    {
2505
        return $this->stat('default_parent');
2506
    }
2507
2508
    /**
2509
     * Get the title for use in menus for this page. If the MenuTitle field is set it returns that, else it returns the
2510
     * Title field.
2511
     *
2512
     * @return string
2513
     */
2514
    public function getMenuTitle()
2515
    {
2516
        if ($value = $this->getField("MenuTitle")) {
2517
            return $value;
2518
        } else {
2519
            return $this->getField("Title");
2520
        }
2521
    }
2522
2523
2524
    /**
2525
     * Set the menu title for this page.
2526
     *
2527
     * @param string $value
2528
     */
2529
    public function setMenuTitle($value)
2530
    {
2531
        if ($value == $this->getField("Title")) {
2532
            $this->setField("MenuTitle", null);
2533
        } else {
2534
            $this->setField("MenuTitle", $value);
2535
        }
2536
    }
2537
2538
    /**
2539
     * A flag provides the user with additional data about the current page status, for example a "removed from draft"
2540
     * status. Each page can have more than one status flag. Returns a map of a unique key to a (localized) title for
2541
     * the flag. The unique key can be reused as a CSS class. Use the 'updateStatusFlags' extension point to customize
2542
     * the flags.
2543
     *
2544
     * Example (simple):
2545
     *   "deletedonlive" => "Deleted"
2546
     *
2547
     * Example (with optional title attribute):
2548
     *   "deletedonlive" => array('text' => "Deleted", 'title' => 'This page has been deleted')
2549
     *
2550
     * @param bool $cached Whether to serve the fields from cache; false regenerate them
2551
     * @return array
2552
     */
2553
    public function getStatusFlags($cached = true)
2554
    {
2555
        if (!$this->_cache_statusFlags || !$cached) {
2556
            $flags = array();
2557
            if ($this->isOnLiveOnly()) {
0 ignored issues
show
Documentation Bug introduced by
The method isOnLiveOnly does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
2558
                $flags['removedfromdraft'] = array(
2559
                    'text' => _t(__CLASS__.'.ONLIVEONLYSHORT', 'On live only'),
2560
                    'title' => _t(__CLASS__.'.ONLIVEONLYSHORTHELP', 'Page is published, but has been deleted from draft'),
2561
                );
2562
            } elseif ($this->isArchived()) {
0 ignored issues
show
Documentation Bug introduced by
The method isArchived does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
2563
                $flags['archived'] = array(
2564
                    'text' => _t(__CLASS__.'.ARCHIVEDPAGESHORT', 'Archived'),
2565
                    'title' => _t(__CLASS__.'.ARCHIVEDPAGEHELP', 'Page is removed from draft and live'),
2566
                );
2567
            } elseif ($this->isOnDraftOnly()) {
0 ignored issues
show
Documentation Bug introduced by
The method isOnDraftOnly does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
2568
                $flags['addedtodraft'] = array(
2569
                    'text' => _t(__CLASS__.'.ADDEDTODRAFTSHORT', 'Draft'),
2570
                    'title' => _t(__CLASS__.'.ADDEDTODRAFTHELP', "Page has not been published yet")
2571
                );
2572
            } elseif ($this->isModifiedOnDraft()) {
0 ignored issues
show
Documentation Bug introduced by
The method isModifiedOnDraft does not exist on object<SilverStripe\CMS\Model\SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
2573
                $flags['modified'] = array(
2574
                    'text' => _t(__CLASS__.'.MODIFIEDONDRAFTSHORT', 'Modified'),
2575
                    'title' => _t(__CLASS__.'.MODIFIEDONDRAFTHELP', 'Page has unpublished changes'),
2576
                );
2577
            }
2578
2579
            $this->extend('updateStatusFlags', $flags);
2580
2581
            $this->_cache_statusFlags = $flags;
2582
        }
2583
2584
        return $this->_cache_statusFlags;
2585
    }
2586
2587
    /**
2588
     * getTreeTitle will return three <span> html DOM elements, an empty <span> with the class 'jstree-pageicon' in
2589
     * front, following by a <span> wrapping around its MenutTitle, then following by a <span> indicating its
2590
     * publication status.
2591
     *
2592
     * @return string An HTML string ready to be directly used in a template
2593
     */
2594
    public function getTreeTitle()
2595
    {
2596
        // Build the list of candidate children
2597
        $children = array();
2598
        $candidates = static::page_type_classes();
2599
        foreach ($this->allowedChildren() as $childClass) {
2600
            if (!in_array($childClass, $candidates)) {
2601
                continue;
2602
            }
2603
            $child = singleton($childClass);
2604
            if ($child->canCreate(null, array('Parent' => $this))) {
2605
                $children[$childClass] = $child->i18n_singular_name();
2606
            }
2607
        }
2608
        $flags = $this->getStatusFlags();
2609
        $treeTitle = sprintf(
2610
            "<span class=\"jstree-pageicon\"></span><span class=\"item\" data-allowedchildren=\"%s\">%s</span>",
2611
            Convert::raw2att(Convert::raw2json($children)),
2612
            Convert::raw2xml(str_replace(array("\n","\r"), "", $this->MenuTitle))
2613
        );
2614
        foreach ($flags as $class => $data) {
2615
            if (is_string($data)) {
2616
                $data = array('text' => $data);
2617
            }
2618
            $treeTitle .= sprintf(
2619
                "<span class=\"badge %s\"%s>%s</span>",
2620
                'status-' . Convert::raw2xml($class),
2621
                (isset($data['title'])) ? sprintf(' title="%s"', Convert::raw2xml($data['title'])) : '',
2622
                Convert::raw2xml($data['text'])
2623
            );
2624
        }
2625
2626
        return $treeTitle;
2627
    }
2628
2629
    /**
2630
     * Returns the page in the current page stack of the given level. Level(1) will return the main menu item that
2631
     * we're currently inside, etc.
2632
     *
2633
     * @param int $level
2634
     * @return SiteTree
2635
     */
2636
    public function Level($level)
2637
    {
2638
        $parent = $this;
2639
        $stack = array($parent);
2640
        while (($parent = $parent->Parent()) && $parent->exists()) {
2641
            array_unshift($stack, $parent);
2642
        }
2643
2644
        return isset($stack[$level-1]) ? $stack[$level-1] : null;
2645
    }
2646
2647
    /**
2648
     * Gets the depth of this page in the sitetree, where 1 is the root level
2649
     *
2650
     * @return int
2651
     */
2652
    public function getPageLevel()
2653
    {
2654
        if ($this->ParentID) {
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
2655
            return 1 + $this->Parent()->getPageLevel();
2656
        }
2657
        return 1;
2658
    }
2659
2660
    /**
2661
     * Find the controller name by our convention of {$ModelClass}Controller
2662
     *
2663
     * @return string
2664
     */
2665
    public function getControllerName()
2666
    {
2667
        //default controller for SiteTree objects
2668
        $controller = ContentController::class;
2669
2670
        //go through the ancestry for this class looking for
2671
        $ancestry = ClassInfo::ancestry(static::class);
2672
        // loop over the array going from the deepest descendant (ie: the current class) to SiteTree
2673
        while ($class = array_pop($ancestry)) {
2674
            //we don't need to go any deeper than the SiteTree class
2675
            if ($class == SiteTree::class) {
2676
                break;
2677
            }
2678
            // If we have a class of "{$ClassName}Controller" then we found our controller
2679
            if (class_exists($candidate = sprintf('%sController', $class))) {
2680
                $controller = $candidate;
2681
                break;
2682
            } elseif (class_exists($candidate = sprintf('%s_Controller', $class))) {
2683
                // Support the legacy underscored filename, but raise a deprecation notice
2684
                Deprecation::notice(
2685
                    '5.0',
2686
                    'Underscored controller class names are deprecated. Use "MyController" instead of "My_Controller".',
2687
                    Deprecation::SCOPE_GLOBAL
2688
                );
2689
                $controller = $candidate;
2690
                break;
2691
            }
2692
        }
2693
2694
        return $controller;
2695
    }
2696
2697
    /**
2698
     * Return the CSS classes to apply to this node in the CMS tree.
2699
     *
2700
     * @return string
2701
     */
2702
    public function CMSTreeClasses()
2703
    {
2704
        $classes = sprintf('class-%s', static::class);
2705
        if ($this->HasBrokenFile || $this->HasBrokenLink) {
0 ignored issues
show
Documentation introduced by
The property HasBrokenFile does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Documentation introduced by
The property HasBrokenLink does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
2706
            $classes .= " BrokenLink";
2707
        }
2708
2709
        if (!$this->canAddChildren()) {
2710
            $classes .= " nochildren";
2711
        }
2712
2713
        if (!$this->canEdit() && !$this->canAddChildren()) {
2714
            if (!$this->canView()) {
2715
                $classes .= " disabled";
2716
            } else {
2717
                $classes .= " edit-disabled";
2718
            }
2719
        }
2720
2721
        if (!$this->ShowInMenus) {
2722
            $classes .= " notinmenu";
2723
        }
2724
2725
        return $classes;
2726
    }
2727
2728
    /**
2729
     * Stops extendCMSFields() being called on getCMSFields(). This is useful when you need access to fields added by
2730
     * subclasses of SiteTree in a extension. Call before calling parent::getCMSFields(), and reenable afterwards.
2731
     */
2732
    public static function disableCMSFieldsExtensions()
2733
    {
2734
        self::$runCMSFieldsExtensions = false;
2735
    }
2736
2737
    /**
2738
     * Reenables extendCMSFields() being called on getCMSFields() after it has been disabled by
2739
     * disableCMSFieldsExtensions().
2740
     */
2741
    public static function enableCMSFieldsExtensions()
2742
    {
2743
        self::$runCMSFieldsExtensions = true;
2744
    }
2745
2746
    public function providePermissions()
2747
    {
2748
        return array(
2749
            'SITETREE_GRANT_ACCESS' => array(
2750
                'name' => _t(__CLASS__.'.PERMISSION_GRANTACCESS_DESCRIPTION', 'Manage access rights for content'),
2751
                'help' => _t(__CLASS__.'.PERMISSION_GRANTACCESS_HELP', 'Allow setting of page-specific access restrictions in the "Pages" section.'),
2752
                'category' => _t('SilverStripe\\Security\\Permission.PERMISSIONS_CATEGORY', 'Roles and access permissions'),
2753
                'sort' => 100
2754
            ),
2755
            'SITETREE_VIEW_ALL' => array(
2756
                'name' => _t(__CLASS__.'.VIEW_ALL_DESCRIPTION', 'View any page'),
2757
                'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'),
2758
                'sort' => -100,
2759
                'help' => _t(__CLASS__.'.VIEW_ALL_HELP', 'Ability to view any page on the site, regardless of the settings on the Access tab.  Requires the "Access to \'Pages\' section" permission')
2760
            ),
2761
            'SITETREE_EDIT_ALL' => array(
2762
                'name' => _t(__CLASS__.'.EDIT_ALL_DESCRIPTION', 'Edit any page'),
2763
                'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'),
2764
                'sort' => -50,
2765
                'help' => _t(__CLASS__.'.EDIT_ALL_HELP', 'Ability to edit any page on the site, regardless of the settings on the Access tab.  Requires the "Access to \'Pages\' section" permission')
2766
            ),
2767
            'SITETREE_REORGANISE' => array(
2768
                'name' => _t(__CLASS__.'.REORGANISE_DESCRIPTION', 'Change site structure'),
2769
                'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'),
2770
                'help' => _t(__CLASS__.'.REORGANISE_HELP', 'Rearrange pages in the site tree through drag&drop.'),
2771
                'sort' => 100
2772
            ),
2773
            'VIEW_DRAFT_CONTENT' => array(
2774
                'name' => _t(__CLASS__.'.VIEW_DRAFT_CONTENT', 'View draft content'),
2775
                'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'),
2776
                'help' => _t(__CLASS__.'.VIEW_DRAFT_CONTENT_HELP', 'Applies to viewing pages outside of the CMS in draft mode. Useful for external collaborators without CMS access.'),
2777
                'sort' => 100
2778
            )
2779
        );
2780
    }
2781
2782
    /**
2783
     * Default singular name for page / sitetree
2784
     *
2785
     * @return string
2786
     */
2787 View Code Duplication
    public function singular_name()
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...
2788
    {
2789
        $base = in_array(static::class, [Page::class, self::class]);
2790
        if ($base) {
2791
            return $this->stat('base_singular_name');
2792
        }
2793
        return parent::singular_name();
2794
    }
2795
2796
    /**
2797
     * Default plural name for page / sitetree
2798
     *
2799
     * @return string
2800
     */
2801 View Code Duplication
    public function plural_name()
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...
2802
    {
2803
        $base = in_array(static::class, [Page::class, self::class]);
2804
        if ($base) {
2805
            return $this->stat('base_plural_name');
2806
        }
2807
        return parent::plural_name();
2808
    }
2809
2810
    /**
2811
     * Get description for this page type
2812
     *
2813
     * @return string|null
2814
     */
2815
    public function classDescription()
2816
    {
2817
        $base = in_array(static::class, [Page::class, self::class]);
2818
        if ($base) {
2819
            return $this->stat('base_description');
2820
        }
2821
        return $this->stat('description');
2822
    }
2823
2824
    /**
2825
     * Get localised description for this page
2826
     *
2827
     * @return string|null
2828
     */
2829
    public function i18n_classDescription()
2830
    {
2831
        $description = $this->classDescription();
2832
        if ($description) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $description of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2833
            return _t(static::class.'.DESCRIPTION', $description);
2834
        }
2835
        return null;
2836
    }
2837
2838
    /**
2839
     * Overloaded to also provide entities for 'Page' class which is usually located in custom code, hence textcollector
2840
     * picks it up for the wrong folder.
2841
     *
2842
     * @return array
2843
     */
2844
    public function provideI18nEntities()
2845
    {
2846
        $entities = parent::provideI18nEntities();
2847
2848
        // Add optional description
2849
        $description = $this->classDescription();
2850
        if ($description) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $description of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2851
            $entities[static::class . '.DESCRIPTION'] = $description;
2852
        }
2853
        return $entities;
2854
    }
2855
2856
    /**
2857
     * Returns 'root' if the current page has no parent, or 'subpage' otherwise
2858
     *
2859
     * @return string
2860
     */
2861
    public function getParentType()
2862
    {
2863
        return $this->ParentID == 0 ? 'root' : 'subpage';
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<SilverStripe\CMS\Model\SiteTree>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
2864
    }
2865
2866
    /**
2867
     * Clear the permissions cache for SiteTree
2868
     */
2869
    public static function reset()
2870
    {
2871
        $permissions = static::getPermissionChecker();
2872
        if ($permissions instanceof InheritedPermissions) {
2873
            $permissions->clearCache();
2874
        }
2875
    }
2876
2877
    /**
2878
     * Update dependant pages
2879
     */
2880
    protected function updateDependentPages()
2881
    {
2882
        // Need to flush cache to avoid outdated versionnumber references
2883
        $this->flushCache();
2884
2885
        // Need to mark pages depending to this one as broken
2886
        $dependentPages = $this->DependentPages();
2887
        if ($dependentPages) {
2888
            foreach ($dependentPages as $page) {
2889
                // $page->write() calls syncLinkTracking, which does all the hard work for us.
2890
                $page->write();
2891
            }
2892
        }
2893
    }
2894
}
2895