Completed
Pull Request — master (#1811)
by Damian
02:29
created

SiteTree::canDelete()   B

Complexity

Conditions 5
Paths 8

Size

Total Lines 25
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 8.439
c 0
b 0
f 0
cc 5
eloc 12
nc 8
nop 1
1
<?php
2
3
namespace SilverStripe\CMS\Model;
4
5
use Page;
6
use SilverStripe\CampaignAdmin\AddToCampaignHandler_FormAction;
7
use SilverStripe\Core\Injector\Injector;
8
use SilverStripe\ORM\CMSPreviewable;
9
use SilverStripe\CMS\Controllers\CMSPageEditController;
10
use SilverStripe\CMS\Controllers\ContentController;
11
use SilverStripe\CMS\Controllers\ModelAsController;
12
use SilverStripe\CMS\Controllers\RootURLController;
13
use SilverStripe\CMS\Forms\SiteTreeURLSegmentField;
14
use SilverStripe\Control\ContentNegotiator;
15
use SilverStripe\Control\Controller;
16
use SilverStripe\Control\Director;
17
use SilverStripe\Control\RequestHandler;
18
use SilverStripe\Core\ClassInfo;
19
use SilverStripe\Core\Config\Config;
20
use SilverStripe\Core\Convert;
21
use SilverStripe\Core\Resettable;
22
use SilverStripe\Dev\Deprecation;
23
use SilverStripe\Forms\CheckboxField;
24
use SilverStripe\Forms\CompositeField;
25
use SilverStripe\Forms\DropdownField;
26
use SilverStripe\Forms\FieldGroup;
27
use SilverStripe\Forms\FieldList;
28
use SilverStripe\Forms\FormAction;
29
use SilverStripe\Forms\FormField;
30
use SilverStripe\Forms\GridField\GridField;
31
use SilverStripe\Forms\GridField\GridFieldDataColumns;
32
use SilverStripe\Forms\HTMLEditor\HTMLEditorField;
33
use SilverStripe\Forms\ListboxField;
34
use SilverStripe\Forms\LiteralField;
35
use SilverStripe\Forms\OptionsetField;
36
use SilverStripe\Forms\Tab;
37
use SilverStripe\Forms\TabSet;
38
use SilverStripe\Forms\TextareaField;
39
use SilverStripe\Forms\TextField;
40
use SilverStripe\Forms\ToggleCompositeField;
41
use SilverStripe\Forms\TreeDropdownField;
42
use SilverStripe\i18n\i18n;
43
use SilverStripe\i18n\i18nEntityProvider;
44
use SilverStripe\ORM\ArrayList;
45
use SilverStripe\ORM\DataList;
46
use SilverStripe\ORM\DataObject;
47
use SilverStripe\ORM\DB;
48
use SilverStripe\ORM\HiddenClass;
49
use SilverStripe\ORM\Hierarchy\Hierarchy;
50
use SilverStripe\ORM\Hierarchy\MarkedSet;
51
use SilverStripe\ORM\ManyManyList;
52
use SilverStripe\ORM\ValidationResult;
53
use SilverStripe\Security\InheritedPermissions;
54
use SilverStripe\Versioned\Versioned;
55
use SilverStripe\Security\Group;
56
use SilverStripe\Security\Member;
57
use SilverStripe\Security\Permission;
58
use SilverStripe\Security\PermissionProvider;
59
use SilverStripe\SiteConfig\SiteConfig;
60
use SilverStripe\View\ArrayData;
61
use SilverStripe\View\Parsers\ShortcodeParser;
62
use SilverStripe\View\Parsers\URLSegmentFilter;
63
use SilverStripe\View\SSViewer;
64
use Subsite;
65
66
/**
67
 * Basic data-object representing all pages within the site tree. All page types that live within the hierarchy should
68
 * inherit from this. In addition, it contains a number of static methods for querying the site tree and working with
69
 * draft and published states.
70
 *
71
 * <h2>URLs</h2>
72
 * A page is identified during request handling via its "URLSegment" database column. As pages can be nested, the full
73
 * path of a URL might contain multiple segments. Each segment is stored in its filtered representation (through
74
 * {@link URLSegmentFilter}). The full path is constructed via {@link Link()}, {@link RelativeLink()} and
75
 * {@link AbsoluteLink()}. You can allow these segments to contain multibyte characters through
76
 * {@link URLSegmentFilter::$default_allow_multibyte}.
77
 *
78
 * @property string URLSegment
79
 * @property string Title
80
 * @property string MenuTitle
81
 * @property string Content HTML content of the page.
82
 * @property string MetaDescription
83
 * @property string ExtraMeta
84
 * @property string ShowInMenus
85
 * @property string ShowInSearch
86
 * @property string Sort Integer value denoting the sort order.
87
 * @property string ReportClass
88
 * @property string CanViewType Type of restriction for viewing this object.
89
 * @property string CanEditType Type of restriction for editing this object.
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
 */
99
class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvider, CMSPreviewable
100
{
101
102
    /**
103
     * Indicates what kind of children this page type can have.
104
     * This can be an array of allowed child classes, or the string "none" -
105
     * indicating that this page type can't have children.
106
     * If a classname is prefixed by "*", such as "*Page", then only that
107
     * class is allowed - no subclasses. Otherwise, the class and all its
108
     * subclasses are allowed.
109
     * To control allowed children on root level (no parent), use {@link $can_be_root}.
110
     *
111
     * Note that this setting is cached when used in the CMS, use the "flush" query parameter to clear it.
112
     *
113
     * @config
114
     * @var array
115
     */
116
    private static $allowed_children = [
117
        self::class
118
    ];
119
120
    /**
121
     * The default child class for this page.
122
     * Note: Value might be cached, see {@link $allowed_chilren}.
123
     *
124
     * @config
125
     * @var string
126
     */
127
    private static $default_child = "Page";
128
129
    /**
130
     * Default value for SiteTree.ClassName enum
131
     * {@see DBClassName::getDefault}
132
     *
133
     * @config
134
     * @var string
135
     */
136
    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...
137
138
    /**
139
     * The default parent class for this page.
140
     * Note: Value might be cached, see {@link $allowed_chilren}.
141
     *
142
     * @config
143
     * @var string
144
     */
145
    private static $default_parent = null;
146
147
    /**
148
     * Controls whether a page can be in the root of the site tree.
149
     * Note: Value might be cached, see {@link $allowed_chilren}.
150
     *
151
     * @config
152
     * @var bool
153
     */
154
    private static $can_be_root = true;
155
156
    /**
157
     * List of permission codes a user can have to allow a user to create a page of this type.
158
     * Note: Value might be cached, see {@link $allowed_chilren}.
159
     *
160
     * @config
161
     * @var array
162
     */
163
    private static $need_permission = null;
164
165
    /**
166
     * If you extend a class, and don't want to be able to select the old class
167
     * in the cms, set this to the old class name. Eg, if you extended Product
168
     * to make ImprovedProduct, then you would set $hide_ancestor to Product.
169
     *
170
     * @config
171
     * @var string
172
     */
173
    private static $hide_ancestor = null;
174
175
    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...
176
        "URLSegment" => "Varchar(255)",
177
        "Title" => "Varchar(255)",
178
        "MenuTitle" => "Varchar(100)",
179
        "Content" => "HTMLText",
180
        "MetaDescription" => "Text",
181
        "ExtraMeta" => "HTMLFragment(['whitelist' => ['meta', 'link']])",
182
        "ShowInMenus" => "Boolean",
183
        "ShowInSearch" => "Boolean",
184
        "Sort" => "Int",
185
        "HasBrokenFile" => "Boolean",
186
        "HasBrokenLink" => "Boolean",
187
        "ReportClass" => "Varchar",
188
        "CanViewType" => "Enum('Anyone, LoggedInUsers, OnlyTheseUsers, Inherit', 'Inherit')",
189
        "CanEditType" => "Enum('LoggedInUsers, OnlyTheseUsers, Inherit', 'Inherit')",
190
    );
191
192
    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...
193
        "URLSegment" => true,
194
    );
195
196
    private static $many_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...
197
        "ViewerGroups" => Group::class,
198
        "EditorGroups" => Group::class,
199
    );
200
201
    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...
202
        "VirtualPages" => "SilverStripe\\CMS\\Model\\VirtualPage.CopyContentFrom"
203
    );
204
205
    private static $owned_by = array(
206
        "VirtualPages"
207
    );
208
209
    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...
210
        "Breadcrumbs" => "HTMLFragment",
211
        "LastEdited" => "Datetime",
212
        "Created" => "Datetime",
213
        'Link' => 'Text',
214
        'RelativeLink' => 'Text',
215
        'AbsoluteLink' => 'Text',
216
        'CMSEditLink' => 'Text',
217
        'TreeTitle' => 'HTMLFragment',
218
        'MetaTags' => 'HTMLFragment',
219
    );
220
221
    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...
222
        "ShowInMenus" => 1,
223
        "ShowInSearch" => 1,
224
        "CanViewType" => "Inherit",
225
        "CanEditType" => "Inherit"
226
    );
227
228
    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...
229
230
    private static $versioning = array(
231
        "Stage",  "Live"
232
    );
233
234
    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...
235
236
    /**
237
     * If this is false, the class cannot be created in the CMS by regular content authors, only by ADMINs.
238
     * @var boolean
239
     * @config
240
     */
241
    private static $can_create = true;
242
243
    /**
244
     * Icon to use in the CMS page tree. This should be the full filename, relative to the webroot.
245
     * Also supports custom CSS rule contents (applied to the correct selector for the tree UI implementation).
246
     *
247
     * @see CMSMain::generateTreeStylingCSS()
248
     * @config
249
     * @var string
250
     */
251
    private static $icon = null;
252
253
    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...
254
        Hierarchy::class,
255
        Versioned::class,
256
        SiteTreeLinkTracking::class,
257
    ];
258
259
    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...
260
        'Title',
261
        'Content',
262
    );
263
264
    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...
265
        'URLSegment' => 'URL'
266
    );
267
268
    /**
269
     * @config
270
     */
271
    private static $nested_urls = true;
272
273
    /**
274
     * @config
275
    */
276
    private static $create_default_pages = true;
277
278
    /**
279
     * This controls whether of not extendCMSFields() is called by getCMSFields.
280
     */
281
    private static $runCMSFieldsExtensions = true;
282
283
    /**
284
     * @config
285
     * @var boolean
286
     */
287
    private static $enforce_strict_hierarchy = true;
288
289
    /**
290
     * The value used for the meta generator tag. Leave blank to omit the tag.
291
     *
292
     * @config
293
     * @var string
294
     */
295
    private static $meta_generator = 'SilverStripe - http://silverstripe.org';
296
297
    protected $_cache_statusFlags = null;
298
299
    /**
300
     * Plural form for SiteTree / Page classes. Not inherited by subclasses.
301
     *
302
     * @config
303
     * @var string
304
     */
305
    private static $base_plural_name = 'Pages';
306
307
    /**
308
     * Plural form for SiteTree / Page classes. Not inherited by subclasses.
309
     *
310
     * @config
311
     * @var string
312
     */
313
    private static $base_singular_name = 'Page';
314
315
    /**
316
     * Description of the class functionality, typically shown to a user
317
     * when selecting which page type to create. Translated through {@link provideI18nEntities()}.
318
     *
319
     * @see SiteTree::classDescription()
320
     * @see SiteTree::i18n_classDescription()
321
     *
322
     * @config
323
     * @var string
324
     */
325
    private static $description = null;
326
327
    /**
328
     * Description for Page and SiteTree classes, but not inherited by subclasses.
329
     * override SiteTree::$description in subclasses instead.
330
     *
331
     * @see SiteTree::classDescription()
332
     * @see SiteTree::i18n_classDescription()
333
     *
334
     * @config
335
     * @var string
336
     */
337
    private static $base_description = 'Generic content page';
338
339
    /**
340
     * Fetches the {@link SiteTree} object that maps to a link.
341
     *
342
     * If you have enabled {@link SiteTree::config()->nested_urls} on this site, then you can use a nested link such as
343
     * "about-us/staff/", and this function will traverse down the URL chain and grab the appropriate link.
344
     *
345
     * Note that if no model can be found, this method will fall over to a extended alternateGetByLink method provided
346
     * by a extension attached to {@link SiteTree}
347
     *
348
     * @param string $link  The link of the page to search for
349
     * @param bool   $cache True (default) to use caching, false to force a fresh search from the database
350
     * @return SiteTree
351
     */
352
    public static function get_by_link($link, $cache = true)
353
    {
354
        if (trim($link, '/')) {
355
            $link = trim(Director::makeRelative($link), '/');
356
        } else {
357
            $link = RootURLController::get_homepage_link();
358
        }
359
360
        $parts = preg_split('|/+|', $link);
361
362
        // Grab the initial root level page to traverse down from.
363
        $URLSegment = array_shift($parts);
364
        $conditions = array('"SiteTree"."URLSegment"' => rawurlencode($URLSegment));
365
        if (self::config()->nested_urls) {
366
            $conditions[] = array('"SiteTree"."ParentID"' => 0);
367
        }
368
        /** @var SiteTree $sitetree */
369
        $sitetree = DataObject::get_one(self::class, $conditions, $cache);
370
371
        /// Fall back on a unique URLSegment for b/c.
372
        if (!$sitetree
373
            && self::config()->nested_urls
374
            && $sitetree = DataObject::get_one(self::class, array(
375
                '"SiteTree"."URLSegment"' => $URLSegment
376
            ), $cache)
377
        ) {
378
            return $sitetree;
379
        }
380
381
        // Attempt to grab an alternative page from extensions.
382
        if (!$sitetree) {
383
            $parentID = self::config()->nested_urls ? 0 : null;
384
385 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...
386
                foreach ($alternatives as $alternative) {
387
                    if ($alternative) {
388
                        $sitetree = $alternative;
389
                    }
390
                }
391
            }
392
393
            if (!$sitetree) {
394
                return null;
395
            }
396
        }
