Completed
Push — master ( d14e00...ecbd77 )
by Ingo
21s
created

SiteTree::updateDependentPages()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 0
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 instanceof ErrorPage
1308
            && $this->ID > 0
1309
        ) {
1310
            $tags[] = HTML::createTag('meta', array(
1311
                'name' => 'x-page-id',
1312
                'content' => $this->obj('ID')->forTemplate(),
1313
            ));
1314
            $tags[] = HTML::createTag('meta', array(
1315
                'name' => 'x-cms-edit-link',
1316
                'content' => $this->obj('CMSEditLink')->forTemplate(),
1317
            ));
1318
        }
1319
1320
        $tags = implode("\n", $tags);
1321
        if ($this->ExtraMeta) {
1322
            $tags .= $this->obj('ExtraMeta')->forTemplate();
1323
        }
1324
1325
        $this->extend('MetaTags', $tags);
1326
1327
        return $tags;
1328
    }
1329
1330
    /**
1331
     * Returns the object that contains the content that a user would associate with this page.
1332
     *
1333
     * Ordinarily, this is just the page itself, but for example on RedirectorPages or VirtualPages ContentSource() will
1334
     * return the page that is linked to.
1335
     *
1336
     * @return $this
1337
     */
1338
    public function ContentSource()
1339
    {
1340
        return $this;
1341
    }
1342
1343
    /**
1344
     * Add default records to database.
1345
     *
1346
     * This function is called whenever the database is built, after the database tables have all been created. Overload
1347
     * this to add default records when the database is built, but make sure you call parent::requireDefaultRecords().
1348
     */
1349
    public function requireDefaultRecords()
1350
    {
1351
        parent::requireDefaultRecords();
1352
1353
        // default pages
1354
        if (static::class == self::class && $this->config()->create_default_pages) {
1355
            if (!SiteTree::get_by_link(RootURLController::config()->default_homepage_link)) {
1356
                $homepage = new Page();
1357
                $homepage->Title = _t(__CLASS__.'.DEFAULTHOMETITLE', 'Home');
1358
                $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>');
1359
                $homepage->URLSegment = RootURLController::config()->default_homepage_link;
1360
                $homepage->Sort = 1;
1361
                $homepage->write();
1362
                $homepage->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
1363
                $homepage->flushCache();
1364
                DB::alteration_message('Home page created', 'created');
1365
            }
1366
1367
            if (DB::query("SELECT COUNT(*) FROM \"SiteTree\"")->value() == 1) {
1368
                $aboutus = new Page();
1369
                $aboutus->Title = _t(__CLASS__.'.DEFAULTABOUTTITLE', 'About Us');
1370
                $aboutus->Content = _t(
1371
                    'SilverStripe\\CMS\\Model\\SiteTree.DEFAULTABOUTCONTENT',
1372
                    '<p>You can fill this page out with your own content, or delete it and create your own pages.</p>'
1373
                );
1374
                $aboutus->Sort = 2;
1375
                $aboutus->write();
1376
                $aboutus->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
1377
                $aboutus->flushCache();
1378
                DB::alteration_message('About Us page created', 'created');
1379
1380
                $contactus = new Page();
1381
                $contactus->Title = _t(__CLASS__.'.DEFAULTCONTACTTITLE', 'Contact Us');
1382
                $contactus->Content = _t(
1383
                    'SilverStripe\\CMS\\Model\\SiteTree.DEFAULTCONTACTCONTENT',
1384
                    '<p>You can fill this page out with your own content, or delete it and create your own pages.</p>'
1385
                );
1386
                $contactus->Sort = 3;
1387
                $contactus->write();
1388
                $contactus->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
1389
                $contactus->flushCache();
1390
                DB::alteration_message('Contact Us page created', 'created');
1391
            }
1392
        }
1393
    }
1394
1395
    protected function onBeforeWrite()
1396
    {
1397
        parent::onBeforeWrite();
1398
1399
        // If Sort hasn't been set, make this page come after it's siblings
1400
        if (!$this->Sort) {
1401
            $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...
1402
            $this->Sort = DB::prepared_query(
1403
                "SELECT MAX(\"Sort\") + 1 FROM \"SiteTree\" WHERE \"ParentID\" = ?",
1404
                array($parentID)
1405
            )->value();
1406
        }
1407
1408
        // If there is no URLSegment set, generate one from Title
1409
        $defaultSegment = $this->generateURLSegment(_t(
1410
            'SilverStripe\\CMS\\Controllers\\CMSMain.NEWPAGE',
1411
            'New {pagetype}',
1412
            array('pagetype' => $this->i18n_singular_name())
1413
        ));
1414
        if ((!$this->URLSegment || $this->URLSegment == $defaultSegment) && $this->Title) {
1415
            $this->URLSegment = $this->generateURLSegment($this->Title);
1416
        } elseif ($this->isChanged('URLSegment', 2)) {
1417
            // Do a strict check on change level, to avoid double encoding caused by
1418
            // bogus changes through forceChange()
1419
            $filter = URLSegmentFilter::create();
1420
            $this->URLSegment = $filter->filter($this->URLSegment);
1421
            // If after sanitising there is no URLSegment, give it a reasonable default
1422
            if (!$this->URLSegment) {
1423
                $this->URLSegment = "page-$this->ID";
1424
            }
1425
        }
1426
1427
        // Ensure that this object has a non-conflicting URLSegment value.
1428
        $count = 2;
1429
        while (!$this->validURLSegment()) {
1430
            $this->URLSegment = preg_replace('/-[0-9]+$/', null, $this->URLSegment) . '-' . $count;
1431
            $count++;
1432
        }
1433
1434
        $this->syncLinkTracking();
1435
1436
        // Check to see if we've only altered fields that shouldn't affect versioning
1437
        $fieldsIgnoredByVersioning = array('HasBrokenLink', 'Status', 'HasBrokenFile', 'ToDo', 'VersionID', 'SaveCount');
1438
        $changedFields = array_keys($this->getChangedFields(true, 2));
1439
1440
        // This more rigorous check is inline with the test that write() does to decide whether or not to write to the
1441
        // DB. We use that to avoid cluttering the system with a migrateVersion() call that doesn't get used
1442
        $oneChangedFields = array_keys($this->getChangedFields(true, 1));
1443
1444
        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...
1445
            // This will have the affect of preserving the versioning
1446
            $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...
1447
        }
1448
    }
1449
1450
    /**
1451
     * Trigger synchronisation of link tracking
1452
     *
1453
     * {@see SiteTreeLinkTracking::augmentSyncLinkTracking}
1454
     */
1455
    public function syncLinkTracking()
1456
    {
1457
        $this->extend('augmentSyncLinkTracking');
1458
    }
1459
1460
    public function onBeforeDelete()
1461
    {
1462
        parent::onBeforeDelete();
1463
1464
        // If deleting this page, delete all its children.
1465
        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...
1466
            foreach ($children as $child) {
1467
                /** @var SiteTree $child */
1468
                $child->delete();
1469
            }
1470
        }
1471
    }
1472
1473
    public function onAfterDelete()
1474
    {
1475
        $this->updateDependentPages();
1476
        parent::onAfterDelete();
1477
    }
1478
1479
    public function flushCache($persistent = true)
1480
    {
1481
        parent::flushCache($persistent);
1482
        $this->_cache_statusFlags = null;
1483
    }
1484
1485
    public function validate()
1486
    {
1487
        $result = parent::validate();
1488
1489
        // Allowed children validation
1490
        $parent = $this->getParent();
1491
        if ($parent && $parent->exists()) {
1492
            // No need to check for subclasses or instanceof, as allowedChildren() already
1493
            // deconstructs any inheritance trees already.
1494
            $allowed = $parent->allowedChildren();
1495
            $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...
1496
                ? $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...
1497
                : $this;
1498
            if (!in_array($subject->ClassName, $allowed)) {
1499
                $result->addError(
1500
                    _t(
1501
                        'SilverStripe\\CMS\\Model\\SiteTree.PageTypeNotAllowed',
1502
                        'Page type "{type}" not allowed as child of this parent page',
1503
                        array('type' => $subject->i18n_singular_name())
1504
                    ),
1505
                    ValidationResult::TYPE_ERROR,
1506
                    'ALLOWED_CHILDREN'
1507
                );
1508
            }
1509
        }
1510
1511
        // "Can be root" validation
1512
        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...
1513
            $result->addError(
1514
                _t(
1515
                    'SilverStripe\\CMS\\Model\\SiteTree.PageTypNotAllowedOnRoot',
1516
                    'Page type "{type}" is not allowed on the root level',
1517
                    array('type' => $this->i18n_singular_name())
1518
                ),
1519
                ValidationResult::TYPE_ERROR,
1520
                'CAN_BE_ROOT'
1521
            );
1522
        }