397
398
        // Check if we have any more URL parts to parse.
399
        if (!self::config()->nested_urls || !count($parts)) {
400
            return $sitetree;
401
        }
402
403
        // Traverse down the remaining URL segments and grab the relevant SiteTree objects.
404
        foreach ($parts as $segment) {
405
            $next = DataObject::get_one(
406
                self::class,
407
                array(
408
                    '"SiteTree"."URLSegment"' => $segment,
409
                    '"SiteTree"."ParentID"' => $sitetree->ID
410
                ),
411
                $cache
412
            );
413
414
            if (!$next) {
415
                $parentID = (int) $sitetree->ID;
416
417 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...
418
                    foreach ($alternatives as $alternative) {
419
                        if ($alternative) {
420
                            $next = $alternative;
421
                        }
422
                    }
423
                }
424
425
                if (!$next) {
426
                    return null;
427
                }
428
            }
429
430
            $sitetree->destroy();
431
            $sitetree = $next;
432
        }
433
434
        return $sitetree;
435
    }
436
437
    /**
438
     * Return a subclass map of SiteTree that shouldn't be hidden through {@link SiteTree::$hide_ancestor}
439
     *
440
     * @return array
441
     */
442
    public static function page_type_classes()
443
    {
444
        $classes = ClassInfo::getValidSubClasses();
445
446
        $baseClassIndex = array_search(self::class, $classes);
447
        if ($baseClassIndex !== false) {
448
            unset($classes[$baseClassIndex]);
449
        }
450
451
        $kill_ancestors = array();
452
453
        // figure out if there are any classes we don't want to appear
454
        foreach ($classes as $class) {
455
            $instance = singleton($class);
456
457
            // do any of the progeny want to hide an ancestor?
458
            if ($ancestor_to_hide = $instance->stat('hide_ancestor')) {
459
                // note for killing later
460
                $kill_ancestors[] = $ancestor_to_hide;
461
            }
462
        }
463
464
        // If any of the descendents don't want any of the elders to show up, cruelly render the elders surplus to
465
        // requirements
466
        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...
467
            $kill_ancestors = array_unique($kill_ancestors);
468
            foreach ($kill_ancestors as $mark) {
469
                // unset from $classes
470
                $idx = array_search($mark, $classes, true);
471
                if ($idx !== false) {
472
                    unset($classes[$idx]);
473
                }
474
            }
475
        }
476
477
        return $classes;
478
    }
479
480
    /**
481
     * Replace a "[sitetree_link id=n]" shortcode with a link to the page with the corresponding ID.
482
     *
483
     * @param array      $arguments
484
     * @param string     $content
485
     * @param ShortcodeParser $parser
486
     * @return string
487
     */
488
    public static function link_shortcode_handler($arguments, $content = null, $parser = null)
489
    {
490
        if (!isset($arguments['id']) || !is_numeric($arguments['id'])) {
491
            return null;
492
        }
493
494
        /** @var SiteTree $page */
495
        if (!($page = DataObject::get_by_id(self::class, $arguments['id']))         // Get the current page by ID.
496
            && !($page = Versioned::get_latest_version(self::class, $arguments['id'])) // Attempt link to old version.
497
        ) {
498
             return null; // There were no suitable matches at all.
499
        }
500
501
        /** @var SiteTree $page */
502
        $link = Convert::raw2att($page->Link());
503
504
        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...
505
            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...
506
        } else {
507
            return $link;
508
        }
509
    }
510
511
    /**
512
     * Return the link for this {@link SiteTree} object, with the {@link Director::baseURL()} included.
513
     *
514
     * @param string $action Optional controller action (method).
515
     *                       Note: URI encoding of this parameter is applied automatically through template casting,
516
     *                       don't encode the passed parameter. Please use {@link Controller::join_links()} instead to
517
     *                       append GET parameters.
518
     * @return string
519
     */
520
    public function Link($action = null)
521
    {
522
        return Controller::join_links(Director::baseURL(), $this->RelativeLink($action));
523
    }
524
525
    /**
526
     * Get the absolute URL for this page, including protocol and host.
527
     *
528
     * @param string $action See {@link Link()}
529
     * @return string
530
     */
531
    public function AbsoluteLink($action = null)
532
    {
533
        if ($this->hasMethod('alternateAbsoluteLink')) {
534
            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...
535
        } else {
536
            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 536 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...
537
        }
538
    }
539
540
    /**
541
     * Base link used for previewing. Defaults to absolute URL, in order to account for domain changes, e.g. on multi
542
     * site setups. Does not contain hints about the stage, see {@link SilverStripeNavigator} for details.
543
     *
544
     * @param string $action See {@link Link()}
545
     * @return string
546
     */
547
    public function PreviewLink($action = null)
548
    {
549
        if ($this->hasMethod('alternatePreviewLink')) {
550
            Deprecation::notice('5.0', 'Use updatePreviewLink or override PreviewLink method');
551
            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...
552
        }
553
554
        $link = $this->AbsoluteLink($action);
555
        $this->extend('updatePreviewLink', $link, $action);
556
        return $link;
557
    }
558
559
    public function getMimeType()
560
    {
561
        return 'text/html';
562
    }
563
564
    /**
565
     * Return the link for this {@link SiteTree} object relative to the SilverStripe root.
566
     *
567
     * By default, if this page is the current home page, and there is no action specified then this will return a link
568
     * to the root of the site. However, if you set the $action parameter to TRUE then the link will not be rewritten
569
     * and returned in its full form.
570
     *
571
     * @uses RootURLController::get_homepage_link()
572
     *
573
     * @param string $action See {@link Link()}
574
     * @return string
575
     */
576
    public function RelativeLink($action = null)
577
    {
578
        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...
579
            $parent = $this->Parent();
580
            // If page is removed select parent from version history (for archive page view)
581
            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...
582
                $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...
583
            }
584
            $base = $parent->RelativeLink($this->URLSegment);
585
        } 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...
586
            // Unset base for root-level homepages.
587
            // Note: Homepages with action parameters (or $action === true)
588
            // need to retain their URLSegment.
589
            $base = null;
590
        } else {
591
            $base = $this->URLSegment;
592
        }
593
594
        $this->extend('updateRelativeLink', $base, $action);
595
596
        // Legacy support: If $action === true, retain URLSegment for homepages,
597
        // but don't append any action
598
        if ($action === true) {
599
            $action = null;
600
        }
601
602
        return Controller::join_links($base, '/', $action);
603
    }
604
605
    /**
606
     * Get the absolute URL for this page on the Live site.
607
     *
608
     * @param bool $includeStageEqualsLive Whether to append the URL with ?stage=Live to force Live mode
609
     * @return string
610
     */
611
    public function getAbsoluteLiveLink($includeStageEqualsLive = true)
612
    {
613
        $oldReadingMode = Versioned::get_reading_mode();
614
        Versioned::set_stage(Versioned::LIVE);
615
        /** @var SiteTree $live */
616
        $live = Versioned::get_one_by_stage(self::class, Versioned::LIVE, array(
617
            '"SiteTree"."ID"' => $this->ID
618
        ));
619
        if ($live) {
620
            $link = $live->AbsoluteLink();
621
            if ($includeStageEqualsLive) {
622
                $link = Controller::join_links($link, '?stage=Live');
623
            }
624
        } else {
625
            $link = null;
626
        }
627
628
        Versioned::set_reading_mode($oldReadingMode);
629
        return $link;
630
    }
631
632
    /**
633
     * Generates a link to edit this page in the CMS.
634
     *
635
     * @return string
636
     */
637
    public function CMSEditLink()
638
    {
639
        $link = Controller::join_links(
640
            CMSPageEditController::singleton()->Link('show'),
641
            $this->ID
642
        );
643
        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 643 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...
644
    }
645
646
647
    /**
648
     * Return a CSS identifier generated from this page's link.
649
     *
650
     * @return string The URL segment
651
     */
652
    public function ElementName()
653
    {
654
        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...
655
    }
656
657
    /**
658
     * Returns true if this is the currently active page being used to handle this request.
659
     *
660
     * @return bool
661
     */
662
    public function isCurrent()
663
    {
664
        $currentPage = Director::get_current_page();
665
        if ($currentPage instanceof ContentController) {
666
            $currentPage = $currentPage->data();
667
        }
668
        if ($currentPage instanceof SiteTree) {
669
            return $currentPage === $this || $currentPage->ID === $this->ID;
670
        }
671
        return false;
672
    }
673
674
    /**
675
     * Check if this page is in the currently active section (e.g. it is either current or one of its children is
676
     * currently being viewed).
677
     *
678
     * @return bool
679
     */
680
    public function isSection()
681
    {
682
        return $this->isCurrent() || (
683
            Director::get_current_page() instanceof SiteTree && in_array($this->ID, Director::get_current_page()->getAncestors()->column())
684
        );
685
    }
686
687
    /**
688
     * Check if the parent of this page has been removed (or made otherwise unavailable), and is still referenced by
689
     * this child. Any such orphaned page may still require access via the CMS, but should not be shown as accessible
690
     * to external users.
691
     *
692
     * @return bool
693
     */
694
    public function isOrphaned()
695
    {
696
        // Always false for root pages
697
        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...
698
            return false;
699
        }
700
701
        // Parent must exist and not be an orphan itself
702
        $parent = $this->Parent();
703
        return !$parent || !$parent->exists() || $parent->isOrphaned();
704
    }
705
706
    /**
707
     * Return "link" or "current" depending on if this is the {@link SiteTree::isCurrent()} current page.
708
     *
709
     * @return string
710
     */
711
    public function LinkOrCurrent()
712
    {
713
        return $this->isCurrent() ? 'current' : 'link';
714
    }
715
716
    /**
717
     * Return "link" or "section" depending on if this is the {@link SiteTree::isSeciton()} current section.
718
     *
719
     * @return string
720
     */
721
    public function LinkOrSection()
722
    {
723
        return $this->isSection() ? 'section' : 'link';
724
    }
725
726
    /**
727
     * Return "link", "current" or "section" depending on if this page is the current page, or not on the current page
728
     * but in the current section.
729
     *
730
     * @return string
731
     */
732
    public function LinkingMode()
733
    {
734
        if ($this->isCurrent()) {
735
            return 'current';
736
        } elseif ($this->isSection()) {
737
            return 'section';
738
        } else {
739
            return 'link';
740
        }
741
    }
742
743
    /**
744
     * Check if this page is in the given current section.
745
     *
746
     * @param string $sectionName Name of the section to check
747
     * @return bool True if we are in the given section
748
     */
749
    public function InSection($sectionName)
750
    {
751
        $page = Director::get_current_page();
752
        while ($page && $page->exists()) {
753
            if ($sectionName == $page->URLSegment) {
754
                return true;
755
            }
756
            $page = $page->Parent();
757
        }
758
        return false;
759
    }
760
761
    /**
762
     * Reset Sort on duped page
763
     *
764
     * @param SiteTree $original
765
     * @param bool $doWrite
766
     */
767
    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...
768
    {
769
        $this->Sort = 0;
770
    }
771
772
    /**
773
     * Duplicates each child of this node recursively and returns the top-level duplicate node.
774
     *
775
     * @return static The duplicated object
776
     */
777
    public function duplicateWithChildren()
778
    {
779
        /** @var SiteTree $clone */
780
        $clone = $this->duplicate();
781
        $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...
782
783
        if ($children) {
784
            /** @var SiteTree $child */
785
            $sort = 0;
786
            foreach ($children as $child) {
787
                $childClone = $child->duplicateWithChildren();
788
                $childClone->ParentID = $clone->ID;
789
                //retain sort order by manually setting sort values
790
                $childClone->Sort = ++$sort;
791
                $childClone->write();
792
            }
793
        }
794
795
        return $clone;
796
    }
797
798
    /**
799
     * Duplicate this node and its children as a child of the node with the given ID
800
     *
801
     * @param int $id ID of the new node's new parent
802
     */
803
    public function duplicateAsChild($id)
804
    {
805
        /** @var SiteTree $newSiteTree */
806
        $newSiteTree = $this->duplicate();
807
        $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...
808
        $newSiteTree->Sort = 0;
809
        $newSiteTree->write();
810
    }
811
812
    /**
813
     * Return a breadcrumb trail to this page. Excludes "hidden" pages (with ShowInMenus=0) by default.
814
     *
815
     * @param int $maxDepth The maximum depth to traverse.
816
     * @param boolean $unlinked Whether to link page titles.
817
     * @param boolean|string $stopAtPageType ClassName of a page to stop the upwards traversal.
818
     * @param boolean $showHidden Include pages marked with the attribute ShowInMenus = 0
819
     * @return string The breadcrumb trail.
820
     */
821
    public function Breadcrumbs($maxDepth = 20, $unlinked = false, $stopAtPageType = false, $showHidden = false)