1523
1524
        return $result;
1525
    }
1526
1527
    /**
1528
     * Returns true if this object has a URLSegment value that does not conflict with any other objects. This method
1529
     * checks for:
1530
     *  - A page with the same URLSegment that has a conflict
1531
     *  - Conflicts with actions on the parent page
1532
     *  - A conflict caused by a root page having the same URLSegment as a class name
1533
     *
1534
     * @return bool
1535
     */
1536
    public function validURLSegment()
1537
    {
1538
        if (self::config()->nested_urls && $parent = $this->Parent()) {
1539
            if ($controller = ModelAsController::controller_for($parent)) {
1540
                if ($controller instanceof Controller && $controller->hasAction($this->URLSegment)) {
1541
                    return false;
1542
                }
1543
            }
1544
        }
1545
1546
        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...
1547
            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...
1548
                return false;
1549
            }
1550
        }
1551
1552
        // Filters by url, id, and parent
1553
        $filter = array('"SiteTree"."URLSegment"' => $this->URLSegment);
1554
        if ($this->ID) {
1555
            $filter['"SiteTree"."ID" <> ?'] = $this->ID;
1556
        }
1557
        if (self::config()->nested_urls) {
1558
            $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...
1559
        }
1560
1561
        // If any of the extensions return `0` consider the segment invalid
1562
        $extensionResponses = array_filter(
1563
            (array)$this->extend('augmentValidURLSegment'),
1564
            function ($response) {
1565
                return !is_null($response);
1566
            }
1567
        );
1568
        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...
1569
            return min($extensionResponses);
1570
        }
1571
1572
        // Check existence
1573
        return !DataObject::get(self::class, $filter)->exists();
1574
    }
1575
1576
    /**
1577
     * Generate a URL segment based on the title provided.
1578
     *
1579
     * If {@link Extension}s wish to alter URL segment generation, they can do so by defining
1580
     * updateURLSegment(&$url, $title).  $url will be passed by reference and should be modified. $title will contain
1581
     * the title that was originally used as the source of this generated URL. This lets extensions either start from
1582
     * scratch, or incrementally modify the generated URL.
1583
     *
1584
     * @param string $title Page title
1585
     * @return string Generated url segment
1586
     */
1587
    public function generateURLSegment($title)
1588
    {
1589
        $filter = URLSegmentFilter::create();
1590
        $t = $filter->filter($title);
1591
1592
        // Fallback to generic page name if path is empty (= no valid, convertable characters)
1593
        if (!$t || $t == '-' || $t == '-1') {
1594
            $t = "page-$this->ID";
1595
        }
1596
1597
        // Hook for extensions
1598
        $this->extend('updateURLSegment', $t, $title);
1599
1600
        return $t;
1601
    }
1602
1603
    /**
1604
     * Gets the URL segment for the latest draft version of this page.
1605
     *
1606
     * @return string
1607
     */
1608
    public function getStageURLSegment()
1609
    {
1610
        $stageRecord = Versioned::get_one_by_stage(self::class, Versioned::DRAFT, array(
1611
            '"SiteTree"."ID"' => $this->ID
1612
        ));
1613
        return ($stageRecord) ? $stageRecord->URLSegment : null;
1614
    }
1615
1616
    /**
1617
     * Gets the URL segment for the currently published version of this page.
1618
     *
1619
     * @return string
1620
     */
1621
    public function getLiveURLSegment()
1622
    {
1623
        $liveRecord = Versioned::get_one_by_stage(self::class, Versioned::LIVE, array(
1624
            '"SiteTree"."ID"' => $this->ID
1625
        ));
1626
        return ($liveRecord) ? $liveRecord->URLSegment : null;
1627
    }
1628
1629
    /**
1630
     * Returns the pages that depend on this page. This includes virtual pages, pages that link to it, etc.
1631
     *
1632
     * @param bool $includeVirtuals Set to false to exlcude virtual pages.
1633
     * @return ArrayList
1634
     */
1635
    public function DependentPages($includeVirtuals = true)
1636
    {
1637
        if (class_exists('Subsite')) {
1638
            $origDisableSubsiteFilter = Subsite::$disable_subsite_filter;
1639
            Subsite::disable_subsite_filter(true);
1640
        }
1641
1642
        // Content links
1643
        $items = new ArrayList();
1644
1645
        // We merge all into a regular SS_List, because DataList doesn't support merge
1646
        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...
1647
            $linkList = new ArrayList();
1648
            foreach ($contentLinks as $item) {
1649
                $item->DependentLinkType = 'Content link';
1650
                $linkList->push($item);
1651
            }
1652
            $items->merge($linkList);
1653
        }
1654
1655
        // Virtual pages
1656
        if ($includeVirtuals) {
1657
            $virtuals = $this->VirtualPages();
1658
            if ($virtuals) {
1659
                $virtualList = new ArrayList();
1660
                foreach ($virtuals as $item) {
1661
                    $item->DependentLinkType = 'Virtual page';
1662
                    $virtualList->push($item);
1663
                }
1664
                $items->merge($virtualList);
1665
            }
1666
        }
1667
1668
        // Redirector pages
1669
        $redirectors = RedirectorPage::get()->where(array(
1670
            '"RedirectorPage"."RedirectionType"' => 'Internal',
1671
            '"RedirectorPage"."LinkToID"' => $this->ID
1672
        ));
1673
        if ($redirectors) {
1674
            $redirectorList = new ArrayList();
1675
            foreach ($redirectors as $item) {
1676
                $item->DependentLinkType = 'Redirector page';
1677
                $redirectorList->push($item);
1678
            }
1679
            $items->merge($redirectorList);
1680
        }
1681
1682
        if (class_exists('Subsite')) {
1683
            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...
1684
        }
1685
1686
        return $items;
1687
    }
1688
1689
    /**
1690
     * Return all virtual pages that link to this page.
1691
     *
1692
     * @return DataList
1693
     */
1694
    public function VirtualPages()
1695
    {
1696
        $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...
1697
1698
        // Disable subsite filter for these pages
1699
        if ($pages instanceof DataList) {
1700
            return $pages->setDataQueryParam('Subsite.filter', false);
1701
        } else {
1702
            return $pages;
1703
        }
1704
    }
1705
1706
    /**
1707
     * Returns a FieldList with which to create the main editing form.
1708
     *
1709
     * You can override this in your child classes to add extra fields - first get the parent fields using
1710
     * parent::getCMSFields(), then use addFieldToTab() on the FieldList.
1711
     *
1712
     * See {@link getSettingsFields()} for a different set of fields concerned with configuration aspects on the record,
1713
     * e.g. access control.
1714
     *
1715
     * @return FieldList The fields to be displayed in the CMS
1716
     */
1717
    public function getCMSFields()
1718
    {
1719
        // Status / message
1720
        // Create a status message for multiple parents
1721
        if ($this->ID && is_numeric($this->ID)) {
1722
            $linkedPages = $this->VirtualPages();
1723
1724
            $parentPageLinks = array();
1725
1726
            if ($linkedPages->count() > 0) {
1727
                /** @var VirtualPage $linkedPage */
1728
                foreach ($linkedPages as $linkedPage) {
1729
                    $parentPage = $linkedPage->Parent();
1730
                    if ($parentPage && $parentPage->exists()) {
1731
                        $link = Convert::raw2att($parentPage->CMSEditLink());
1732
                        $title = Convert::raw2xml($parentPage->Title);
1733
                    } else {
1734
                        $link = CMSPageEditController::singleton()->Link('show');
1735
                        $title = _t(__CLASS__.'.TOPLEVEL', 'Site Content (Top Level)');
1736
                    }
1737
                    $parentPageLinks[] = "<a class=\"cmsEditlink\" href=\"{$link}\">{$title}</a>";
1738
                }
1739
1740
                $lastParent = array_pop($parentPageLinks);
1741
                $parentList = "'$lastParent'";
1742
1743
                if (count($parentPageLinks)) {
1744
                    $parentList = "'" . implode("', '", $parentPageLinks) . "' and "
1745
                        . $parentList;
1746
                }
1747
1748
                $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...
1749
                    'SilverStripe\\CMS\\Model\\SiteTree.APPEARSVIRTUALPAGES',
1750
                    "This content also appears on the virtual pages in the {title} sections.",
1751
                    array('title' => $parentList)
1752
                );
1753
            }
1754
        }
1755
1756
        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...
1757
            $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...
1758
        }
1759
1760
        $dependentNote = '';
1761
        $dependentTable = new LiteralField('DependentNote', '<p></p>');
1762
1763
        // Create a table for showing pages linked to this one
1764
        $dependentPages = $this->DependentPages();
1765
        $dependentPagesCount = $dependentPages->count();
1766
        if ($dependentPagesCount) {
1767
            $dependentColumns = array(
1768
                'Title' => $this->fieldLabel('Title'),
1769
                'AbsoluteLink' => _t(__CLASS__.'.DependtPageColumnURL', 'URL'),
1770
                'DependentLinkType' => _t(__CLASS__.'.DependtPageColumnLinkType', 'Link type'),
1771
            );
1772
            if (class_exists('Subsite')) {
1773
                $dependentColumns['Subsite.Title'] = singleton('Subsite')->i18n_singular_name();
1774
            }
1775
1776
            $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>');
1777
            $dependentTable = GridField::create(
1778
                'DependentPages',
1779
                false,
1780
                $dependentPages
1781
            );
1782
            /** @var GridFieldDataColumns $dataColumns */
1783
            $dataColumns = $dependentTable->getConfig()->getComponentByType('SilverStripe\\Forms\\GridField\\GridFieldDataColumns');
1784
            $dataColumns
1785
                ->setDisplayFields($dependentColumns)
1786
                ->setFieldFormatting(array(
1787
                    'Title' => function ($value, &$item) {
1788
                        return sprintf(
1789
                            '<a href="admin/pages/edit/show/%d">%s</a>',
1790
                            (int)$item->ID,
1791
                            Convert::raw2xml($item->Title)
1792
                        );
1793
                    },
1794
                    '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...
1795
                        return sprintf(
1796
                            '<a href="%s" target="_blank">%s</a>',
1797
                            Convert::raw2xml($value),
1798
                            Convert::raw2xml($value)
1799
                        );
1800
                    }
1801
                ));
1802
        }
1803
1804
        $baseLink = Controller::join_links(
1805
            Director::absoluteBaseURL(),
1806
            (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...
1807
        );
1808
1809
        $urlsegment = SiteTreeURLSegmentField::create("URLSegment", $this->fieldLabel('URLSegment'))
1810
            ->setURLPrefix($baseLink)
1811
            ->setDefaultURL($this->generateURLSegment(_t(
1812
                'SilverStripe\\CMS\\Controllers\\CMSMain.NEWPAGE',
1813
                'New {pagetype}',
1814
                array('pagetype' => $this->i18n_singular_name())
1815
            )));
1816
        $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...
1817
            ? $this->fieldLabel('LinkChangeNote')
1818
            : '';
1819
        if (!Config::inst()->get('SilverStripe\\View\\Parsers\\URLSegmentFilter', 'default_allow_multibyte')) {
1820
            $helpText .= _t('SilverStripe\\CMS\\Forms\\SiteTreeURLSegmentField.HelpChars', ' Special characters are automatically converted or removed.');
1821
        }
1822
        $urlsegment->setHelpText($helpText);
1823
1824
        $fields = new FieldList(
1825
            $rootTab = new TabSet(
1826
                "Root",
1827
                $tabMain = new Tab(
1828
                    'Main',
1829
                    new TextField("Title", $this->fieldLabel('Title')),
1830
                    $urlsegment,
1831
                    new TextField("MenuTitle", $this->fieldLabel('MenuTitle')),
1832
                    $htmlField = new HTMLEditorField("Content", _t(__CLASS__.'.HTMLEDITORTITLE', "Content", 'HTML editor title')),
1833
                    ToggleCompositeField::create(
1834
                        'Metadata',
1835
                        _t(__CLASS__.'.MetadataToggle', 'Metadata'),
1836
                        array(
1837
                            $metaFieldDesc = new TextareaField("MetaDescription", $this->fieldLabel('MetaDescription')),
1838
                            $metaFieldExtra = new TextareaField("ExtraMeta", $this->fieldLabel('ExtraMeta'))
1839
                        )
1840
                    )->setHeadingLevel(4)
1841
                ),
1842
                $tabDependent = new Tab(
1843
                    'Dependent',
1844
                    $dependentNote,
1845
                    $dependentTable
1846
                )
1847
            )
1848
        );
1849
        $htmlField->addExtraClass('stacked');
1850
1851
        // Help text for MetaData on page content editor
1852
        $metaFieldDesc
1853
            ->setRightTitle(
1854
                _t(
1855
                    'SilverStripe\\CMS\\Model\\SiteTree.METADESCHELP',
1856
                    "Search engines use this content for displaying search results (although it will not influence their ranking)."
1857
                )
1858
            )
1859
            ->addExtraClass('help');
1860
        $metaFieldExtra
1861
            ->setRightTitle(
1862
                _t(
1863
                    'SilverStripe\\CMS\\Model\\SiteTree.METAEXTRAHELP',
1864
                    "HTML tags for additional meta information. For example &lt;meta name=\"customName\" content=\"your custom content here\" /&gt;"
1865
                )
1866
            )
1867
            ->addExtraClass('help');
1868
1869
        // Conditional dependent pages tab
1870
        if ($dependentPagesCount) {
1871
            $tabDependent->setTitle(_t(__CLASS__.'.TABDEPENDENT', "Dependent pages") . " ($dependentPagesCount)");
1872
        } else {
1873
            $fields->removeFieldFromTab('Root', 'Dependent');
1874
        }
1875
1876
        $tabMain->setTitle(_t(__CLASS__.'.TABCONTENT', "Main Content"));
1877
1878
        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...
1879
            $obsoleteWarning = _t(
1880
                'SilverStripe\\CMS\\Model\\SiteTree.OBSOLETECLASS',
1881
                "This page is of obsolete type {type}. Saving will reset its type and you may lose data",
1882
                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...
1883
            );
1884
1885
            $fields->addFieldToTab(
1886
                "Root.Main",
1887
                new LiteralField("ObsoleteWarningHeader", "<p class=\"message warning\">$obsoleteWarning</p>"),
1888
                "Title"
1889
            );
1890
        }
1891
1892
        if (file_exists(BASE_PATH . '/install.php')) {
1893
            $fields->addFieldToTab("Root.Main", new LiteralField(
1894
                "InstallWarningHeader",
1895
                "<p class=\"message warning\">" . _t(
1896
                    "SilverStripe\\CMS\\Model\\SiteTree.REMOVE_INSTALL_WARNING",
1897
                    "Warning: You should remove install.php from this SilverStripe install for security reasons."
1898
                )
1899
                . "</p>"
1900
            ), "Title");
1901
        }
1902
1903
        if (self::$runCMSFieldsExtensions) {
1904
            $this->extend('updateCMSFields', $fields);
1905
        }
1906
1907
        return $fields;
1908
    }
1909
1910
1911
    /**
1912
     * Returns fields related to configuration aspects on this record, e.g. access control. See {@link getCMSFields()}
1913
     * for content-related fields.
1914
     *
1915
     * @return FieldList
1916
     */
1917
    public function getSettingsFields()