822
    {
823
        $pages = $this->getBreadcrumbItems($maxDepth, $stopAtPageType, $showHidden);
824
        $template = new SSViewer('BreadcrumbsTemplate');
825
        return $template->process($this->customise(new ArrayData(array(
826
            "Pages" => $pages,
827
            "Unlinked" => $unlinked
828
        ))));
829
    }
830
831
832
    /**
833
     * Returns a list of breadcrumbs for the current page.
834
     *
835
     * @param int $maxDepth The maximum depth to traverse.
836
     * @param boolean|string $stopAtPageType ClassName of a page to stop the upwards traversal.
837
     * @param boolean $showHidden Include pages marked with the attribute ShowInMenus = 0
838
     *
839
     * @return ArrayList
840
    */
841
    public function getBreadcrumbItems($maxDepth = 20, $stopAtPageType = false, $showHidden = false)
842
    {
843
        $page = $this;
844
        $pages = array();
845
846
        while ($page
847
            && $page->exists()
848
            && (!$maxDepth || count($pages) < $maxDepth)
849
            && (!$stopAtPageType || $page->ClassName != $stopAtPageType)
850
        ) {
851
            if ($showHidden || $page->ShowInMenus || ($page->ID == $this->ID)) {
852
                $pages[] = $page;
853
            }
854
855
            $page = $page->Parent();
856
        }
857
858
        return new ArrayList(array_reverse($pages));
859
    }
860
861
862
    /**
863
     * Make this page a child of another page.
864
     *
865
     * If the parent page does not exist, resolve it to a valid ID before updating this page's reference.
866
     *
867
     * @param SiteTree|int $item Either the parent object, or the parent ID
868
     */
869
    public function setParent($item)
870
    {
871
        if (is_object($item)) {
872
            if (!$item->exists()) {
873
                $item->write();
874
            }
875
            $this->setField("ParentID", $item->ID);
876
        } else {
877
            $this->setField("ParentID", $item);
878
        }
879
    }
880
881
    /**
882
     * Get the parent of this page.
883
     *
884
     * @return SiteTree Parent of this page
885
     */
886
    public function getParent()
887
    {
888
        if ($parentID = $this->getField("ParentID")) {
889
            return DataObject::get_by_id(self::class, $parentID);
890
        }
891
        return null;
892
    }
893
894
    /**
895
     * Return a string of the form "parent - page" or "grandparent - parent - page" using page titles
896
     *
897
     * @param int $level The maximum amount of levels to traverse.
898
     * @param string $separator Seperating string
899
     * @return string The resulting string
900
     */
901
    public function NestedTitle($level = 2, $separator = " - ")
902
    {
903
        $item = $this;
904
        $parts = [];
905
        while ($item && $level > 0) {
906
            $parts[] = $item->Title;
907
            $item = $item->getParent();
908
            $level--;
909
        }
910
        return implode($separator, array_reverse($parts));
911
    }
912
913
    /**
914
     * This function should return true if the current user can execute this action. It can be overloaded to customise
915
     * the security model for an application.
916
     *
917
     * Slightly altered from parent behaviour in {@link DataObject->can()}:
918
     * - Checks for existence of a method named "can<$perm>()" on the object
919
     * - Calls decorators and only returns for FALSE "vetoes"
920
     * - Falls back to {@link Permission::check()}
921
     * - Does NOT check for many-many relations named "Can<$perm>"
922
     *
923
     * @uses DataObjectDecorator->can()
924
     *
925
     * @param string $perm The permission to be checked, such as 'View'
926
     * @param Member $member The member whose permissions need checking. Defaults to the currently logged in user.
927
     * @param array $context Context argument for canCreate()
928
     * @return bool True if the the member is allowed to do the given action
929
     */
930
    public function can($perm, $member = null, $context = array())
931
    {
932
        if (!$member) {
933
            $member = Member::currentUser();
934
        }
935
936
        if ($member && Permission::checkMember($member, "ADMIN")) {
937
            return true;
938
        }
939
940
        if (is_string($perm) && method_exists($this, 'can' . ucfirst($perm))) {
941
            $method = 'can' . ucfirst($perm);
942
            return $this->$method($member);
943
        }
944
945
        $results = $this->extend('can', $member);
946
        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...
947
            if (!min($results)) {
948
                return false;
949
            }
950
        }
951
952
        return ($member && Permission::checkMember($member, $perm));
953
    }
954
955
    /**
956
     * This function should return true if the current user can add children to this page. It can be overloaded to
957
     * customise the security model for an application.
958
     *
959
     * Denies permission if any of the following conditions is true:
960
     * - alternateCanAddChildren() on a extension returns false
961
     * - canEdit() is not granted
962
     * - There are no classes defined in {@link $allowed_children}
963
     *
964
     * @uses SiteTreeExtension->canAddChildren()
965
     * @uses canEdit()
966
     * @uses $allowed_children
967
     *
968
     * @param Member|int $member
969
     * @return bool True if the current user can add children
970
     */
971
    public function canAddChildren($member = null)
972
    {
973
        // Disable adding children to archived pages
974
        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...
975
            return false;
976
        }
977
978
        if (!$member) {
979
            $member = Member::currentUser();
980
        }
981
982
        // Standard mechanism for accepting permission changes from extensions
983
        $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...
984
        if ($extended !== null) {
985
            return $extended;
986
        }
987
988
        // Default permissions
989
        if ($member && Permission::checkMember($member, "ADMIN")) {
990
            return true;
991
        }
992
993
        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 971 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...
994
    }
995
996
    /**
997
     * This function should return true if the current user can view this page. It can be overloaded to customise the
998
     * security model for an application.
999
     *
1000
     * Denies permission if any of the following conditions is true:
1001
     * - canView() on any extension returns false
1002
     * - "CanViewType" directive is set to "Inherit" and any parent page return false for canView()
1003
     * - "CanViewType" directive is set to "LoggedInUsers" and no user is logged in
1004
     * - "CanViewType" directive is set to "OnlyTheseUsers" and user is not in the given groups
1005
     *
1006
     * @uses DataExtension->canView()
1007
     * @uses ViewerGroups()
1008
     *
1009
     * @param Member $member
1010
     * @return bool True if the current user can view this page
1011
     */
1012
    public function canView($member = null)
1013
    {
1014
        if (!$member) {
1015
            $member = Member::currentUser();
1016
        }
1017
1018
        // Standard mechanism for accepting permission changes from extensions
1019
        $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...
1020
        if ($extended !== null) {
1021
            return $extended;
1022
        }
1023
1024
        // admin override
1025
        if ($member && Permission::checkMember($member, array("ADMIN", "SITETREE_VIEW_ALL"))) {
1026
            return true;
1027
        }
1028
1029
        // Orphaned pages (in the current stage) are unavailable, except for admins via the CMS
1030
        if ($this->isOrphaned()) {
1031
            return false;
1032
        }
1033
1034
        // Note: getInheritedPermissions() is disused in this instance
1035
        // to allow parent canView extensions to influence subpage canView()
1036
1037
        // check for empty spec
1038
        if (!$this->CanViewType || $this->CanViewType === 'Anyone') {
1039
            return true;
1040
        }
1041
1042
        // check for inherit
1043
        if ($this->CanViewType === 'Inherit') {
1044
            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...
1045
                return $this->Parent()->canView($member);
1046
            } else {
1047
                return $this->getSiteConfig()->canViewPages($member);
1048
            }
1049
        }
1050
1051
        // check for any logged-in users
1052
        if ($this->CanViewType === 'LoggedInUsers' && $member && $member->ID) {
1053
            return true;
1054
        }
1055
1056
        // check for specific groups
1057
        if ($this->CanViewType === 'OnlyTheseUsers'
1058
            && $member
1059
            && $member->inGroups($this->ViewerGroups())
1060
        ) {
1061
            return true;
1062
        }
1063
1064
        return false;
1065
    }
1066
1067
    /**
1068
     * Check if this page can be published
1069
     *
1070
     * @param Member $member
1071
     * @return bool
1072
     */
1073 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...
1074
    {
1075
        if (!$member) {
1076
            $member = Member::currentUser();
1077
        }
1078
1079
        // Check extension
1080
        $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...
1081
        if ($extended !== null) {
1082
            return $extended;
1083
        }
1084
1085
        if (Permission::checkMember($member, "ADMIN")) {
1086
            return true;
1087
        }
1088
1089
        // Default to relying on edit permission
1090
        return $this->canEdit($member);
1091
    }
1092
1093
    /**
1094
     * This function should return true if the current user can delete this page. It can be overloaded to customise the
1095
     * security model for an application.
1096
     *
1097
     * Denies permission if any of the following conditions is true:
1098
     * - canDelete() returns false on any extension
1099
     * - canEdit() returns false
1100
     * - any descendant page returns false for canDelete()
1101
     *
1102
     * @uses canDelete()
1103
     * @uses SiteTreeExtension->canDelete()
1104
     * @uses canEdit()
1105
     *
1106
     * @param Member $member
1107
     * @return bool True if the current user can delete this page
1108
     */
1109
    public function canDelete($member = null)
1110
    {
1111
        if (!$member) {
1112
            $member = Member::currentUser();
1113
        }
1114
1115
        // Standard mechanism for accepting permission changes from extensions
1116
        $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...
1117
        if ($extended !== null) {
1118
            return $extended;
1119
        }
1120
1121
        if (!$member) {
1122
            return false;
1123
        }
1124
1125
        // Default permission check
1126
        if (Permission::checkMember($member, array("ADMIN", "SITETREE_EDIT_ALL"))) {
1127
            return true;
1128
        }
1129
1130
        // Check inherited permissions
1131
        return static::getInheritedPermissions()
1132
            ->canDelete($this->ID, $member);
1133
    }
1134
1135
    /**
1136
     * This function should return true if the current user can create new pages of this class, regardless of class. It
1137
     * can be overloaded to customise the security model for an application.
1138
     *
1139
     * By default, permission to create at the root level is based on the SiteConfig configuration, and permission to
1140
     * create beneath a parent is based on the ability to edit that parent page.
1141
     *
1142
     * Use {@link canAddChildren()} to control behaviour of creating children under this page.
1143
     *
1144
     * @uses $can_create
1145
     * @uses DataExtension->canCreate()
1146
     *
1147
     * @param Member $member
1148
     * @param array $context Optional array which may contain array('Parent' => $parentObj)
1149
     *                       If a parent page is known, it will be checked for validity.
1150
     *                       If omitted, it will be assumed this is to be created as a top level page.
1151
     * @return bool True if the current user can create pages on this class.
1152
     */
1153
    public function canCreate($member = null, $context = array())
1154
    {
1155
        if (!$member) {
1156
            $member = Member::currentUser();
1157
        }
1158
1159
        // Check parent (custom canCreate option for SiteTree)
1160
        // Block children not allowed for this parent type
1161
        $parent = isset($context['Parent']) ? $context['Parent'] : null;
1162
        if ($parent && !in_array(static::class, $parent->allowedChildren())) {
1163
            return false;
1164
        }
1165
1166
        // Standard mechanism for accepting permission changes from extensions
1167
        $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...
1168
        if ($extended !== null) {
1169
            return $extended;
1170
        }
1171
1172
        // Check permission
1173
        if ($member && Permission::checkMember($member, "ADMIN")) {
1174
            return true;
1175
        }
1176
1177
        // Fall over to inherited permissions
1178
        if ($parent && $parent->exists()) {
1179
            return $parent->canAddChildren($member);
1180
        } else {
1181
            // This doesn't necessarily mean we are creating a root page, but that
1182
            // we don't know if there is a parent, so default to this permission
1183
            return SiteConfig::current_site_config()->canCreateTopLevel($member);
1184
        }
1185
    }
1186
1187
    /**
1188
     * This function should return true if the current user can edit this page. It can be overloaded to customise the
1189
     * security model for an application.
1190
     *
1191
     * Denies permission if any of the following conditions is true:
1192
     * - canEdit() on any extension returns false
1193
     * - canView() return false
1194
     * - "CanEditType" directive is set to "Inherit" and any parent page return false for canEdit()
1195
     * - "CanEditType" directive is set to "LoggedInUsers" and no user is logged in or doesn't have the
1196
     *   CMS_Access_CMSMAIN permission code
1197
     * - "CanEditType" directive is set to "OnlyTheseUsers" and user is not in the given groups
1198
     *
1199
     * @uses canView()
1200
     * @uses EditorGroups()
1201
     * @uses DataExtension->canEdit()
1202
     *
1203
     * @param Member $member Set to false if you want to explicitly test permissions without a valid user (useful for
1204
     *                       unit tests)
1205
     * @return bool True if the current user can edit this page
1206
     */
1207 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...
1208
    {
1209
        if (!$member) {
1210
            $member = Member::currentUser();
1211
        }
1212
1213
        // Standard mechanism for accepting permission changes from extensions
1214
        $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...
1215
        if ($extended !== null) {
1216
            return $extended;
1217
        }
1218
1219
        // Default permissions
1220
        if (Permission::checkMember($member, "SITETREE_EDIT_ALL")) {
1221
            return true;
1222
        }
1223
1224
        // Check inherited permissions
1225
        return static::getInheritedPermissions()
1226
            ->canEdit($this->ID, $member);
1227
    }
1228
1229
    /**
1230
     * Stub method to get the site config, unless the current class can provide an alternate.
1231
     *
1232
     * @return SiteConfig
1233
     */