1918
    {
1919
        $groupsMap = array();
1920
        foreach (Group::get() as $group) {
1921
            // Listboxfield values are escaped, use ASCII char instead of &raquo;
1922
            $groupsMap[$group->ID] = $group->getBreadcrumbs(' > ');
1923
        }
1924
        asort($groupsMap);
1925
1926
        $fields = new FieldList(
1927
            $rootTab = new TabSet(
1928
                "Root",
1929
                $tabBehaviour = new Tab(
1930
                    'Settings',
1931
                    new DropdownField(
1932
                        "ClassName",
1933
                        $this->fieldLabel('ClassName'),
1934
                        $this->getClassDropdown()
1935
                    ),
1936
                    $parentTypeSelector = new CompositeField(
1937
                        $parentType = new OptionsetField("ParentType", _t("SilverStripe\\CMS\\Model\\SiteTree.PAGELOCATION", "Page location"), array(
1938
                            "root" => _t("SilverStripe\\CMS\\Model\\SiteTree.PARENTTYPE_ROOT", "Top-level page"),
1939
                            "subpage" => _t("SilverStripe\\CMS\\Model\\SiteTree.PARENTTYPE_SUBPAGE", "Sub-page underneath a parent page"),
1940
                        )),
1941
                        $parentIDField = new TreeDropdownField("ParentID", $this->fieldLabel('ParentID'), self::class, 'ID', 'MenuTitle')
1942
                    ),
1943
                    $visibility = new FieldGroup(
1944
                        new CheckboxField("ShowInMenus", $this->fieldLabel('ShowInMenus')),
1945
                        new CheckboxField("ShowInSearch", $this->fieldLabel('ShowInSearch'))
1946
                    ),
1947
                    $viewersOptionsField = new OptionsetField(
1948
                        "CanViewType",
1949
                        _t(__CLASS__.'.ACCESSHEADER', "Who can view this page?")
1950
                    ),
1951
                    $viewerGroupsField = ListboxField::create("ViewerGroups", _t(__CLASS__.'.VIEWERGROUPS', "Viewer Groups"))
1952
                        ->setSource($groupsMap)
1953
                        ->setAttribute(
1954
                            'data-placeholder',
1955
                            _t(__CLASS__.'.GroupPlaceholder', 'Click to select group')
1956
                        ),
1957
                    $editorsOptionsField = new OptionsetField(
1958
                        "CanEditType",
1959
                        _t(__CLASS__.'.EDITHEADER', "Who can edit this page?")
1960
                    ),
1961
                    $editorGroupsField = ListboxField::create("EditorGroups", _t(__CLASS__.'.EDITORGROUPS', "Editor Groups"))
1962
                        ->setSource($groupsMap)
1963
                        ->setAttribute(
1964
                            'data-placeholder',
1965
                            _t(__CLASS__.'.GroupPlaceholder', 'Click to select group')
1966
                        )
1967
                )
1968
            )
1969
        );
1970
1971
        $parentType->addExtraClass('noborder');
1972
        $visibility->setTitle($this->fieldLabel('Visibility'));
1973
1974
1975
        // This filter ensures that the ParentID dropdown selection does not show this node,
1976
        // or its descendents, as this causes vanishing bugs
1977
        $parentIDField->setFilterFunction(function ($node) {
1978
            return $node->ID != $this->ID;
1979
        });
1980
        $parentTypeSelector->addExtraClass('parentTypeSelector');
1981
1982
        $tabBehaviour->setTitle(_t(__CLASS__.'.TABBEHAVIOUR', "Behavior"));
1983
1984
        // Make page location fields read-only if the user doesn't have the appropriate permission
1985
        if (!Permission::check("SITETREE_REORGANISE")) {
1986
            $fields->makeFieldReadonly('ParentType');
1987
            if ($this->getParentType() === 'root') {
1988
                $fields->removeByName('ParentID');
1989
            } else {
1990
                $fields->makeFieldReadonly('ParentID');
1991
            }
1992
        }
1993
1994
        $viewersOptionsSource = [
1995
            InheritedPermissions::INHERIT => _t(__CLASS__.'.INHERIT', "Inherit from parent page"),
1996
            InheritedPermissions::ANYONE => _t(__CLASS__.'.ACCESSANYONE', "Anyone"),
1997
            InheritedPermissions::LOGGED_IN_USERS => _t(__CLASS__.'.ACCESSLOGGEDIN', "Logged-in users"),
1998
            InheritedPermissions::ONLY_THESE_USERS => _t(
1999
                __CLASS__.'.ACCESSONLYTHESE',
2000
                "Only these people (choose from list)"
2001
            ),
2002
        ];
2003
        $viewersOptionsField->setSource($viewersOptionsSource);
2004
2005
        // Editors have same options, except no "Anyone"
2006
        $editorsOptionsSource = $viewersOptionsSource;
2007
        unset($editorsOptionsSource[InheritedPermissions::ANYONE]);
2008
        $editorsOptionsField->setSource($editorsOptionsSource);
2009
2010
        if (!Permission::check('SITETREE_GRANT_ACCESS')) {
2011
            $fields->makeFieldReadonly($viewersOptionsField);
2012
            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...
2013
                $fields->makeFieldReadonly($viewerGroupsField);
2014
            } else {
2015
                $fields->removeByName('ViewerGroups');
2016
            }
2017
2018
            $fields->makeFieldReadonly($editorsOptionsField);
2019
            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...
2020
                $fields->makeFieldReadonly($editorGroupsField);
2021
            } else {
2022
                $fields->removeByName('EditorGroups');
2023
            }
2024
        }
2025
2026
        if (self::$runCMSFieldsExtensions) {
2027
            $this->extend('updateSettingsFields', $fields);
2028
        }
2029
2030
        return $fields;
2031
    }
2032
2033
    /**
2034
     * @param bool $includerelations A boolean value to indicate if the labels returned should include relation fields
2035
     * @return array
2036
     */
2037
    public function fieldLabels($includerelations = true)
2038
    {
2039
        $cacheKey = static::class . '_' . $includerelations;
2040
        if (!isset(self::$_cache_field_labels[$cacheKey])) {
2041
            $labels = parent::fieldLabels($includerelations);
2042
            $labels['Title'] = _t(__CLASS__.'.PAGETITLE', "Page name");
2043
            $labels['MenuTitle'] = _t(__CLASS__.'.MENUTITLE', "Navigation label");
2044
            $labels['MetaDescription'] = _t(__CLASS__.'.METADESC', "Meta Description");
2045
            $labels['ExtraMeta'] = _t(__CLASS__.'.METAEXTRA', "Custom Meta Tags");
2046
            $labels['ClassName'] = _t(__CLASS__.'.PAGETYPE', "Page type", 'Classname of a page object');
2047
            $labels['ParentType'] = _t(__CLASS__.'.PARENTTYPE', "Page location");
2048
            $labels['ParentID'] = _t(__CLASS__.'.PARENTID', "Parent page");
2049
            $labels['ShowInMenus'] =_t(__CLASS__.'.SHOWINMENUS', "Show in menus?");
2050
            $labels['ShowInSearch'] = _t(__CLASS__.'.SHOWINSEARCH', "Show in search?");
2051
            $labels['ViewerGroups'] = _t(__CLASS__.'.VIEWERGROUPS', "Viewer Groups");
2052
            $labels['EditorGroups'] = _t(__CLASS__.'.EDITORGROUPS', "Editor Groups");
2053
            $labels['URLSegment'] = _t(__CLASS__.'.URLSegment', 'URL Segment', 'URL for this page');
2054
            $labels['Content'] = _t(__CLASS__.'.Content', 'Content', 'Main HTML Content for a page');
2055
            $labels['CanViewType'] = _t(__CLASS__.'.Viewers', 'Viewers Groups');
2056
            $labels['CanEditType'] = _t(__CLASS__.'.Editors', 'Editors Groups');
2057
            $labels['Comments'] = _t(__CLASS__.'.Comments', 'Comments');
2058
            $labels['Visibility'] = _t(__CLASS__.'.Visibility', 'Visibility');
2059
            $labels['LinkChangeNote'] = _t(
2060
                'SilverStripe\\CMS\\Model\\SiteTree.LINKCHANGENOTE',
2061
                'Changing this page\'s link will also affect the links of all child pages.'
2062
            );
2063
2064
            if ($includerelations) {
2065
                $labels['Parent'] = _t(__CLASS__.'.has_one_Parent', 'Parent Page', 'The parent page in the site hierarchy');
2066
                $labels['LinkTracking'] = _t(__CLASS__.'.many_many_LinkTracking', 'Link Tracking');
2067
                $labels['ImageTracking'] = _t(__CLASS__.'.many_many_ImageTracking', 'Image Tracking');
2068
                $labels['BackLinkTracking'] = _t(__CLASS__.'.many_many_BackLinkTracking', 'Backlink Tracking');
2069
            }
2070
2071
            self::$_cache_field_labels[$cacheKey] = $labels;
2072
        }
2073
2074
        return self::$_cache_field_labels[$cacheKey];
2075
    }
2076
2077
    /**
2078
     * Get the actions available in the CMS for this page - eg Save, Publish.
2079
     *
2080
     * Frontend scripts and styles know how to handle the following FormFields:
2081
     * - top-level FormActions appear as standalone buttons
2082
     * - top-level CompositeField with FormActions within appear as grouped buttons
2083
     * - TabSet & Tabs appear as a drop ups
2084
     * - FormActions within the Tab are restyled as links
2085
     * - major actions can provide alternate states for richer presentation (see ssui.button widget extension)
2086
     *
2087
     * @return FieldList The available actions for this page.
2088
     */
2089
    public function getCMSActions()
2090
    {
2091
        // Get status of page
2092
        $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...
2093
        $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...
2094
        $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...
2095
2096
        // Check permissions
2097
        $canPublish = $this->canPublish();
2098
        $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...
2099
        $canEdit = $this->canEdit();
2100
2101
        // Major actions appear as buttons immediately visible as page actions.
2102
        $majorActions = CompositeField::create()->setName('MajorActions');
2103
        $majorActions->setFieldHolderTemplate(get_class($majorActions) . '_holder_buttongroup');
2104
2105
        // Minor options are hidden behind a drop-up and appear as links (although they are still FormActions).
2106
        $rootTabSet = new TabSet('ActionMenus');
2107
        $moreOptions = new Tab(
2108
            'MoreOptions',
2109
            _t(__CLASS__.'.MoreOptions', 'More options', 'Expands a view for more buttons')
2110
        );
2111
        $rootTabSet->push($moreOptions);
2112
        $rootTabSet->addExtraClass('ss-ui-action-tabset action-menus noborder');
2113
2114
        // Render page information into the "more-options" drop-up, on the top.
2115
        $liveRecord = Versioned::get_by_stage(self::class, Versioned::LIVE)->byID($this->ID);
2116
        $infoTemplate = SSViewer::get_templates_by_class(static::class, '_Information', self::class);
2117
        $moreOptions->push(
2118
            new LiteralField(
2119
                'Information',
2120
                $this->customise(array(
2121
                    'Live' => $liveRecord,
2122
                    'ExistsOnLive' => $isPublished
2123
                ))->renderWith($infoTemplate)
2124
            )
2125
        );
2126
2127
        // Add to campaign option if not-archived and has publish permission
2128
        if (($isPublished || $isOnDraft) && $canPublish) {
2129
            $moreOptions->push(
2130
                AddToCampaignHandler_FormAction::create()
2131
                    ->removeExtraClass('btn-primary')
2132
                    ->addExtraClass('btn-secondary')
2133
            );
2134
        }
2135
2136
        // "readonly"/viewing version that isn't the current version of the record
2137
        $stageRecord = Versioned::get_by_stage(static::class, Versioned::DRAFT)->byID($this->ID);
2138
        /** @skipUpgrade */
2139
        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...
2140
            $moreOptions->push(FormAction::create('email', _t('SilverStripe\\CMS\\Controllers\\CMSMain.EMAIL', 'Email')));
2141
            $moreOptions->push(FormAction::create('rollback', _t('SilverStripe\\CMS\\Controllers\\CMSMain.ROLLBACK', 'Roll back to this version')));
2142
            $actions = new FieldList(array($majorActions, $rootTabSet));
2143
2144
            // getCMSActions() can be extended with updateCMSActions() on a extension
2145
            $this->extend('updateCMSActions', $actions);
2146
            return $actions;
2147
        }
2148
2149
        // "unpublish"
2150 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...
2151
            $moreOptions->push(
2152
                FormAction::create('unpublish', _t(__CLASS__.'.BUTTONUNPUBLISH', 'Unpublish'), 'delete')
2153
                    ->setDescription(_t(__CLASS__.'.BUTTONUNPUBLISHDESC', 'Remove this page from the published site'))
2154
                    ->addExtraClass('btn-secondary')
2155
            );
2156
        }
2157
2158
        // "rollback"
2159 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...
2160
            $moreOptions->push(
2161
                FormAction::create('rollback', _t(__CLASS__.'.BUTTONCANCELDRAFT', 'Cancel draft changes'))
2162
                    ->setDescription(_t(
2163
                        'SilverStripe\\CMS\\Model\\SiteTree.BUTTONCANCELDRAFTDESC',
2164
                        'Delete your draft and revert to the currently published page'
2165
                    ))
2166
                    ->addExtraClass('btn-secondary')
2167
            );
2168
        }
2169
2170
        // "restore"
2171
        if ($canEdit && !$isOnDraft && $isPublished) {
2172
            $majorActions->push(FormAction::create('revert', _t('SilverStripe\\CMS\\Controllers\\CMSMain.RESTORE', 'Restore')));
2173
        }
2174
2175
        // Check if we can restore a deleted page
2176
        // Note: It would be nice to have a canRestore() permission at some point
2177
        if ($canEdit && !$isOnDraft && !$isPublished) {
2178
            // Determine if we should force a restore to root (where once it was a subpage)
2179
            $restoreToRoot = $this->isParentArchived();
2180
2181
            // "restore"
2182
            $title = $restoreToRoot
2183
                ? _t('SilverStripe\\CMS\\Controllers\\CMSMain.RESTORE_TO_ROOT', 'Restore draft at top level')
2184
                : _t('SilverStripe\\CMS\\Controllers\\CMSMain.RESTORE', 'Restore draft');
2185
            $description = $restoreToRoot
2186
                ? _t('SilverStripe\\CMS\\Controllers\\CMSMain.RESTORE_TO_ROOT_DESC', 'Restore the archived version to draft as a top level page')
2187
                : _t('SilverStripe\\CMS\\Controllers\\CMSMain.RESTORE_DESC', 'Restore the archived version to draft');
2188
            $majorActions->push(
2189
                FormAction::create('restore', $title)
2190
                    ->setDescription($description)
2191
                    ->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...
2192
                    ->setAttribute('data-icon', 'decline')
2193
            );
2194
        }
2195
2196
        // If a page is on any stage it can be archived
2197
        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...
2198
            $title = $isPublished
2199
                ? _t('SilverStripe\\CMS\\Controllers\\CMSMain.UNPUBLISH_AND_ARCHIVE', 'Unpublish and archive')
2200
                : _t('SilverStripe\\CMS\\Controllers\\CMSMain.ARCHIVE', 'Archive');
2201
            $moreOptions->push(
2202
                FormAction::create('archive', $title)
2203
                    ->addExtraClass('delete btn btn-secondary')
2204
                    ->setDescription(_t(
2205
                        'SilverStripe\\CMS\\Model\\SiteTree.BUTTONDELETEDESC',
2206
                        'Remove from draft/live and send to archive'
2207
                    ))
2208
            );
2209
        }
2210
2211
        // "save", supports an alternate state that is still clickable, but notifies the user that the action is not needed.