1234
    public function getSiteConfig()
1235
    {
1236
        $configs = $this->invokeWithExtensions('alternateSiteConfig');
1237
        foreach (array_filter($configs) as $config) {
1238
            return $config;
1239
        }
1240
1241
        return SiteConfig::current_site_config();
1242
    }
1243
1244
    /**
1245
     * @return InheritedPermissions
1246
     */
1247
    public static function getInheritedPermissions()
1248
    {
1249
        /** @var InheritedPermissions $permissions */
1250
        return Injector::inst()->get(InheritedPermissions::class.'.sitetree');
1251
    }
1252
1253
    /**
1254
     * Collate selected descendants of this page.
1255
     *
1256
     * {@link $condition} will be evaluated on each descendant, and if it is succeeds, that item will be added to the
1257
     * $collator array.
1258
     *
1259
     * @param string $condition The PHP condition to be evaluated. The page will be called $item
1260
     * @param array  $collator  An array, passed by reference, to collect all of the matching descendants.
1261
     * @return bool
1262
     */
1263
    public function collateDescendants($condition, &$collator)
1264
    {
1265
        $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...
1266
        if ($children) {
1267
            foreach ($children as $item) {
1268
                if (eval("return $condition;")) {
1269
                    $collator[] = $item;
1270
                }
1271
                /** @var SiteTree $item */
1272
                $item->collateDescendants($condition, $collator);
1273
            }
1274
            return true;
1275
        }
1276
        return false;
1277
    }
1278
1279
    /**
1280
     * Return the title, description, keywords and language metatags.
1281
     *
1282
     * @todo Move <title> tag in separate getter for easier customization and more obvious usage
1283
     *
1284
     * @param bool $includeTitle Show default <title>-tag, set to false for custom templating
1285
     * @return string The XHTML metatags
1286
     */
1287
    public function MetaTags($includeTitle = true)
1288
    {
1289
        $tags = array();
1290
        if ($includeTitle && strtolower($includeTitle) != 'false') {
1291
            $tags[] = FormField::create_tag('title', array(), $this->obj('Title')->forTemplate());
1292
        }
1293
1294
        $generator = trim(Config::inst()->get(self::class, 'meta_generator'));
1295
        if (!empty($generator)) {
1296
            $tags[] = FormField::create_tag('meta', array(
1297
                'name' => 'generator',
1298
                'content' => $generator,
1299
            ));
1300
        }
1301
1302
        $charset = ContentNegotiator::config()->uninherited('encoding');
1303
        $tags[] = FormField::create_tag('meta', array(
1304
            'http-equiv' => 'Content-Type',
1305
            'content' => 'text/html; charset=' . $charset,
1306
        ));
1307
        if ($this->MetaDescription) {
1308
            $tags[] = FormField::create_tag('meta', array(
1309
                'name' => 'description',
1310
                'content' => $this->MetaDescription,
1311
            ));
1312
        }
1313
1314
        if (Permission::check('CMS_ACCESS_CMSMain')
1315
            && !$this instanceof ErrorPage
1316
            && $this->ID > 0
1317
        ) {
1318
            $tags[] = FormField::create_tag('meta', array(
1319
                'name' => 'x-page-id',
1320
                'content' => $this->obj('ID')->forTemplate(),
1321
            ));
1322
            $tags[] = FormField::create_tag('meta', array(
1323
                'name' => 'x-cms-edit-link',
1324
                'content' => $this->obj('CMSEditLink')->forTemplate(),
1325
            ));
1326
        }
1327
1328
        $tags = implode("\n", $tags);
1329
        if ($this->ExtraMeta) {
1330
            $tags .= $this->obj('ExtraMeta')->forTemplate();
1331
        }
1332
1333
        $this->extend('MetaTags', $tags);
1334
1335
        return $tags;
1336
    }
1337
1338
    /**
1339
     * Returns the object that contains the content that a user would associate with this page.
1340
     *
1341
     * Ordinarily, this is just the page itself, but for example on RedirectorPages or VirtualPages ContentSource() will
1342
     * return the page that is linked to.
1343
     *
1344
     * @return $this
1345
     */
1346
    public function ContentSource()
1347
    {
1348
        return $this;
1349
    }
1350
1351
    /**
1352
     * Add default records to database.
1353
     *
1354
     * This function is called whenever the database is built, after the database tables have all been created. Overload
1355
     * this to add default records when the database is built, but make sure you call parent::requireDefaultRecords().
1356
     */
1357
    public function requireDefaultRecords()
1358
    {
1359
        parent::requireDefaultRecords();
1360
1361
        // default pages
1362
        if (static::class == self::class && $this->config()->create_default_pages) {
1363
            if (!SiteTree::get_by_link(RootURLController::config()->default_homepage_link)) {
1364
                $homepage = new Page();
1365
                $homepage->Title = _t(__CLASS__.'.DEFAULTHOMETITLE', 'Home');
1366
                $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>');
1367
                $homepage->URLSegment = RootURLController::config()->default_homepage_link;
1368
                $homepage->Sort = 1;
1369
                $homepage->write();
1370
                $homepage->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
1371
                $homepage->flushCache();
1372
                DB::alteration_message('Home page created', 'created');
1373
            }
1374
1375
            if (DB::query("SELECT COUNT(*) FROM \"SiteTree\"")->value() == 1) {
1376
                $aboutus = new Page();
1377
                $aboutus->Title = _t(__CLASS__.'.DEFAULTABOUTTITLE', 'About Us');
1378
                $aboutus->Content = _t(
1379
                    'SilverStripe\\CMS\\Model\\SiteTree.DEFAULTABOUTCONTENT',
1380
                    '<p>You can fill this page out with your own content, or delete it and create your own pages.</p>'
1381
                );
1382
                $aboutus->Sort = 2;
1383
                $aboutus->write();
1384
                $aboutus->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
1385
                $aboutus->flushCache();
1386
                DB::alteration_message('About Us page created', 'created');
1387
1388
                $contactus = new Page();
1389
                $contactus->Title = _t(__CLASS__.'.DEFAULTCONTACTTITLE', 'Contact Us');
1390
                $contactus->Content = _t(
1391
                    'SilverStripe\\CMS\\Model\\SiteTree.DEFAULTCONTACTCONTENT',
1392
                    '<p>You can fill this page out with your own content, or delete it and create your own pages.</p>'
1393
                );
1394
                $contactus->Sort = 3;
1395
                $contactus->write();
1396
                $contactus->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
1397
                $contactus->flushCache();
1398
                DB::alteration_message('Contact Us page created', 'created');
1399
            }
1400
        }
1401
    }
1402
1403
    protected function onBeforeWrite()
1404
    {
1405
        parent::onBeforeWrite();
1406
1407
        // If Sort hasn't been set, make this page come after it's siblings
1408
        if (!$this->Sort) {
1409
            $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...
1410
            $this->Sort = DB::prepared_query(
1411
                "SELECT MAX(\"Sort\") + 1 FROM \"SiteTree\" WHERE \"ParentID\" = ?",
1412
                array($parentID)
1413
            )->value();
1414
        }
1415
1416
        // If there is no URLSegment set, generate one from Title
1417
        $defaultSegment = $this->generateURLSegment(_t(
1418
            'SilverStripe\\CMS\\Controllers\\CMSMain.NEWPAGE',
1419
            'New {pagetype}',
1420
            array('pagetype' => $this->i18n_singular_name())
1421
        ));
1422
        if ((!$this->URLSegment || $this->URLSegment == $defaultSegment) && $this->Title) {
1423
            $this->URLSegment = $this->generateURLSegment($this->Title);
1424
        } elseif ($this->isChanged('URLSegment', 2)) {
1425
            // Do a strict check on change level, to avoid double encoding caused by
1426
            // bogus changes through forceChange()
1427
            $filter = URLSegmentFilter::create();
1428
            $this->URLSegment = $filter->filter($this->URLSegment);
1429
            // If after sanitising there is no URLSegment, give it a reasonable default
1430
            if (!$this->URLSegment) {
1431
                $this->URLSegment = "page-$this->ID";
1432
            }
1433
        }
1434
1435
        // Ensure that this object has a non-conflicting URLSegment value.
1436
        $count = 2;
1437
        while (!$this->validURLSegment()) {
1438
            $this->URLSegment = preg_replace('/-[0-9]+$/', null, $this->URLSegment) . '-' . $count;
1439
            $count++;
1440
        }
1441
1442
        $this->syncLinkTracking();
1443
1444
        // Check to see if we've only altered fields that shouldn't affect versioning
1445
        $fieldsIgnoredByVersioning = array('HasBrokenLink', 'Status', 'HasBrokenFile', 'ToDo', 'VersionID', 'SaveCount');
1446
        $changedFields = array_keys($this->getChangedFields(true, 2));
1447
1448
        // This more rigorous check is inline with the test that write() does to decide whether or not to write to the
1449
        // DB. We use that to avoid cluttering the system with a migrateVersion() call that doesn't get used
1450
        $oneChangedFields = array_keys($this->getChangedFields(true, 1));
1451
1452
        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...
1453
            // This will have the affect of preserving the versioning
1454
            $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...
1455
        }
1456
    }
1457
1458
    /**
1459
     * Trigger synchronisation of link tracking
1460
     *
1461
     * {@see SiteTreeLinkTracking::augmentSyncLinkTracking}
1462
     */
1463
    public function syncLinkTracking()
1464
    {
1465
        $this->extend('augmentSyncLinkTracking');
1466
    }
1467
1468
    public function onBeforeDelete()
1469
    {
1470
        parent::onBeforeDelete();
1471
1472
        // If deleting this page, delete all its children.
1473
        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...
1474
            foreach ($children as $child) {
1475
                /** @var SiteTree $child */
1476
                $child->delete();
1477
            }
1478
        }
1479
    }
1480
1481
    public function onAfterDelete()
1482
    {
1483
        // Need to flush cache to avoid outdated versionnumber references
1484
        $this->flushCache();
1485
1486
        // Need to mark pages depending to this one as broken
1487
        $dependentPages = $this->DependentPages();
1488
        if ($dependentPages) {
1489
            foreach ($dependentPages as $page) {
1490
            // $page->write() calls syncLinkTracking, which does all the hard work for us.
1491
                $page->write();
1492
            }
1493
        }
1494
1495
        parent::onAfterDelete();
1496
    }
1497
1498
    public function flushCache($persistent = true)
1499
    {
1500
        parent::flushCache($persistent);
1501
        $this->_cache_statusFlags = null;
1502
    }
1503
1504
    public function validate()
1505
    {
1506
        $result = parent::validate();
1507
1508
        // Allowed children validation
1509
        $parent = $this->getParent();
1510
        if ($parent && $parent->exists()) {
1511
            // No need to check for subclasses or instanceof, as allowedChildren() already
1512
            // deconstructs any inheritance trees already.
1513
            $allowed = $parent->allowedChildren();
1514
            $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...
1515
                ? $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...
1516
                : $this;
1517
            if (!in_array($subject->ClassName, $allowed)) {
1518
                $result->addError(
1519
                    _t(
1520
                        'SilverStripe\\CMS\\Model\\SiteTree.PageTypeNotAllowed',
1521
                        'Page type "{type}" not allowed as child of this parent page',
1522
                        array('type' => $subject->i18n_singular_name())
1523
                    ),
1524
                    ValidationResult::TYPE_ERROR,
1525
                    'ALLOWED_CHILDREN'
1526
                );
1527
            }
1528
        }
1529
1530
        // "Can be root" validation
1531
        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...
1532
            $result->addError(
1533
                _t(
1534
                    'SilverStripe\\CMS\\Model\\SiteTree.PageTypNotAllowedOnRoot',
1535
                    'Page type "{type}" is not allowed on the root level',
1536
                    array('type' => $this->i18n_singular_name())
1537
                ),
1538
                ValidationResult::TYPE_ERROR,
1539
                'CAN_BE_ROOT'
1540
            );
1541
        }
1542
1543
        return $result;
1544
    }
1545
1546
    /**
1547
     * Returns true if this object has a URLSegment value that does not conflict with any other objects. This method
1548
     * checks for:
1549
     *  - A page with the same URLSegment that has a conflict
1550
     *  - Conflicts with actions on the parent page
1551
     *  - A conflict caused by a root page having the same URLSegment as a class name
1552
     *
1553
     * @return bool
1554
     */
1555
    public function validURLSegment()
1556
    {
1557
        if (self::config()->nested_urls && $parent = $this->Parent()) {
1558
            if ($controller = ModelAsController::controller_for($parent)) {
1559
                if ($controller instanceof Controller && $controller->hasAction($this->URLSegment)) {
1560
                    return false;
1561
                }
1562
            }
1563
        }
1564
1565
        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...
1566
            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...
1567
                return false;
1568
            }
1569
        }
1570
1571
        // Filters by url, id, and parent
1572
        $filter = array('"SiteTree"."URLSegment"' => $this->URLSegment);
1573
        if ($this->ID) {
1574
            $filter['"SiteTree"."ID" <> ?'] = $this->ID;
1575
        }
1576
        if (self::config()->nested_urls) {
1577
            $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...
1578
        }
1579
1580
        // If any of the extensions return `0` consider the segment invalid
1581
        $extensionResponses = array_filter(
1582
            (array)$this->extend('augmentValidURLSegment'),
1583
            function ($response) {
1584
                return !is_null($response);
1585
            }
1586
        );
1587
        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...
1588
            return min($extensionResponses);
1589
        }
1590
1591
        // Check existence
1592
        return !DataObject::get(self::class, $filter)->exists();
1593
    }
1594
1595
    /**
1596
     * Generate a URL segment based on the title provided.
1597
     *
1598
     * If {@link Extension}s wish to alter URL segment generation, they can do so by defining
1599
     * updateURLSegment(&$url, $title).  $url will be passed by reference and should be modified. $title will contain
1600
     * the title that was originally used as the source of this generated URL. This lets extensions either start from
1601
     * scratch, or incrementally modify the generated URL.
1602
     *
1603
     * @param string $title Page title
1604
     * @return string Generated url segment
1605
     */
1606
    public function generateURLSegment($title)
1607
    {
1608
        $filter = URLSegmentFilter::create();
1609
        $t = $filter->filter($title);
1610
1611
        // Fallback to generic page name if path is empty (= no valid, convertable characters)
1612
        if (!$t || $t == '-' || $t == '-1') {
1613
            $t = "page-$this->ID";
1614
        }
1615
1616
        // Hook for extensions
1617
        $this->extend('updateURLSegment', $t, $title);
1618
1619
        return $t;
1620
    }
1621
1622
    /**
1623
     * Gets the URL segment for the latest draft version of this page.
1624
     *
1625
     * @return string
1626
     */
1627
    public function getStageURLSegment()
1628
    {
1629
        $stageRecord = Versioned::get_one_by_stage(self::class, Versioned::DRAFT, array(
1630
            '"SiteTree"."ID"' => $this->ID
1631
        ));
1632
        return ($stageRecord) ? $stageRecord->URLSegment : null;
1633
    }
1634
1635
    /**
1636
     * Gets the URL segment for the currently published version of this page.
1637
     *
1638
     * @return string
1639
     */
1640
    public function getLiveURLSegment()
1641
    {
1642
        $liveRecord = Versioned::get_one_by_stage(self::class, Versioned::LIVE, array(
1643
            '"SiteTree"."ID"' => $this->ID
1644
        ));
1645
        return ($liveRecord) ? $liveRecord->URLSegment : null;
1646
    }
1647
1648
    /**
1649
     * Returns the pages that depend on this page. This includes virtual pages, pages that link to it, etc.
1650
     *
1651
     * @param bool $includeVirtuals Set to false to exlcude virtual pages.
1652
     * @return ArrayList
1653
     */
1654
    public function DependentPages($includeVirtuals = true)
1655
    {
1656
        if (class_exists('Subsite')) {
1657
            $origDisableSubsiteFilter = Subsite::$disable_subsite_filter;
1658
            Subsite::disable_subsite_filter(true);
1659
        }
1660
1661
        // Content links
1662
        $items = new ArrayList();
1663
1664
        // We merge all into a regular SS_List, because DataList doesn't support merge
1665
        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...
1666
            $linkList = new ArrayList();
1667
            foreach ($contentLinks as $item) {
1668
                $item->DependentLinkType = 'Content link';
1669
                $linkList->push($item);
1670
            }
1671
            $items->merge($linkList);
1672
        }
1673
1674
        // Virtual pages
1675
        if ($includeVirtuals) {
1676
            $virtuals = $this->VirtualPages();
1677
            if ($virtuals) {
1678
                $virtualList = new ArrayList();
1679
                foreach ($virtuals as $item) {
1680
                    $item->DependentLinkType = 'Virtual page';
1681
                    $virtualList->push($item);
1682
                }
1683
                $items->merge($virtualList);
1684
            }
1685
        }
1686
1687
        // Redirector pages
1688
        $redirectors = RedirectorPage::get()->where(array(
1689
            '"RedirectorPage"."RedirectionType"' => 'Internal',
1690
            '"RedirectorPage"."LinkToID"' => $this->ID
1691
        ));
1692
        if ($redirectors) {
1693
            $redirectorList = new ArrayList();
1694
            foreach ($redirectors as $item) {
1695
                $item->DependentLinkType = 'Redirector page';
1696
                $redirectorList->push($item);
1697
            }
1698
            $items->merge($redirectorList);
1699
        }
1700
1701
        if (class_exists('Subsite')) {
1702
            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...
1703
        }
1704
1705
        return $items;
1706
    }
1707
1708
    /**
1709
     * Return all virtual pages that link to this page.
1710
     *
1711
     * @return DataList
1712
     */
1713
    public function VirtualPages()
1714
    {
1715
        $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...
1716
1717
        // Disable subsite filter for these pages
1718
        if ($pages instanceof DataList) {
1719
            return $pages->setDataQueryParam('Subsite.filter', false);
1720
        } else {
1721
            return $pages;
1722
        }
1723
    }
1724
1725
    /**
1726
     * Returns a FieldList with which to create the main editing form.
1727
     *
1728
     * You can override this in your child classes to add extra fields - first get the parent fields using
1729
     * parent::getCMSFields(), then use addFieldToTab() on the FieldList.
1730
     *
1731
     * See {@link getSettingsFields()} for a different set of fields concerned with configuration aspects on the record,
1732
     * e.g. access control.
1733
     *
1734
     * @return FieldList The fields to be displayed in the CMS
1735
     */
1736
    public function getCMSFields()
1737
    {
1738
        // Status / message
1739
        // Create a status message for multiple parents
1740
        if ($this->ID && is_numeric($this->ID)) {
1741
            $linkedPages = $this->VirtualPages();
1742
1743
            $parentPageLinks = array();
1744
1745
            if ($linkedPages->count() > 0) {
1746
                /** @var VirtualPage $linkedPage */
1747
                foreach ($linkedPages as $linkedPage) {
1748
                    $parentPage = $linkedPage->Parent();
1749
                    if ($parentPage && $parentPage->exists()) {
1750
                        $link = Convert::raw2att($parentPage->CMSEditLink());
1751
                        $title = Convert::raw2xml($parentPage->Title);
1752
                    } else {
1753
                        $link = CMSPageEditController::singleton()->Link('show');
1754
                        $title = _t(__CLASS__.'.TOPLEVEL', 'Site Content (Top Level)');
1755
                    }
1756
                    $parentPageLinks[] = "<a class=\"cmsEditlink\" href=\"{$link}\">{$title}</a>";
1757
                }
1758
1759
                $lastParent = array_pop($parentPageLinks);
1760
                $parentList = "'$lastParent'";
1761
1762
                if (count($parentPageLinks)) {
1763
                    $parentList = "'" . implode("', '", $parentPageLinks) . "' and "
1764
                        . $parentList;
1765
                }
1766
1767
                $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...
1768
                    'SilverStripe\\CMS\\Model\\SiteTree.APPEARSVIRTUALPAGES',
1769
                    "This content also appears on the virtual pages in the {title} sections.",
1770
                    array('title' => $parentList)
1771
                );
1772
            }
1773
        }
1774
1775
        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...
1776
            $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...
1777
        }
1778
1779
        $dependentNote = '';
1780
        $dependentTable = new LiteralField('DependentNote', '<p></p>');
1781
1782
        // Create a table for showing pages linked to this one
1783
        $dependentPages = $this->DependentPages();
1784
        $dependentPagesCount = $dependentPages->count();
1785
        if ($dependentPagesCount) {
1786
            $dependentColumns = array(
1787
                'Title' => $this->fieldLabel('Title'),
1788
                'AbsoluteLink' => _t(__CLASS__.'.DependtPageColumnURL', 'URL'),
1789
                'DependentLinkType' => _t(__CLASS__.'.DependtPageColumnLinkType', 'Link type'),
1790
            );
1791
            if (class_exists('Subsite')) {
1792
                $dependentColumns['Subsite.Title'] = singleton('Subsite')->i18n_singular_name();
1793
            }
1794
1795
            $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>');
1796
            $dependentTable = GridField::create(
1797
                'DependentPages',
1798
                false,
1799
                $dependentPages
1800
            );
1801
            /** @var GridFieldDataColumns $dataColumns */
1802
            $dataColumns = $dependentTable->getConfig()->getComponentByType('SilverStripe\\Forms\\GridField\\GridFieldDataColumns');
1803
            $dataColumns
1804
                ->setDisplayFields($dependentColumns)
1805
                ->setFieldFormatting(array(
1806
                    'Title' => function ($value, &$item) {
1807
                        return sprintf(
1808
                            '<a href="admin/pages/edit/show/%d">%s</a>',
1809
                            (int)$item->ID,
1810
                            Convert::raw2xml($item->Title)
1811
                        );
1812
                    },
1813
                    '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...
1814
                        return sprintf(
1815
                            '<a href="%s" target="_blank">%s</a>',
1816
                            Convert::raw2xml($value),
1817
                            Convert::raw2xml($value)
1818
                        );
1819
                    }
1820
                ));
1821
        }
1822
1823
        $baseLink = Controller::join_links(
1824
            Director::absoluteBaseURL(),
1825
            (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...
1826
        );
1827
1828
        $urlsegment = SiteTreeURLSegmentField::create("URLSegment", $this->fieldLabel('URLSegment'))
1829
            ->setURLPrefix($baseLink)
1830
            ->setDefaultURL($this->generateURLSegment(_t(
1831
                'SilverStripe\\CMS\\Controllers\\CMSMain.NEWPAGE',
1832
                'New {pagetype}',
1833
                array('pagetype' => $this->i18n_singular_name())
1834
            )));
1835
        $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...
1836
            ? $this->fieldLabel('LinkChangeNote')
1837
            : '';
1838
        if (!Config::inst()->get('SilverStripe\\View\\Parsers\\URLSegmentFilter', 'default_allow_multibyte')) {
1839
            $helpText .= _t('SilverStripe\\CMS\\Forms\\SiteTreeURLSegmentField.HelpChars', ' Special characters are automatically converted or removed.');
1840
        }
1841
        $urlsegment->setHelpText($helpText);
1842
1843
        $fields = new FieldList(
1844
            $rootTab = new TabSet(
1845
                "Root",
1846
                $tabMain = new Tab(
1847
                    'Main',
1848
                    new TextField("Title", $this->fieldLabel('Title')),
1849
                    $urlsegment,
1850
                    new TextField("MenuTitle", $this->fieldLabel('MenuTitle')),
1851
                    $htmlField = new HTMLEditorField("Content", _t(__CLASS__.'.HTMLEDITORTITLE', "Content", 'HTML editor title')),
1852
                    ToggleCompositeField::create(
1853
                        'Metadata',
1854
                        _t(__CLASS__.'.MetadataToggle', 'Metadata'),
1855
                        array(
1856
                            $metaFieldDesc = new TextareaField("MetaDescription", $this->fieldLabel('MetaDescription')),
1857
                            $metaFieldExtra = new TextareaField("ExtraMeta", $this->fieldLabel('ExtraMeta'))
1858
                        )
1859
                    )->setHeadingLevel(4)
1860
                ),
1861
                $tabDependent = new Tab(
1862
                    'Dependent',
1863
                    $dependentNote,
1864
                    $dependentTable
1865
                )
1866
            )
1867
        );
1868
        $htmlField->addExtraClass('stacked');
1869
1870
        // Help text for MetaData on page content editor
1871
        $metaFieldDesc
1872
            ->setRightTitle(
1873
                _t(
1874
                    'SilverStripe\\CMS\\Model\\SiteTree.METADESCHELP',
1875
                    "Search engines use this content for displaying search results (although it will not influence their ranking)."
1876
                )
1877
            )
1878
            ->addExtraClass('help');
1879
        $metaFieldExtra
1880
            ->setRightTitle(
1881
                _t(
1882
                    'SilverStripe\\CMS\\Model\\SiteTree.METAEXTRAHELP',
1883
                    "HTML tags for additional meta information. For example &lt;meta name=\"customName\" content=\"your custom content here\" /&gt;"
1884
                )
1885
            )
1886
            ->addExtraClass('help');
1887
1888
        // Conditional dependent pages tab
1889
        if ($dependentPagesCount) {
1890
            $tabDependent->setTitle(_t(__CLASS__.'.TABDEPENDENT', "Dependent pages") . " ($dependentPagesCount)");
1891
        } else {
1892
            $fields->removeFieldFromTab('Root', 'Dependent');
1893
        }
1894
1895
        $tabMain->setTitle(_t(__CLASS__.'.TABCONTENT', "Main Content"));
1896
1897
        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...
1898
            $obsoleteWarning = _t(
1899
                'SilverStripe\\CMS\\Model\\SiteTree.OBSOLETECLASS',
1900
                "This page is of obsolete type {type}. Saving will reset its type and you may lose data",
1901
                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...
1902
            );
1903
1904
            $fields->addFieldToTab(
1905
                "Root.Main",
1906
                new LiteralField("ObsoleteWarningHeader", "<p class=\"message warning\">$obsoleteWarning</p>"),
1907
                "Title"
1908
            );
1909
        }
1910
1911
        if (file_exists(BASE_PATH . '/install.php')) {
1912
            $fields->addFieldToTab("Root.Main", new LiteralField(
1913
                "InstallWarningHeader",
1914
                "<p class=\"message warning\">" . _t(
1915
                    "SilverStripe\\CMS\\Model\\SiteTree.REMOVE_INSTALL_WARNING",
1916
                    "Warning: You should remove install.php from this SilverStripe install for security reasons."
1917
                )
1918
                . "</p>"
1919
            ), "Title");
1920
        }