2212
        if ($canEdit && $isOnDraft) {
2213
            $majorActions->push(
2214
                FormAction::create('save', _t(__CLASS__.'.BUTTONSAVED', 'Saved'))
2215
                    ->addExtraClass('btn-secondary-outline font-icon-check-mark')
2216
                    ->setAttribute('data-btn-alternate', 'btn action btn-primary font-icon-save')
2217
                    ->setUseButtonTag(true)
2218
                    ->setAttribute('data-text-alternate', _t('SilverStripe\\CMS\\Controllers\\CMSMain.SAVEDRAFT', 'Save draft'))
2219
            );
2220
        }
2221
2222
        if ($canPublish && $isOnDraft) {
2223
            // "publish", as with "save", it supports an alternate state to show when action is needed.
2224
            $majorActions->push(
2225
                $publish = FormAction::create('publish', _t(__CLASS__.'.BUTTONPUBLISHED', 'Published'))
2226
                    ->addExtraClass('btn-secondary-outline font-icon-check-mark')
2227
                    ->setAttribute('data-btn-alternate', 'btn action btn-primary font-icon-rocket')
2228
                    ->setUseButtonTag(true)
2229
                    ->setAttribute('data-text-alternate', _t(__CLASS__.'.BUTTONSAVEPUBLISH', 'Save & publish'))
2230
            );
2231
2232
            // Set up the initial state of the button to reflect the state of the underlying SiteTree object.
2233
            if ($stagesDiffer) {
2234
                $publish->addExtraClass('btn-primary font-icon-rocket');
2235
                $publish->setTitle(_t(__CLASS__.'.BUTTONSAVEPUBLISH', 'Save & publish'));
2236
                $publish->removeExtraClass('btn-secondary-outline font-icon-check-mark');
2237
            }
2238
        }
2239
2240
        $actions = new FieldList(array($majorActions, $rootTabSet));
2241
2242
        // Hook for extensions to add/remove actions.
2243
        $this->extend('updateCMSActions', $actions);
2244
2245
        return $actions;
2246
    }
2247
2248
    public function onAfterPublish()
2249
    {
2250
        // Force live sort order to match stage sort order
2251
        DB::prepared_query(
2252
            'UPDATE "SiteTree_Live"
2253
			SET "Sort" = (SELECT "SiteTree"."Sort" FROM "SiteTree" WHERE "SiteTree_Live"."ID" = "SiteTree"."ID")
2254
			WHERE EXISTS (SELECT "SiteTree"."Sort" FROM "SiteTree" WHERE "SiteTree_Live"."ID" = "SiteTree"."ID") AND "ParentID" = ?',
2255
            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...
2256
        );
2257
    }
2258
2259
    /**
2260
     * Update draft dependant pages
2261
     */
2262
    public function onAfterRevertToLive()
2263
    {
2264
        // Use an alias to get the updates made by $this->publish
2265
        /** @var SiteTree $stageSelf */
2266
        $stageSelf = Versioned::get_by_stage(self::class, Versioned::DRAFT)->byID($this->ID);
2267
        $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...
2268
2269
        // Need to update pages linking to this one as no longer broken
2270
        foreach ($stageSelf->DependentPages() as $page) {
2271
            /** @var SiteTree $page */
2272
            $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...
2273
        }
2274
    }
2275
2276
    /**
2277
     * Determine if this page references a parent which is archived, and not available in stage
2278
     *
2279
     * @return bool True if there is an archived parent
2280
     */
2281
    protected function isParentArchived()
2282
    {
2283
        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...
2284
            /** @var SiteTree $parentPage */
2285
            $parentPage = Versioned::get_latest_version(self::class, $parentID);
2286
            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...
2287
                return true;
2288
            }
2289
        }
2290
        return false;
2291
    }
2292
2293
    /**
2294
     * Restore the content in the active copy of this SiteTree page to the stage site.
2295
     *
2296
     * @return self
2297
     */
2298
    public function doRestoreToStage()
2299
    {
2300
        $this->invokeWithExtensions('onBeforeRestoreToStage', $this);
2301
2302
        // Ensure that the parent page is restored, otherwise restore to root
2303
        if ($this->isParentArchived()) {
2304
            $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...
2305
        }
2306
2307
        // if no record can be found on draft stage (meaning it has been "deleted from draft" before),
2308
        // create an empty record
2309
        if (!DB::prepared_query("SELECT \"ID\" FROM \"SiteTree\" WHERE \"ID\" = ?", array($this->ID))->value()) {
2310
            $conn = DB::get_conn();
2311
            if (method_exists($conn, 'allowPrimaryKeyEditing')) {
2312
                $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...
2313
            }
2314
            DB::prepared_query("INSERT INTO \"SiteTree\" (\"ID\") VALUES (?)", array($this->ID));
2315
            if (method_exists($conn, 'allowPrimaryKeyEditing')) {
2316
                $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...
2317
            }
2318
        }
2319
2320
        $oldReadingMode = Versioned::get_reading_mode();
2321
        Versioned::set_stage(Versioned::DRAFT);
2322
        $this->forceChange();
2323
        $this->write();
2324
2325
        /** @var SiteTree $result */
2326
        $result = DataObject::get_by_id(self::class, $this->ID);
2327
2328
        Versioned::set_reading_mode($oldReadingMode);
2329
2330
        // Need to update pages linking to this one as no longer broken
2331
        $this->updateDependentPages();
2332
2333
        $this->invokeWithExtensions('onAfterRestoreToStage', $this);
2334
2335
        return $result;
2336
    }
2337
2338
    /**
2339
     * Check if this page is new - that is, if it has yet to have been written to the database.
2340
     *
2341
     * @return bool
2342
     */
2343
    public function isNew()
2344
    {
2345
        /**
2346
         * This check was a problem for a self-hosted site, and may indicate a bug in the interpreter on their server,
2347
         * or a bug here. Changing the condition from empty($this->ID) to !$this->ID && !$this->record['ID'] fixed this.
2348
         */
2349
        if (empty($this->ID)) {
2350
            return true;
2351
        }
2352
2353
        if (is_numeric($this->ID)) {
2354
            return false;
2355
        }
2356
2357
        return stripos($this->ID, 'new') === 0;
2358
    }
2359
2360
    /**
2361
     * Get the class dropdown used in the CMS to change the class of a page. This returns the list of options in the
2362
     * dropdown as a Map from class name to singular name. Filters by {@link SiteTree->canCreate()}, as well as
2363
     * {@link SiteTree::$needs_permission}.
2364
     *
2365
     * @return array
2366
     */
2367
    protected function getClassDropdown()
2368
    {
2369
        $classes = self::page_type_classes();
2370
        $currentClass = null;
2371
2372
        $result = array();
2373
        foreach ($classes as $class) {
2374
            $instance = singleton($class);
2375
2376
            // if the current page type is this the same as the class type always show the page type in the list
2377
            if ($this->ClassName != $instance->ClassName) {
2378
                if ($instance instanceof HiddenClass) {
2379
                    continue;
2380
                }
2381
                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...
2382
                    continue;
2383
                }
2384
            }
2385
2386
            if ($perms = $instance->stat('need_permission')) {
2387
                if (!$this->can($perms)) {
2388
                    continue;
2389
                }
2390
            }
2391
2392
            $pageTypeName = $instance->i18n_singular_name();
2393
2394
            $currentClass = $class;
2395
            $result[$class] = $pageTypeName;
2396
2397
            // If we're in translation mode, the link between the translated pagetype title and the actual classname
2398
            // might not be obvious, so we add it in parantheses. Example: class "RedirectorPage" has the title
2399
            // "Weiterleitung" in German, so it shows up as "Weiterleitung (RedirectorPage)"
2400
            if (i18n::getData()->langFromLocale(i18n::get_locale()) != 'en') {
2401
                $result[$class] = $result[$class] .  " ({$class})";
2402
            }
2403
        }
2404
2405
        // sort alphabetically, and put current on top
2406
        asort($result);
2407
        if ($currentClass) {
2408
            $currentPageTypeName = $result[$currentClass];
2409
            unset($result[$currentClass]);
2410
            $result = array_reverse($result);
2411
            $result[$currentClass] = $currentPageTypeName;
2412
            $result = array_reverse($result);
2413
        }
2414
2415
        return $result;
2416
    }
2417
2418
    /**
2419
     * Returns an array of the class names of classes that are allowed to be children of this class.
2420
     *
2421
     * @return string[]
2422
     */
2423
    public function allowedChildren()
2424
    {
2425
        // Get config based on old FIRST_SET rules
2426
        $candidates = null;
2427
        $class = get_class($this);
2428
        while ($class) {
2429
            if (Config::inst()->exists($class, 'allowed_children', Config::UNINHERITED)) {
2430
                $candidates = Config::inst()->get($class, 'allowed_children', Config::UNINHERITED);
2431
                break;
2432
            }
2433
            $class = get_parent_class($class);
2434
        }
2435
        if (!$candidates || $candidates === 'none' || $candidates === 'SiteTree_root') {
2436
            return [];
2437
        }
2438
2439
        // Parse candidate list
2440
        $allowedChildren = [];
2441
        foreach ($candidates as $candidate) {
2442
            // If a classname is prefixed by "*", such as "*Page", then only that class is allowed - no subclasses.
2443
            // Otherwise, the class and all its subclasses are allowed.
2444
            if (substr($candidate, 0, 1) == '*') {
2445
                $allowedChildren[] = substr($candidate, 1);
2446
            } elseif ($subclasses = ClassInfo::subclassesFor($candidate)) {
2447
                foreach ($subclasses as $subclass) {
2448
                    if ($subclass == 'SiteTree_root' || singleton($subclass) instanceof HiddenClass) {
2449
                        continue;
2450
                    }
2451
                    $allowedChildren[] = $subclass;
2452
                }
2453
            }
2454
        }
2455
        return $allowedChildren;
2456
    }
2457
2458
    /**
2459
     * Returns the class name of the default class for children of this page.
2460
     *
2461
     * @return string
2462
     */
2463
    public function defaultChild()
2464
    {
2465
        $default = $this->stat('default_child');
2466
        $allowed = $this->allowedChildren();
2467
        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...
2468
            if (!$default || !in_array($default, $allowed)) {
2469
                $default = reset($allowed);
2470
            }
2471
            return $default;
2472
        }
2473
        return null;
2474
    }
2475
2476
    /**
2477
     * Returns the class name of the default class for the parent of this page.
2478
     *
2479
     * @return string
2480
     */
2481
    public function defaultParent()
2482
    {
2483
        return $this->stat('default_parent');
2484
    }
2485
2486
    /**
2487
     * Get the title for use in menus for this page. If the MenuTitle field is set it returns that, else it returns the
2488
     * Title field.
2489
     *
2490
     * @return string
2491
     */
2492
    public function getMenuTitle()
2493
    {
2494
        if ($value = $this->getField("MenuTitle")) {
2495
            return $value;
2496
        } else {
2497
            return $this->getField("Title");
2498
        }
2499
    }
2500
2501
2502
    /**
2503
     * Set the menu title for this page.
2504
     *
2505
     * @param string $value
2506
     */
2507
    public function setMenuTitle($value)
2508
    {
2509
        if ($value == $this->getField("Title")) {
2510
            $this->setField("MenuTitle", null);
2511
        } else {
2512
            $this->setField("MenuTitle", $value);
2513
        }
2514
    }
2515
2516
    /**
2517
     * A flag provides the user with additional data about the current page status, for example a "removed from draft"
2518
     * status. Each page can have more than one status flag. Returns a map of a unique key to a (localized) title for
2519
     * the flag. The unique key can be reused as a CSS class. Use the 'updateStatusFlags' extension point to customize
2520
     * the flags.
2521
     *
2522
     * Example (simple):
2523
     *   "deletedonlive" => "Deleted"
2524
     *
2525
     * Example (with optional title attribute):
2526
     *   "deletedonlive" => array('text' => "Deleted", 'title' => 'This page has been deleted')
2527
     *
2528
     * @param bool $cached Whether to serve the fields from cache; false regenerate them
2529
     * @return array
2530
     */
2531
    public function getStatusFlags($cached = true)
2532
    {
2533
        if (!$this->_cache_statusFlags || !$cached) {
2534
            $flags = array();
2535
            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...
2536
                $flags['removedfromdraft'] = array(
2537
                    'text' => _t(__CLASS__.'.ONLIVEONLYSHORT', 'On live only'),
2538
                    'title' => _t(__CLASS__.'.ONLIVEONLYSHORTHELP', 'Page is published, but has been deleted from draft'),
2539
                );
2540
            } 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...
2541
                $flags['archived'] = array(
2542
                    'text' => _t(__CLASS__.'.ARCHIVEDPAGESHORT', 'Archived'),
2543
                    'title' => _t(__CLASS__.'.ARCHIVEDPAGEHELP', 'Page is removed from draft and live'),
2544
                );
2545
            } 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...
2546
                $flags['addedtodraft'] = array(
2547
                    'text' => _t(__CLASS__.'.ADDEDTODRAFTSHORT', 'Draft'),
2548
                    'title' => _t(__CLASS__.'.ADDEDTODRAFTHELP', "Page has not been published yet")
2549
                );
2550
            } 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...
2551
                $flags['modified'] = array(
2552
                    'text' => _t(__CLASS__.'.MODIFIEDONDRAFTSHORT', 'Modified'),
2553
                    'title' => _t(__CLASS__.'.MODIFIEDONDRAFTHELP', 'Page has unpublished changes'),
2554
                );
2555
            }
2556
2557
            $this->extend('updateStatusFlags', $flags);
2558
2559
            $this->_cache_statusFlags = $flags;
2560
        }
2561
2562
        return $this->_cache_statusFlags;
2563
    }
2564
2565
    /**
2566
     * getTreeTitle will return three <span> html DOM elements, an empty <span> with the class 'jstree-pageicon' in
2567
     * front, following by a <span> wrapping around its MenutTitle, then following by a <span> indicating its
2568
     * publication status.
2569
     *
2570
     * @return string An HTML string ready to be directly used in a template
2571
     */
2572
    public function getTreeTitle()
2573
    {
2574
        // Build the list of candidate children
2575
        $children = array();
2576
        $candidates = static::page_type_classes();
2577
        foreach ($this->allowedChildren() as $childClass) {
2578
            if (!in_array($childClass, $candidates)) {
2579
                continue;
2580
            }
2581
            $child = singleton($childClass);
2582
            if ($child->canCreate(null, array('Parent' => $this))) {
2583
                $children[$childClass] = $child->i18n_singular_name();
2584
            }
2585
        }
2586
        $flags = $this->getStatusFlags();
2587
        $treeTitle = sprintf(
2588
            "<span class=\"jstree-pageicon\"></span><span class=\"item\" data-allowedchildren=\"%s\">%s</span>",
2589
            Convert::raw2att(Convert::raw2json($children)),
2590
            Convert::raw2xml(str_replace(array("\n","\r"), "", $this->MenuTitle))
2591
        );
2592
        foreach ($flags as $class => $data) {
2593
            if (is_string($data)) {
2594
                $data = array('text' => $data);
2595
            }
2596
            $treeTitle .= sprintf(
2597
                "<span class=\"badge %s\"%s>%s</span>",
2598
                'status-' . Convert::raw2xml($class),
2599
                (isset($data['title'])) ? sprintf(' title="%s"', Convert::raw2xml($data['title'])) : '',
2600
                Convert::raw2xml($data['text'])
2601
            );
2602
        }
2603
2604
        return $treeTitle;
2605
    }
2606
2607
    /**
2608
     * Returns the page in the current page stack of the given level. Level(1) will return the main menu item that
2609
     * we're currently inside, etc.
2610
     *
2611
     * @param int $level
2612
     * @return SiteTree
2613
     */
2614
    public function Level($level)
2615
    {
2616
        $parent = $this;
2617
        $stack = array($parent);
2618
        while (($parent = $parent->Parent()) && $parent->exists()) {
2619
            array_unshift($stack, $parent);
2620
        }
2621
2622
        return isset($stack[$level-1]) ? $stack[$level-1] : null;
2623
    }
2624
2625
    /**
2626
     * Gets the depth of this page in the sitetree, where 1 is the root level
2627
     *
2628
     * @return int
2629
     */
2630
    public function getPageLevel()