1921
1922
        if (self::$runCMSFieldsExtensions) {
1923
            $this->extend('updateCMSFields', $fields);
1924
        }
1925
1926
        return $fields;
1927
    }
1928
1929
1930
    /**
1931
     * Returns fields related to configuration aspects on this record, e.g. access control. See {@link getCMSFields()}
1932
     * for content-related fields.
1933
     *
1934
     * @return FieldList
1935
     */
1936
    public function getSettingsFields()
1937
    {
1938
        $groupsMap = array();
1939
        foreach (Group::get() as $group) {
1940
            // Listboxfield values are escaped, use ASCII char instead of &raquo;
1941
            $groupsMap[$group->ID] = $group->getBreadcrumbs(' > ');
1942
        }
1943
        asort($groupsMap);
1944
1945
        $fields = new FieldList(
1946
            $rootTab = new TabSet(
1947
                "Root",
1948
                $tabBehaviour = new Tab(
1949
                    'Settings',
1950
                    new DropdownField(
1951
                        "ClassName",
1952
                        $this->fieldLabel('ClassName'),
1953
                        $this->getClassDropdown()
1954
                    ),
1955
                    $parentTypeSelector = new CompositeField(
1956
                        $parentType = new OptionsetField("ParentType", _t("SilverStripe\\CMS\\Model\\SiteTree.PAGELOCATION", "Page location"), array(
1957
                            "root" => _t("SilverStripe\\CMS\\Model\\SiteTree.PARENTTYPE_ROOT", "Top-level page"),
1958
                            "subpage" => _t("SilverStripe\\CMS\\Model\\SiteTree.PARENTTYPE_SUBPAGE", "Sub-page underneath a parent page"),
1959
                        )),
1960
                        $parentIDField = new TreeDropdownField("ParentID", $this->fieldLabel('ParentID'), self::class, 'ID', 'MenuTitle')
1961
                    ),
1962
                    $visibility = new FieldGroup(
1963
                        new CheckboxField("ShowInMenus", $this->fieldLabel('ShowInMenus')),
1964
                        new CheckboxField("ShowInSearch", $this->fieldLabel('ShowInSearch'))
1965
                    ),
1966
                    $viewersOptionsField = new OptionsetField(
1967
                        "CanViewType",
1968
                        _t(__CLASS__.'.ACCESSHEADER', "Who can view this page?")
1969
                    ),
1970
                    $viewerGroupsField = ListboxField::create("ViewerGroups", _t(__CLASS__.'.VIEWERGROUPS', "Viewer Groups"))
1971
                        ->setSource($groupsMap)
1972
                        ->setAttribute(
1973
                            'data-placeholder',
1974
                            _t(__CLASS__.'.GroupPlaceholder', 'Click to select group')
1975
                        ),
1976
                    $editorsOptionsField = new OptionsetField(
1977
                        "CanEditType",
1978
                        _t(__CLASS__.'.EDITHEADER', "Who can edit this page?")
1979
                    ),
1980
                    $editorGroupsField = ListboxField::create("EditorGroups", _t(__CLASS__.'.EDITORGROUPS', "Editor Groups"))
1981
                        ->setSource($groupsMap)
1982
                        ->setAttribute(
1983
                            'data-placeholder',
1984
                            _t(__CLASS__.'.GroupPlaceholder', 'Click to select group')
1985
                        )
1986
                )
1987
            )
1988
        );
1989
1990
        $parentType->addExtraClass('noborder');
1991
        $visibility->setTitle($this->fieldLabel('Visibility'));
1992
1993
1994
        // This filter ensures that the ParentID dropdown selection does not show this node,
1995
        // or its descendents, as this causes vanishing bugs
1996
        $parentIDField->setFilterFunction(create_function('$node', "return \$node->ID != {$this->ID};"));
1997
        $parentTypeSelector->addExtraClass('parentTypeSelector');
1998
1999
        $tabBehaviour->setTitle(_t(__CLASS__.'.TABBEHAVIOUR', "Behavior"));
2000
2001
        // Make page location fields read-only if the user doesn't have the appropriate permission
2002
        if (!Permission::check("SITETREE_REORGANISE")) {
2003
            $fields->makeFieldReadonly('ParentType');
2004
            if ($this->getParentType() === 'root') {
2005
                $fields->removeByName('ParentID');
2006
            } else {
2007
                $fields->makeFieldReadonly('ParentID');
2008
            }
2009
        }
2010
2011
        $viewersOptionsSource = array();
2012
        $viewersOptionsSource["Inherit"] = _t(__CLASS__.'.INHERIT', "Inherit from parent page");
2013
        $viewersOptionsSource["Anyone"] = _t(__CLASS__.'.ACCESSANYONE', "Anyone");
2014
        $viewersOptionsSource["LoggedInUsers"] = _t(__CLASS__.'.ACCESSLOGGEDIN', "Logged-in users");
2015
        $viewersOptionsSource["OnlyTheseUsers"] = _t(__CLASS__.'.ACCESSONLYTHESE', "Only these people (choose from list)");
2016
        $viewersOptionsField->setSource($viewersOptionsSource);
2017
2018
        $editorsOptionsSource = array();
2019
        $editorsOptionsSource["Inherit"] = _t(__CLASS__.'.INHERIT', "Inherit from parent page");
2020
        $editorsOptionsSource["LoggedInUsers"] = _t(__CLASS__.'.EDITANYONE', "Anyone who can log-in to the CMS");
2021
        $editorsOptionsSource["OnlyTheseUsers"] = _t(__CLASS__.'.EDITONLYTHESE', "Only these people (choose from list)");
2022
        $editorsOptionsField->setSource($editorsOptionsSource);
2023
2024
        if (!Permission::check('SITETREE_GRANT_ACCESS')) {
2025
            $fields->makeFieldReadonly($viewersOptionsField);
2026
            if ($this->CanViewType == 'OnlyTheseUsers') {
2027
                $fields->makeFieldReadonly($viewerGroupsField);
2028
            } else {
2029
                $fields->removeByName('ViewerGroups');
2030
            }
2031
2032
            $fields->makeFieldReadonly($editorsOptionsField);
2033
            if ($this->CanEditType == 'OnlyTheseUsers') {
2034
                $fields->makeFieldReadonly($editorGroupsField);
2035
            } else {
2036
                $fields->removeByName('EditorGroups');
2037
            }
2038
        }
2039
2040
        if (self::$runCMSFieldsExtensions) {
2041
            $this->extend('updateSettingsFields', $fields);
2042
        }
2043
2044
        return $fields;
2045
    }
2046
2047
    /**
2048
     * @param bool $includerelations A boolean value to indicate if the labels returned should include relation fields
2049
     * @return array
2050
     */
2051
    public function fieldLabels($includerelations = true)
2052
    {
2053
        $cacheKey = static::class . '_' . $includerelations;
2054
        if (!isset(self::$_cache_field_labels[$cacheKey])) {
2055
            $labels = parent::fieldLabels($includerelations);
2056
            $labels['Title'] = _t(__CLASS__.'.PAGETITLE', "Page name");
2057
            $labels['MenuTitle'] = _t(__CLASS__.'.MENUTITLE', "Navigation label");
2058
            $labels['MetaDescription'] = _t(__CLASS__.'.METADESC', "Meta Description");
2059
            $labels['ExtraMeta'] = _t(__CLASS__.'.METAEXTRA', "Custom Meta Tags");
2060
            $labels['ClassName'] = _t(__CLASS__.'.PAGETYPE', "Page type", 'Classname of a page object');
2061
            $labels['ParentType'] = _t(__CLASS__.'.PARENTTYPE', "Page location");
2062
            $labels['ParentID'] = _t(__CLASS__.'.PARENTID', "Parent page");
2063
            $labels['ShowInMenus'] =_t(__CLASS__.'.SHOWINMENUS', "Show in menus?");
2064
            $labels['ShowInSearch'] = _t(__CLASS__.'.SHOWINSEARCH', "Show in search?");
2065
            $labels['ViewerGroups'] = _t(__CLASS__.'.VIEWERGROUPS', "Viewer Groups");
2066
            $labels['EditorGroups'] = _t(__CLASS__.'.EDITORGROUPS', "Editor Groups");
2067
            $labels['URLSegment'] = _t(__CLASS__.'.URLSegment', 'URL Segment', 'URL for this page');
2068
            $labels['Content'] = _t(__CLASS__.'.Content', 'Content', 'Main HTML Content for a page');
2069
            $labels['CanViewType'] = _t(__CLASS__.'.Viewers', 'Viewers Groups');
2070
            $labels['CanEditType'] = _t(__CLASS__.'.Editors', 'Editors Groups');
2071
            $labels['Comments'] = _t(__CLASS__.'.Comments', 'Comments');
2072
            $labels['Visibility'] = _t(__CLASS__.'.Visibility', 'Visibility');
2073
            $labels['LinkChangeNote'] = _t(
2074
                'SilverStripe\\CMS\\Model\\SiteTree.LINKCHANGENOTE',
2075
                'Changing this page\'s link will also affect the links of all child pages.'
2076
            );
2077
2078
            if ($includerelations) {
2079
                $labels['Parent'] = _t(__CLASS__.'.has_one_Parent', 'Parent Page', 'The parent page in the site hierarchy');
2080
                $labels['LinkTracking'] = _t(__CLASS__.'.many_many_LinkTracking', 'Link Tracking');
2081
                $labels['ImageTracking'] = _t(__CLASS__.'.many_many_ImageTracking', 'Image Tracking');
2082
                $labels['BackLinkTracking'] = _t(__CLASS__.'.many_many_BackLinkTracking', 'Backlink Tracking');
2083
            }
2084
2085
            self::$_cache_field_labels[$cacheKey] = $labels;
2086
        }
2087
2088
        return self::$_cache_field_labels[$cacheKey];
2089
    }
2090
2091
    /**
2092
     * Get the actions available in the CMS for this page - eg Save, Publish.
2093
     *
2094
     * Frontend scripts and styles know how to handle the following FormFields:
2095
     * - top-level FormActions appear as standalone buttons
2096
     * - top-level CompositeField with FormActions within appear as grouped buttons
2097
     * - TabSet & Tabs appear as a drop ups
2098
     * - FormActions within the Tab are restyled as links
2099
     * - major actions can provide alternate states for richer presentation (see ssui.button widget extension)
2100
     *
2101
     * @return FieldList The available actions for this page.
2102
     */
2103
    public function getCMSActions()
2104
    {
2105
        // Get status of page
2106
        $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...
2107
        $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...
2108
        $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...
2109
2110
        // Check permissions
2111
        $canPublish = $this->canPublish();
2112
        $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...
2113
        $canEdit = $this->canEdit();
2114
2115
        // Major actions appear as buttons immediately visible as page actions.
2116
        $majorActions = CompositeField::create()->setName('MajorActions');
2117
        $majorActions->setFieldHolderTemplate(get_class($majorActions) . '_holder_buttongroup');
2118
2119
        // Minor options are hidden behind a drop-up and appear as links (although they are still FormActions).
2120
        $rootTabSet = new TabSet('ActionMenus');
2121
        $moreOptions = new Tab(
2122
            'MoreOptions',
2123
            _t(__CLASS__.'.MoreOptions', 'More options', 'Expands a view for more buttons')
2124
        );
2125
        $rootTabSet->push($moreOptions);
2126
        $rootTabSet->addExtraClass('ss-ui-action-tabset action-menus noborder');
2127
2128
        // Render page information into the "more-options" drop-up, on the top.
2129
        $liveRecord = Versioned::get_by_stage(self::class, Versioned::LIVE)->byID($this->ID);
2130
        $infoTemplate = SSViewer::get_templates_by_class(static::class, '_Information', self::class);
2131
        $moreOptions->push(
2132
            new LiteralField(
2133
                'Information',
2134
                $this->customise(array(
2135
                    'Live' => $liveRecord,
2136
                    'ExistsOnLive' => $isPublished
2137
                ))->renderWith($infoTemplate)
2138
            )
2139
        );
2140
2141
        // Add to campaign option if not-archived and has publish permission
2142
        if (($isPublished || $isOnDraft) && $canPublish) {
2143
            $moreOptions->push(
2144
                AddToCampaignHandler_FormAction::create()
2145
                    ->removeExtraClass('btn-primary')
2146
                    ->addExtraClass('btn-secondary')
2147
            );
2148
        }
2149
2150
        // "readonly"/viewing version that isn't the current version of the record
2151
        $stageRecord = Versioned::get_by_stage(static::class, Versioned::DRAFT)->byID($this->ID);
2152
        /** @skipUpgrade */
2153
        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...
2154
            $moreOptions->push(FormAction::create('email', _t('SilverStripe\\CMS\\Controllers\\CMSMain.EMAIL', 'Email')));
2155
            $moreOptions->push(FormAction::create('rollback', _t('SilverStripe\\CMS\\Controllers\\CMSMain.ROLLBACK', 'Roll back to this version')));
2156
            $actions = new FieldList(array($majorActions, $rootTabSet));
2157
2158
            // getCMSActions() can be extended with updateCMSActions() on a extension
2159
            $this->extend('updateCMSActions', $actions);
2160
            return $actions;
2161
        }
2162
2163
        // "unpublish"
2164 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...
2165
            $moreOptions->push(
2166
                FormAction::create('unpublish', _t(__CLASS__.'.BUTTONUNPUBLISH', 'Unpublish'), 'delete')
2167
                    ->setDescription(_t(__CLASS__.'.BUTTONUNPUBLISHDESC', 'Remove this page from the published site'))
2168
                    ->addExtraClass('btn-secondary')
2169
            );
2170
        }
2171
2172
        // "rollback"
2173 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...
2174
            $moreOptions->push(
2175
                FormAction::create('rollback', _t(__CLASS__.'.BUTTONCANCELDRAFT', 'Cancel draft changes'))
2176
                    ->setDescription(_t(
2177
                        'SilverStripe\\CMS\\Model\\SiteTree.BUTTONCANCELDRAFTDESC',
2178
                        'Delete your draft and revert to the currently published page'
2179
                    ))
2180
                    ->addExtraClass('btn-secondary')
2181
            );
2182
        }
2183
2184
        // "restore"
2185
        if ($canEdit && !$isOnDraft && $isPublished) {
2186
            $majorActions->push(FormAction::create('revert', _t('SilverStripe\\CMS\\Controllers\\CMSMain.RESTORE', 'Restore')));
2187
        }
2188
2189
        // Check if we can restore a deleted page
2190
        // Note: It would be nice to have a canRestore() permission at some point
2191
        if ($canEdit && !$isOnDraft && !$isPublished) {
2192
            // Determine if we should force a restore to root (where once it was a subpage)
2193
            $restoreToRoot = $this->isParentArchived();
2194
2195
            // "restore"
2196
            $title = $restoreToRoot
2197
                ? _t('SilverStripe\\CMS\\Controllers\\CMSMain.RESTORE_TO_ROOT', 'Restore draft at top level')
2198
                : _t('SilverStripe\\CMS\\Controllers\\CMSMain.RESTORE', 'Restore draft');
2199
            $description = $restoreToRoot
2200
                ? _t('SilverStripe\\CMS\\Controllers\\CMSMain.RESTORE_TO_ROOT_DESC', 'Restore the archived version to draft as a top level page')
2201
                : _t('SilverStripe\\CMS\\Controllers\\CMSMain.RESTORE_DESC', 'Restore the archived version to draft');
2202
            $majorActions->push(
2203
                FormAction::create('restore', $title)
2204
                    ->setDescription($description)
2205
                    ->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...
2206
                    ->setAttribute('data-icon', 'decline')
2207
            );
2208
        }
2209
2210
        // If a page is on any stage it can be archived
2211
        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...
2212
            $title = $isPublished
2213
                ? _t('SilverStripe\\CMS\\Controllers\\CMSMain.UNPUBLISH_AND_ARCHIVE', 'Unpublish and archive')
2214
                : _t('SilverStripe\\CMS\\Controllers\\CMSMain.ARCHIVE', 'Archive');
2215
            $moreOptions->push(
2216
                FormAction::create('archive', $title)
2217
                    ->addExtraClass('delete btn btn-secondary')
2218
                    ->setDescription(_t(
2219
                        'SilverStripe\\CMS\\Model\\SiteTree.BUTTONDELETEDESC',
2220
                        'Remove from draft/live and send to archive'
2221
                    ))
2222
            );
2223
        }
2224
2225
        // "save", supports an alternate state that is still clickable, but notifies the user that the action is not needed.
2226
        if ($canEdit && $isOnDraft) {
2227
            $majorActions->push(
2228
                FormAction::create('save', _t(__CLASS__.'.BUTTONSAVED', 'Saved'))
2229
                    ->addExtraClass('btn-secondary-outline font-icon-check-mark')
2230
                    ->setAttribute('data-btn-alternate', 'btn action btn-primary font-icon-save')
2231
                    ->setUseButtonTag(true)
2232
                    ->setAttribute('data-text-alternate', _t('SilverStripe\\CMS\\Controllers\\CMSMain.SAVEDRAFT', 'Save draft'))
2233
            );
2234
        }
2235
2236
        if ($canPublish && $isOnDraft) {
2237
            // "publish", as with "save", it supports an alternate state to show when action is needed.
2238
            $majorActions->push(
2239
                $publish = FormAction::create('publish', _t(__CLASS__.'.BUTTONPUBLISHED', 'Published'))
2240
                    ->addExtraClass('btn-secondary-outline font-icon-check-mark')
2241
                    ->setAttribute('data-btn-alternate', 'btn action btn-primary font-icon-rocket')
2242
                    ->setUseButtonTag(true)
2243
                    ->setAttribute('data-text-alternate', _t(__CLASS__.'.BUTTONSAVEPUBLISH', 'Save & publish'))
2244
            );
2245
2246
            // Set up the initial state of the button to reflect the state of the underlying SiteTree object.
2247
            if ($stagesDiffer) {
2248
                $publish->addExtraClass('btn-primary font-icon-rocket');
2249
                $publish->setTitle(_t(__CLASS__.'.BUTTONSAVEPUBLISH', 'Save & publish'));
2250
                $publish->removeExtraClass('btn-secondary-outline font-icon-check-mark');
2251
            }
2252
        }
2253
2254
        $actions = new FieldList(array($majorActions, $rootTabSet));
2255
2256
        // Hook for extensions to add/remove actions.
2257
        $this->extend('updateCMSActions', $actions);
2258
2259
        return $actions;
2260
    }
2261
2262
    public function onAfterPublish()
2263
    {
2264
        // Force live sort order to match stage sort order
2265
        DB::prepared_query(
2266
            'UPDATE "SiteTree_Live"
2267
			SET "Sort" = (SELECT "SiteTree"."Sort" FROM "SiteTree" WHERE "SiteTree_Live"."ID" = "SiteTree"."ID")
2268
			WHERE EXISTS (SELECT "SiteTree"."Sort" FROM "SiteTree" WHERE "SiteTree_Live"."ID" = "SiteTree"."ID") AND "ParentID" = ?',
2269
            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...
2270
        );
2271
    }
2272
2273
    /**
2274
     * Update draft dependant pages
2275
     */
2276
    public function onAfterRevertToLive()
2277
    {
2278
        // Use an alias to get the updates made by $this->publish
2279
        /** @var SiteTree $stageSelf */
2280
        $stageSelf = Versioned::get_by_stage(self::class, Versioned::DRAFT)->byID($this->ID);
2281
        $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...
2282
2283
        // Need to update pages linking to this one as no longer broken
2284
        foreach ($stageSelf->DependentPages() as $page) {
2285
            /** @var SiteTree $page */
2286
            $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...
2287
        }
2288
    }
2289
2290
    /**
2291
     * Determine if this page references a parent which is archived, and not available in stage
2292
     *
2293
     * @return bool True if there is an archived parent
2294
     */
2295
    protected function isParentArchived()
2296
    {
2297
        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...
2298
            /** @var SiteTree $parentPage */
2299
            $parentPage = Versioned::get_latest_version(self::class, $parentID);
2300
            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...
2301
                return true;
2302
            }
2303
        }
2304
        return false;
2305
    }
2306
2307
    /**
2308
     * Restore the content in the active copy of this SiteTree page to the stage site.
2309
     *
2310
     * @return self
2311
     */
2312
    public function doRestoreToStage()
2313
    {
2314
        $this->invokeWithExtensions('onBeforeRestoreToStage', $this);
2315
2316
        // Ensure that the parent page is restored, otherwise restore to root
2317
        if ($this->isParentArchived()) {
2318
            $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...
2319
        }
2320
2321
        // if no record can be found on draft stage (meaning it has been "deleted from draft" before),
2322
        // create an empty record
2323
        if (!DB::prepared_query("SELECT \"ID\" FROM \"SiteTree\" WHERE \"ID\" = ?", array($this->ID))->value()) {
2324
            $conn = DB::get_conn();
2325
            if (method_exists($conn, 'allowPrimaryKeyEditing')) {
2326
                $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...
2327
            }
2328
            DB::prepared_query("INSERT INTO \"SiteTree\" (\"ID\") VALUES (?)", array($this->ID));
2329
            if (method_exists($conn, 'allowPrimaryKeyEditing')) {
2330
                $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...
2331
            }
2332
        }
2333
2334
        $oldReadingMode = Versioned::get_reading_mode();
2335
        Versioned::set_stage(Versioned::DRAFT);
2336
        $this->forceChange();
2337
        $this->write();
2338
2339
        /** @var SiteTree $result */
2340
        $result = DataObject::get_by_id(self::class, $this->ID);
2341
2342
        // Need to update pages linking to this one as no longer broken
2343
        foreach ($result->DependentPages(false) as $page) {
2344
            // $page->write() calls syncLinkTracking, which does all the hard work for us.
2345
            $page->write();
2346
        }
2347
2348
        Versioned::set_reading_mode($oldReadingMode);
2349
2350
        $this->invokeWithExtensions('onAfterRestoreToStage', $this);
2351
2352
        return $result;
2353
    }
2354
2355
    /**
2356
     * Check if this page is new - that is, if it has yet to have been written to the database.
2357
     *
2358
     * @return bool
2359
     */
2360
    public function isNew()
2361
    {
2362
        /**
2363
         * This check was a problem for a self-hosted site, and may indicate a bug in the interpreter on their server,
2364
         * or a bug here. Changing the condition from empty($this->ID) to !$this->ID && !$this->record['ID'] fixed this.
2365
         */
2366
        if (empty($this->ID)) {
2367
            return true;
2368
        }
2369
2370
        if (is_numeric($this->ID)) {
2371
            return false;
2372
        }
2373
2374
        return stripos($this->ID, 'new') === 0;
2375
    }
2376
2377
    /**
2378
     * Get the class dropdown used in the CMS to change the class of a page. This returns the list of options in the
2379
     * dropdown as a Map from class name to singular name. Filters by {@link SiteTree->canCreate()}, as well as
2380
     * {@link SiteTree::$needs_permission}.
2381
     *
2382
     * @return array
2383
     */
2384
    protected function getClassDropdown()
2385
    {
2386
        $classes = self::page_type_classes();
2387
        $currentClass = null;
2388
2389
        $result = array();
2390
        foreach ($classes as $class) {
2391
            $instance = singleton($class);
2392
2393
            // if the current page type is this the same as the class type always show the page type in the list
2394
            if ($this->ClassName != $instance->ClassName) {
2395
                if ($instance instanceof HiddenClass) {
2396
                    continue;
2397
                }
2398
                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...
2399
                    continue;
2400
                }
2401
            }
2402
2403
            if ($perms = $instance->stat('need_permission')) {
2404
                if (!$this->can($perms)) {
2405
                    continue;
2406
                }
2407
            }
2408
2409
            $pageTypeName = $instance->i18n_singular_name();
2410
2411
            $currentClass = $class;
2412
            $result[$class] = $pageTypeName;
2413
2414
            // If we're in translation mode, the link between the translated pagetype title and the actual classname
2415
            // might not be obvious, so we add it in parantheses. Example: class "RedirectorPage" has the title
2416
            // "Weiterleitung" in German, so it shows up as "Weiterleitung (RedirectorPage)"
2417
            if (i18n::getData()->langFromLocale(i18n::get_locale()) != 'en') {
2418
                $result[$class] = $result[$class] .  " ({$class})";
2419
            }
2420
        }
2421
2422
        // sort alphabetically, and put current on top
2423
        asort($result);
2424
        if ($currentClass) {
2425
            $currentPageTypeName = $result[$currentClass];
2426
            unset($result[$currentClass]);
2427
            $result = array_reverse($result);
2428
            $result[$currentClass] = $currentPageTypeName;
2429
            $result = array_reverse($result);
2430
        }
2431
2432
        return $result;
2433
    }
2434
2435
    /**
2436
     * Returns an array of the class names of classes that are allowed to be children of this class.
2437
     *
2438
     * @return string[]
2439
     */
2440
    public function allowedChildren()
2441
    {
2442
        // Get config based on old FIRST_SET rules
2443
        $candidates = null;
2444
        $class = get_class($this);
2445
        while ($class) {
2446
            if (Config::inst()->exists($class, 'allowed_children', Config::UNINHERITED)) {
2447
                $candidates = Config::inst()->get($class, 'allowed_children', Config::UNINHERITED);
2448
                break;
2449
            }
2450
            $class = get_parent_class($class);
2451
        }
2452
        if (!$candidates || $candidates === 'none' || $candidates === 'SiteTree_root') {
2453
            return [];
2454
        }
2455
2456
        // Parse candidate list
2457
        $allowedChildren = [];
2458
        foreach ($candidates as $candidate) {
2459
            // If a classname is prefixed by "*", such as "*Page", then only that class is allowed - no subclasses.
2460
            // Otherwise, the class and all its subclasses are allowed.
2461
            if (substr($candidate, 0, 1) == '*') {
2462
                $allowedChildren[] = substr($candidate, 1);
2463
            } elseif ($subclasses = ClassInfo::subclassesFor($candidate)) {
2464
                foreach ($subclasses as $subclass) {
2465
                    if ($subclass == 'SiteTree_root' || singleton($subclass) instanceof HiddenClass) {
2466
                        continue;
2467
                    }
2468
                    $allowedChildren[] = $subclass;
2469
                }
2470
            }
2471
        }
2472
        return $allowedChildren;
2473
    }
2474
2475
    /**
2476
     * Returns the class name of the default class for children of this page.
2477
     *
2478
     * @return string
2479
     */
2480
    public function defaultChild()
2481
    {
2482
        $default = $this->stat('default_child');
2483
        $allowed = $this->allowedChildren();
2484
        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...
2485
            if (!$default || !in_array($default, $allowed)) {
2486
                $default = reset($allowed);
2487
            }
2488
            return $default;
2489
        }