2631
    {
2632
        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...
2633
            return 1 + $this->Parent()->getPageLevel();
2634
        }
2635
        return 1;
2636
    }
2637
2638
    /**
2639
     * Find the controller name by our convention of {$ModelClass}Controller
2640
     *
2641
     * @return string
2642
     */
2643
    public function getControllerName()
2644
    {
2645
        //default controller for SiteTree objects
2646
        $controller = ContentController::class;
2647
2648
        //go through the ancestry for this class looking for
2649
        $ancestry = ClassInfo::ancestry(static::class);
2650
        // loop over the array going from the deepest descendant (ie: the current class) to SiteTree
2651
        while ($class = array_pop($ancestry)) {
2652
            //we don't need to go any deeper than the SiteTree class
2653
            if ($class == SiteTree::class) {
2654
                break;
2655
            }
2656
            // If we have a class of "{$ClassName}Controller" then we found our controller
2657
            if (class_exists($candidate = sprintf('%sController', $class))) {
2658
                $controller = $candidate;
2659
                break;
2660
            } elseif (class_exists($candidate = sprintf('%s_Controller', $class))) {
2661
                // Support the legacy underscored filename, but raise a deprecation notice
2662
                Deprecation::notice(
2663
                    '5.0',
2664
                    'Underscored controller class names are deprecated. Use "MyController" instead of "My_Controller".',
2665
                    Deprecation::SCOPE_GLOBAL
2666
                );
2667
                $controller = $candidate;
2668
                break;
2669
            }
2670
        }
2671
2672
        return $controller;
2673
    }
2674
2675
    /**
2676
     * Return the CSS classes to apply to this node in the CMS tree.
2677
     *
2678
     * @return string
2679
     */
2680
    public function CMSTreeClasses()
2681
    {
2682
        $classes = sprintf('class-%s', static::class);
2683
        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...
2684
            $classes .= " BrokenLink";
2685
        }
2686
2687
        if (!$this->canAddChildren()) {
2688
            $classes .= " nochildren";
2689
        }
2690
2691
        if (!$this->canEdit() && !$this->canAddChildren()) {
2692
            if (!$this->canView()) {
2693
                $classes .= " disabled";
2694
            } else {
2695
                $classes .= " edit-disabled";
2696
            }
2697
        }
2698
2699
        if (!$this->ShowInMenus) {
2700
            $classes .= " notinmenu";
2701
        }
2702
2703
        return $classes;
2704
    }
2705
2706
    /**
2707
     * Stops extendCMSFields() being called on getCMSFields(). This is useful when you need access to fields added by
2708
     * subclasses of SiteTree in a extension. Call before calling parent::getCMSFields(), and reenable afterwards.
2709
     */
2710
    public static function disableCMSFieldsExtensions()
2711
    {
2712
        self::$runCMSFieldsExtensions = false;
2713
    }
2714
2715
    /**
2716
     * Reenables extendCMSFields() being called on getCMSFields() after it has been disabled by
2717
     * disableCMSFieldsExtensions().
2718
     */
2719
    public static function enableCMSFieldsExtensions()
2720
    {
2721
        self::$runCMSFieldsExtensions = true;
2722
    }
2723
2724
    public function providePermissions()
2725
    {
2726
        return array(
2727
            'SITETREE_GRANT_ACCESS' => array(
2728
                'name' => _t(__CLASS__.'.PERMISSION_GRANTACCESS_DESCRIPTION', 'Manage access rights for content'),
2729
                'help' => _t(__CLASS__.'.PERMISSION_GRANTACCESS_HELP', 'Allow setting of page-specific access restrictions in the "Pages" section.'),
2730
                'category' => _t('SilverStripe\\Security\\Permission.PERMISSIONS_CATEGORY', 'Roles and access permissions'),
2731
                'sort' => 100
2732
            ),
2733
            'SITETREE_VIEW_ALL' => array(
2734
                'name' => _t(__CLASS__.'.VIEW_ALL_DESCRIPTION', 'View any page'),
2735
                'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'),
2736
                'sort' => -100,
2737
                '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')
2738
            ),
2739
            'SITETREE_EDIT_ALL' => array(
2740
                'name' => _t(__CLASS__.'.EDIT_ALL_DESCRIPTION', 'Edit any page'),
2741
                'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'),
2742
                'sort' => -50,
2743
                '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')
2744
            ),
2745
            'SITETREE_REORGANISE' => array(
2746
                'name' => _t(__CLASS__.'.REORGANISE_DESCRIPTION', 'Change site structure'),
2747
                'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'),
2748
                'help' => _t(__CLASS__.'.REORGANISE_HELP', 'Rearrange pages in the site tree through drag&drop.'),
2749
                'sort' => 100
2750
            ),
2751
            'VIEW_DRAFT_CONTENT' => array(
2752
                'name' => _t(__CLASS__.'.VIEW_DRAFT_CONTENT', 'View draft content'),
2753
                'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'),
2754
                '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.'),
2755
                'sort' => 100
2756
            )
2757
        );
2758
    }
2759
2760
    /**
2761
     * Default singular name for page / sitetree
2762
     *
2763
     * @return string
2764
     */
2765 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...
2766
    {
2767
        $base = in_array(static::class, [Page::class, self::class]);
2768
        if ($base) {
2769
            return $this->stat('base_singular_name');
2770
        }
2771
        return parent::singular_name();
2772
    }
2773
2774
    /**
2775
     * Default plural name for page / sitetree
2776
     *
2777
     * @return string
2778
     */
2779 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...
2780
    {
2781
        $base = in_array(static::class, [Page::class, self::class]);
2782
        if ($base) {
2783
            return $this->stat('base_plural_name');
2784
        }
2785
        return parent::plural_name();
2786
    }
2787
2788
    /**
2789
     * Get description for this page type
2790
     *
2791
     * @return string|null
2792
     */
2793
    public function classDescription()
2794
    {
2795
        $base = in_array(static::class, [Page::class, self::class]);
2796
        if ($base) {
2797
            return $this->stat('base_description');
2798
        }
2799
        return $this->stat('description');
2800
    }
2801
2802
    /**
2803
     * Get localised description for this page
2804
     *
2805
     * @return string|null
2806
     */
2807
    public function i18n_classDescription()
2808
    {
2809
        $description = $this->classDescription();
2810
        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...
2811
            return _t(static::class.'.DESCRIPTION', $description);
2812
        }
2813
        return null;
2814
    }
2815
2816
    /**
2817
     * Overloaded to also provide entities for 'Page' class which is usually located in custom code, hence textcollector
2818
     * picks it up for the wrong folder.
2819
     *
2820
     * @return array
2821
     */
2822
    public function provideI18nEntities()
2823
    {
2824
        $entities = parent::provideI18nEntities();
2825
2826
        // Add optional description
2827
        $description = $this->classDescription();
2828
        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...
2829
            $entities[static::class . '.DESCRIPTION'] = $description;
2830
        }
2831
        return $entities;
2832
    }
2833
2834
    /**
2835
     * Returns 'root' if the current page has no parent, or 'subpage' otherwise
2836
     *
2837
     * @return string
2838
     */
2839
    public function getParentType()
2840
    {
2841
        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...
2842
    }
2843
2844
    /**
2845
     * Clear the permissions cache for SiteTree
2846
     */
2847
    public static function reset()
2848
    {
2849
        $permissions = static::getPermissionChecker();
2850
        if ($permissions instanceof InheritedPermissions) {
2851
            $permissions->clearCache();
2852
        }
2853
    }
2854
2855
    /**
2856
     * Update dependant pages
2857
     */
2858
    protected function updateDependentPages()
2859
    {
2860
        // Need to flush cache to avoid outdated versionnumber references
2861
        $this->flushCache();
2862
2863
        // Need to mark pages depending to this one as broken
2864
        $dependentPages = $this->DependentPages();
2865
        if ($dependentPages) {
2866
            foreach ($dependentPages as $page) {
2867
                // $page->write() calls syncLinkTracking, which does all the hard work for us.
2868
                $page->write();
2869
            }
2870
        }
2871
    }
2872
}
2873