2490
        return null;
2491
    }
2492
2493
    /**
2494
     * Returns the class name of the default class for the parent of this page.
2495
     *
2496
     * @return string
2497
     */
2498
    public function defaultParent()
2499
    {
2500
        return $this->stat('default_parent');
2501
    }
2502
2503
    /**
2504
     * Get the title for use in menus for this page. If the MenuTitle field is set it returns that, else it returns the
2505
     * Title field.
2506
     *
2507
     * @return string
2508
     */
2509
    public function getMenuTitle()
2510
    {
2511
        if ($value = $this->getField("MenuTitle")) {
2512
            return $value;
2513
        } else {
2514
            return $this->getField("Title");
2515
        }
2516
    }
2517
2518
2519
    /**
2520
     * Set the menu title for this page.
2521
     *
2522
     * @param string $value
2523
     */
2524
    public function setMenuTitle($value)
2525
    {
2526
        if ($value == $this->getField("Title")) {
2527
            $this->setField("MenuTitle", null);
2528
        } else {
2529
            $this->setField("MenuTitle", $value);
2530
        }
2531
    }
2532
2533
    /**
2534
     * A flag provides the user with additional data about the current page status, for example a "removed from draft"
2535
     * status. Each page can have more than one status flag. Returns a map of a unique key to a (localized) title for
2536
     * the flag. The unique key can be reused as a CSS class. Use the 'updateStatusFlags' extension point to customize
2537
     * the flags.
2538
     *
2539
     * Example (simple):
2540
     *   "deletedonlive" => "Deleted"
2541
     *
2542
     * Example (with optional title attribute):
2543
     *   "deletedonlive" => array('text' => "Deleted", 'title' => 'This page has been deleted')
2544
     *
2545
     * @param bool $cached Whether to serve the fields from cache; false regenerate them
2546
     * @return array
2547
     */
2548
    public function getStatusFlags($cached = true)
2549
    {
2550
        if (!$this->_cache_statusFlags || !$cached) {
2551
            $flags = array();
2552
            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...
2553
                $flags['removedfromdraft'] = array(
2554
                    'text' => _t(__CLASS__.'.ONLIVEONLYSHORT', 'On live only'),
2555
                    'title' => _t(__CLASS__.'.ONLIVEONLYSHORTHELP', 'Page is published, but has been deleted from draft'),
2556
                );
2557
            } 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...
2558
                $flags['archived'] = array(
2559
                    'text' => _t(__CLASS__.'.ARCHIVEDPAGESHORT', 'Archived'),
2560
                    'title' => _t(__CLASS__.'.ARCHIVEDPAGEHELP', 'Page is removed from draft and live'),
2561
                );
2562
            } 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...
2563
                $flags['addedtodraft'] = array(
2564
                    'text' => _t(__CLASS__.'.ADDEDTODRAFTSHORT', 'Draft'),
2565
                    'title' => _t(__CLASS__.'.ADDEDTODRAFTHELP', "Page has not been published yet")
2566
                );
2567
            } 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...
2568
                $flags['modified'] = array(
2569
                    'text' => _t(__CLASS__.'.MODIFIEDONDRAFTSHORT', 'Modified'),
2570
                    'title' => _t(__CLASS__.'.MODIFIEDONDRAFTHELP', 'Page has unpublished changes'),
2571
                );
2572
            }
2573
2574
            $this->extend('updateStatusFlags', $flags);
2575
2576
            $this->_cache_statusFlags = $flags;
2577
        }
2578
2579
        return $this->_cache_statusFlags;
2580
    }
2581
2582
    /**
2583
     * getTreeTitle will return three <span> html DOM elements, an empty <span> with the class 'jstree-pageicon' in
2584
     * front, following by a <span> wrapping around its MenutTitle, then following by a <span> indicating its
2585
     * publication status.
2586
     *
2587
     * @return string An HTML string ready to be directly used in a template
2588
     */
2589
    public function getTreeTitle()
2590
    {
2591
        // Build the list of candidate children
2592
        $children = array();
2593
        $candidates = static::page_type_classes();
2594
        foreach ($this->allowedChildren() as $childClass) {
2595
            if (!in_array($childClass, $candidates)) {
2596
                continue;
2597
            }
2598
            $child = singleton($childClass);
2599
            if ($child->canCreate(null, array('Parent' => $this))) {
2600
                $children[$childClass] = $child->i18n_singular_name();
2601
            }
2602
        }
2603
        $flags = $this->getStatusFlags();
2604
        $treeTitle = sprintf(
2605
            "<span class=\"jstree-pageicon\"></span><span class=\"item\" data-allowedchildren=\"%s\">%s</span>",
2606
            Convert::raw2att(Convert::raw2json($children)),
2607
            Convert::raw2xml(str_replace(array("\n","\r"), "", $this->MenuTitle))
2608
        );
2609
        foreach ($flags as $class => $data) {
2610
            if (is_string($data)) {
2611
                $data = array('text' => $data);
2612
            }
2613
            $treeTitle .= sprintf(
2614
                "<span class=\"badge %s\"%s>%s</span>",
2615
                'status-' . Convert::raw2xml($class),
2616
                (isset($data['title'])) ? sprintf(' title="%s"', Convert::raw2xml($data['title'])) : '',
2617
                Convert::raw2xml($data['text'])
2618
            );
2619
        }
2620
2621
        return $treeTitle;
2622
    }
2623
2624
    /**
2625
     * Returns the page in the current page stack of the given level. Level(1) will return the main menu item that
2626
     * we're currently inside, etc.
2627
     *
2628
     * @param int $level
2629
     * @return SiteTree
2630
     */
2631
    public function Level($level)
2632
    {
2633
        $parent = $this;
2634
        $stack = array($parent);
2635
        while (($parent = $parent->Parent()) && $parent->exists()) {
2636
            array_unshift($stack, $parent);
2637
        }
2638
2639
        return isset($stack[$level-1]) ? $stack[$level-1] : null;
2640
    }
2641
2642
    /**
2643
     * Gets the depth of this page in the sitetree, where 1 is the root level
2644
     *
2645
     * @return int
2646
     */
2647
    public function getPageLevel()
2648
    {
2649
        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...
2650
            return 1 + $this->Parent()->getPageLevel();
2651
        }
2652
        return 1;
2653
    }
2654
2655
    /**
2656
     * Find the controller name by our convention of {$ModelClass}Controller
2657
     *
2658
     * @return string
2659
     */
2660
    public function getControllerName()
2661
    {
2662
        //default controller for SiteTree objects
2663
        $controller = ContentController::class;
2664
2665
        //go through the ancestry for this class looking for
2666
        $ancestry = ClassInfo::ancestry(static::class);
2667
        // loop over the array going from the deepest descendant (ie: the current class) to SiteTree
2668
        while ($class = array_pop($ancestry)) {
2669
            //we don't need to go any deeper than the SiteTree class
2670
            if ($class == SiteTree::class) {
2671
                break;
2672
            }
2673
            // If we have a class of "{$ClassName}Controller" then we found our controller
2674
            if (class_exists($candidate = sprintf('%sController', $class))) {
2675
                $controller = $candidate;
2676
                break;
2677
            } elseif (class_exists($candidate = sprintf('%s_Controller', $class))) {
2678
                // Support the legacy underscored filename, but raise a deprecation notice
2679
                Deprecation::notice(
2680
                    '5.0',
2681
                    'Underscored controller class names are deprecated. Use "MyController" instead of "My_Controller".',
2682
                    Deprecation::SCOPE_GLOBAL
2683
                );
2684
                $controller = $candidate;
2685
                break;
2686
            }
2687
        }
2688
2689
        return $controller;
2690
    }
2691
2692
    /**
2693
     * Return the CSS classes to apply to this node in the CMS tree.
2694
     *
2695
     * @return string
2696
     */
2697
    public function CMSTreeClasses()
2698
    {
2699
        $classes = sprintf('class-%s', static::class);
2700
        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...
2701
            $classes .= " BrokenLink";
2702
        }
2703
2704
        if (!$this->canAddChildren()) {
2705
            $classes .= " nochildren";
2706
        }
2707
2708
        if (!$this->canEdit() && !$this->canAddChildren()) {
2709
            if (!$this->canView()) {
2710
                $classes .= " disabled";
2711
            } else {
2712
                $classes .= " edit-disabled";
2713
            }
2714
        }
2715
2716
        if (!$this->ShowInMenus) {
2717
            $classes .= " notinmenu";
2718
        }
2719
2720
        return $classes;
2721
    }
2722
2723
    /**
2724
     * Stops extendCMSFields() being called on getCMSFields(). This is useful when you need access to fields added by
2725
     * subclasses of SiteTree in a extension. Call before calling parent::getCMSFields(), and reenable afterwards.
2726
     */
2727
    public static function disableCMSFieldsExtensions()
2728
    {
2729
        self::$runCMSFieldsExtensions = false;
2730
    }
2731
2732
    /**
2733
     * Reenables extendCMSFields() being called on getCMSFields() after it has been disabled by
2734
     * disableCMSFieldsExtensions().
2735
     */
2736
    public static function enableCMSFieldsExtensions()
2737
    {
2738
        self::$runCMSFieldsExtensions = true;
2739
    }
2740
2741
    public function providePermissions()
2742
    {
2743
        return array(
2744
            'SITETREE_GRANT_ACCESS' => array(
2745
                'name' => _t(__CLASS__.'.PERMISSION_GRANTACCESS_DESCRIPTION', 'Manage access rights for content'),
2746
                'help' => _t(__CLASS__.'.PERMISSION_GRANTACCESS_HELP', 'Allow setting of page-specific access restrictions in the "Pages" section.'),
2747
                'category' => _t('SilverStripe\\Security\\Permission.PERMISSIONS_CATEGORY', 'Roles and access permissions'),
2748
                'sort' => 100
2749
            ),
2750
            'SITETREE_VIEW_ALL' => array(
2751
                'name' => _t(__CLASS__.'.VIEW_ALL_DESCRIPTION', 'View any page'),
2752
                'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'),
2753
                'sort' => -100,
2754
                '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')
2755
            ),
2756
            'SITETREE_EDIT_ALL' => array(
2757
                'name' => _t(__CLASS__.'.EDIT_ALL_DESCRIPTION', 'Edit any page'),
2758
                'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'),
2759
                'sort' => -50,
2760
                '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')
2761
            ),
2762
            'SITETREE_REORGANISE' => array(
2763
                'name' => _t(__CLASS__.'.REORGANISE_DESCRIPTION', 'Change site structure'),
2764
                'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'),
2765
                'help' => _t(__CLASS__.'.REORGANISE_HELP', 'Rearrange pages in the site tree through drag&drop.'),
2766
                'sort' => 100
2767
            ),
2768
            'VIEW_DRAFT_CONTENT' => array(
2769
                'name' => _t(__CLASS__.'.VIEW_DRAFT_CONTENT', 'View draft content'),
2770
                'category' => _t('SilverStripe\\Security\\Permission.CONTENT_CATEGORY', 'Content permissions'),
2771
                '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.'),
2772
                'sort' => 100
2773
            )
2774
        );
2775
    }
2776
2777
    /**
2778
     * Default singular name for page / sitetree
2779
     *
2780
     * @return string
2781
     */
2782 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...
2783
    {
2784
        $base = in_array(static::class, [Page::class, self::class]);
2785
        if ($base) {
2786
            return $this->stat('base_singular_name');
2787
        }
2788
        return parent::singular_name();
2789
    }
2790
2791
    /**
2792
     * Default plural name for page / sitetree
2793
     *
2794
     * @return string
2795
     */
2796 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...
2797
    {
2798
        $base = in_array(static::class, [Page::class, self::class]);
2799
        if ($base) {
2800
            return $this->stat('base_plural_name');
2801
        }
2802
        return parent::plural_name();
2803
    }
2804
2805
    /**
2806
     * Get description for this page type
2807
     *
2808
     * @return string|null
2809
     */
2810
    public function classDescription()
2811
    {
2812
        $base = in_array(static::class, [Page::class, self::class]);
2813
        if ($base) {
2814
            return $this->stat('base_description');
2815
        }
2816
        return $this->stat('description');
2817
    }
2818
2819
    /**
2820
     * Get localised description for this page
2821
     *
2822
     * @return string|null
2823
     */
2824
    public function i18n_classDescription()
2825
    {
2826
        $description = $this->classDescription();
2827
        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...
2828
            return _t(static::class.'.DESCRIPTION', $description);
2829
        }
2830
        return null;
2831
    }
2832
2833
    /**
2834
     * Overloaded to also provide entities for 'Page' class which is usually located in custom code, hence textcollector
2835
     * picks it up for the wrong folder.
2836
     *
2837
     * @return array
2838
     */
2839
    public function provideI18nEntities()
2840
    {
2841
        $entities = parent::provideI18nEntities();
2842
2843
        // Add optional description
2844
        $description = $this->classDescription();
2845
        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...
2846
            $entities[static::class . '.DESCRIPTION'] = $description;
2847
        }
2848
        return $entities;
2849
    }
2850
2851
    /**
2852
     * Returns 'root' if the current page has no parent, or 'subpage' otherwise
2853
     *
2854
     * @return string
2855
     */
2856
    public function getParentType()
2857
    {
2858
        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...
2859
    }
2860
}
2861