Completed
Pull Request — master (#1464)
by Damian
02:56
created

SiteTree::getTreeTitle()   C

Complexity

Conditions 7
Paths 12

Size

Total Lines 29
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 29
rs 6.7272
cc 7
eloc 21
nc 12
nop 0
1
<?php
2
/**
3
 * Basic data-object representing all pages within the site tree. All page types that live within the hierarchy should
4
 * inherit from this. In addition, it contains a number of static methods for querying the site tree and working with
5
 * draft and published states.
6
 *
7
 * <h2>URLs</h2>
8
 * A page is identified during request handling via its "URLSegment" database column. As pages can be nested, the full
9
 * path of a URL might contain multiple segments. Each segment is stored in its filtered representation (through
10
 * {@link URLSegmentFilter}). The full path is constructed via {@link Link()}, {@link RelativeLink()} and
11
 * {@link AbsoluteLink()}. You can allow these segments to contain multibyte characters through
12
 * {@link URLSegmentFilter::$default_allow_multibyte}.
13
 *
14
 * @property string URLSegment
15
 * @property string Title
16
 * @property string MenuTitle
17
 * @property string Content HTML content of the page.
18
 * @property string MetaDescription
19
 * @property string ExtraMeta
20
 * @property string ShowInMenus
21
 * @property string ShowInSearch
22
 * @property string Sort Integer value denoting the sort order.
23
 * @property string ReportClass
24
 * @property string CanViewType Type of restriction for viewing this object.
25
 * @property string CanEditType Type of restriction for editing this object.
26
 *
27
 * @method ManyManyList ViewerGroups List of groups that can view this object.
28
 * @method ManyManyList EditorGroups List of groups that can edit this object.
29
 *
30
 * @mixin Hierarchy
31
 * @mixin Versioned
32
 * @mixin SiteTreeLinkTracking
33
 *
34
 * @package cms
35
 */
36
class SiteTree extends DataObject implements PermissionProvider,i18nEntityProvider,CMSPreviewable {
37
38
	/**
39
	 * Indicates what kind of children this page type can have.
40
	 * This can be an array of allowed child classes, or the string "none" -
41
	 * indicating that this page type can't have children.
42
	 * If a classname is prefixed by "*", such as "*Page", then only that
43
	 * class is allowed - no subclasses. Otherwise, the class and all its
44
	 * subclasses are allowed.
45
	 * To control allowed children on root level (no parent), use {@link $can_be_root}.
46
	 *
47
	 * Note that this setting is cached when used in the CMS, use the "flush" query parameter to clear it.
48
	 *
49
	 * @config
50
	 * @var array
51
	 */
52
	private static $allowed_children = array("SiteTree");
53
54
	/**
55
	 * The default child class for this page.
56
	 * Note: Value might be cached, see {@link $allowed_chilren}.
57
	 *
58
	 * @config
59
	 * @var string
60
	 */
61
	private static $default_child = "Page";
62
63
	/**
64
	 * Default value for SiteTree.ClassName enum
65
	 * {@see DBClassName::getDefault}
66
	 *
67
	 * @config
68
	 * @var string
69
	 */
70
	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...
71
72
	/**
73
	 * The default parent class for this page.
74
	 * Note: Value might be cached, see {@link $allowed_chilren}.
75
	 *
76
	 * @config
77
	 * @var string
78
	 */
79
	private static $default_parent = null;
80
81
	/**
82
	 * Controls whether a page can be in the root of the site tree.
83
	 * Note: Value might be cached, see {@link $allowed_chilren}.
84
	 *
85
	 * @config
86
	 * @var bool
87
	 */
88
	private static $can_be_root = true;
89
90
	/**
91
	 * List of permission codes a user can have to allow a user to create a page of this type.
92
	 * Note: Value might be cached, see {@link $allowed_chilren}.
93
	 *
94
	 * @config
95
	 * @var array
96
	 */
97
	private static $need_permission = null;
98
99
	/**
100
	 * If you extend a class, and don't want to be able to select the old class
101
	 * in the cms, set this to the old class name. Eg, if you extended Product
102
	 * to make ImprovedProduct, then you would set $hide_ancestor to Product.
103
	 *
104
	 * @config
105
	 * @var string
106
	 */
107
	private static $hide_ancestor = null;
108
109
	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...
110
		"URLSegment" => "Varchar(255)",
111
		"Title" => "Varchar(255)",
112
		"MenuTitle" => "Varchar(100)",
113
		"Content" => "HTMLText",
114
		"MetaDescription" => "Text",
115
		"ExtraMeta" => "HTMLText('meta, link')",
116
		"ShowInMenus" => "Boolean",
117
		"ShowInSearch" => "Boolean",
118
		"Sort" => "Int",
119
		"HasBrokenFile" => "Boolean",
120
		"HasBrokenLink" => "Boolean",
121
		"ReportClass" => "Varchar",
122
		"CanViewType" => "Enum('Anyone, LoggedInUsers, OnlyTheseUsers, Inherit', 'Inherit')",
123
		"CanEditType" => "Enum('LoggedInUsers, OnlyTheseUsers, Inherit', 'Inherit')",
124
	);
125
126
	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...
127
		"URLSegment" => true,
128
	);
129
130
	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...
131
		"ViewerGroups" => "Group",
132
		"EditorGroups" => "Group",
133
	);
134
135
	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...
136
		"VirtualPages" => "VirtualPage.CopyContentFrom"
137
	);
138
139
	private static $owned_by = array(
140
		"VirtualPages"
141
	);
142
143
	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...
144
		"Breadcrumbs" => "HTMLText",
145
		"LastEdited" => "SS_Datetime",
146
		"Created" => "SS_Datetime",
147
		'Link' => 'Text',
148
		'RelativeLink' => 'Text',
149
		'AbsoluteLink' => 'Text',
150
		'TreeTitle' => 'HTMLText',
151
	);
152
153
	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...
154
		"ShowInMenus" => 1,
155
		"ShowInSearch" => 1,
156
		"CanViewType" => "Inherit",
157
		"CanEditType" => "Inherit"
158
	);
159
160
	private static $versioning = array(
161
		"Stage",  "Live"
162
	);
163
164
	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...
165
166
	/**
167
	 * If this is false, the class cannot be created in the CMS by regular content authors, only by ADMINs.
168
	 * @var boolean
169
	 * @config
170
	 */
171
	private static $can_create = true;
172
173
	/**
174
	 * Icon to use in the CMS page tree. This should be the full filename, relative to the webroot.
175
	 * Also supports custom CSS rule contents (applied to the correct selector for the tree UI implementation).
176
	 *
177
	 * @see CMSMain::generateTreeStylingCSS()
178
	 * @config
179
	 * @var string
180
	 */
181
	private static $icon = null;
182
183
	/**
184
	 * @config
185
	 * @var string Description of the class functionality, typically shown to a user
186
	 * when selecting which page type to create. Translated through {@link provideI18nEntities()}.
187
	 */
188
	private static $description = 'Generic content page';
189
190
	private static $extensions = 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...
191
		"Hierarchy",
192
		"Versioned",
193
		"SiteTreeLinkTracking"
194
	);
195
196
	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...
197
		'Title',
198
		'Content',
199
	);
200
201
	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...
202
		'URLSegment' => 'URL'
203
	);
204
205
	/**
206
	 * @config
207
	 */
208
	private static $nested_urls = true;
209
210
	/**
211
	 * @config
212
	*/
213
	private static $create_default_pages = true;
214
215
	/**
216
	 * This controls whether of not extendCMSFields() is called by getCMSFields.
217
	 */
218
	private static $runCMSFieldsExtensions = true;
219
220
	/**
221
	 * Cache for canView/Edit/Publish/Delete permissions.
222
	 * Keyed by permission type (e.g. 'edit'), with an array
223
	 * of IDs mapped to their boolean permission ability (true=allow, false=deny).
224
	 * See {@link batch_permission_check()} for details.
225
	 */
226
	private static $cache_permissions = array();
227
228
	/**
229
	 * @config
230
	 * @var boolean
231
	 */
232
	private static $enforce_strict_hierarchy = true;
233
234
	/**
235
	 * The value used for the meta generator tag. Leave blank to omit the tag.
236
	 *
237
	 * @config
238
	 * @var string
239
	 */
240
	private static $meta_generator = 'SilverStripe - http://silverstripe.org';
241
242
	protected $_cache_statusFlags = null;
243
244
	/**
245
	 * Fetches the {@link SiteTree} object that maps to a link.
246
	 *
247
	 * If you have enabled {@link SiteTree::config()->nested_urls} on this site, then you can use a nested link such as
248
	 * "about-us/staff/", and this function will traverse down the URL chain and grab the appropriate link.
249
	 *
250
	 * Note that if no model can be found, this method will fall over to a extended alternateGetByLink method provided
251
	 * by a extension attached to {@link SiteTree}
252
	 *
253
	 * @param string $link  The link of the page to search for
254
	 * @param bool   $cache True (default) to use caching, false to force a fresh search from the database
255
	 * @return SiteTree
256
	 */
257
	static public function get_by_link($link, $cache = true) {
258
		if(trim($link, '/')) {
259
			$link = trim(Director::makeRelative($link), '/');
260
		} else {
261
			$link = RootURLController::get_homepage_link();
262
		}
263
264
		$parts = preg_split('|/+|', $link);
265
266
		// Grab the initial root level page to traverse down from.
267
		$URLSegment = array_shift($parts);
268
		$conditions = array('"SiteTree"."URLSegment"' => rawurlencode($URLSegment));
269
		if(self::config()->nested_urls) {
270
			$conditions[] = array('"SiteTree"."ParentID"' => 0);
271
		}
272
		$sitetree = DataObject::get_one('SiteTree', $conditions, $cache);
273
274
		/// Fall back on a unique URLSegment for b/c.
275
		if(	!$sitetree
276
			&& self::config()->nested_urls
277
			&& $page = DataObject::get_one('SiteTree', array(
278
				'"SiteTree"."URLSegment"' => $URLSegment
279
			), $cache)
280
		) {
281
			return $page;
282
		}
283
284
		// Attempt to grab an alternative page from extensions.
285
		if(!$sitetree) {
286
			$parentID = self::config()->nested_urls ? 0 : null;
287
288 View Code Duplication
			if($alternatives = singleton('SiteTree')->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...
289
				foreach($alternatives as $alternative) if($alternative) $sitetree = $alternative;
290
			}
291
292
			if(!$sitetree) return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by SiteTree::get_by_link of type SiteTree.

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

Let’s take a look at an example:

class Author {
    private $name;

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

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

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

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

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

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

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

Loading history...
293
		}
294
295
		// Check if we have any more URL parts to parse.
296
		if(!self::config()->nested_urls || !count($parts)) return $sitetree;
297
298
		// Traverse down the remaining URL segments and grab the relevant SiteTree objects.
299
		foreach($parts as $segment) {
300
			$next = DataObject::get_one('SiteTree', array(
301
					'"SiteTree"."URLSegment"' => $segment,
302
					'"SiteTree"."ParentID"' => $sitetree->ID
303
				),
304
				$cache
305
			);
306
307
			if(!$next) {
308
				$parentID = (int) $sitetree->ID;
309
310 View Code Duplication
				if($alternatives = singleton('SiteTree')->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...
311
					foreach($alternatives as $alternative) if($alternative) $next = $alternative;
312
				}
313
314
				if(!$next) return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by SiteTree::get_by_link of type SiteTree.

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

Let’s take a look at an example:

class Author {
    private $name;

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

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

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

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

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

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

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

Loading history...
315
			}
316
317
			$sitetree->destroy();
318
			$sitetree = $next;
319
		}
320
321
		return $sitetree;
322
	}
323
324
	/**
325
	 * Return a subclass map of SiteTree that shouldn't be hidden through {@link SiteTree::$hide_ancestor}
326
	 *
327
	 * @return array
328
	 */
329
	public static function page_type_classes() {
330
		$classes = ClassInfo::getValidSubClasses();
331
332
		$baseClassIndex = array_search('SiteTree', $classes);
333
		if($baseClassIndex !== FALSE) unset($classes[$baseClassIndex]);
334
335
		$kill_ancestors = array();
336
337
		// figure out if there are any classes we don't want to appear
338
		foreach($classes as $class) {
339
			$instance = singleton($class);
340
341
			// do any of the progeny want to hide an ancestor?
342
			if($ancestor_to_hide = $instance->stat('hide_ancestor')) {
343
				// note for killing later
344
				$kill_ancestors[] = $ancestor_to_hide;
345
			}
346
		}
347
348
		// If any of the descendents don't want any of the elders to show up, cruelly render the elders surplus to
349
		// requirements
350
		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...
351
			$kill_ancestors = array_unique($kill_ancestors);
352
			foreach($kill_ancestors as $mark) {
353
				// unset from $classes
354
				$idx = array_search($mark, $classes, true);
355
				if ($idx !== false) {
356
					unset($classes[$idx]);
357
				}
358
			}
359
		}
360
361
		return $classes;
362
	}
363
364
	/**
365
	 * Replace a "[sitetree_link id=n]" shortcode with a link to the page with the corresponding ID.
366
	 *
367
	 * @param array      $arguments
368
	 * @param string     $content
369
	 * @param TextParser $parser
370
	 * @return string
371
	 */
372
	static public function link_shortcode_handler($arguments, $content = null, $parser = null) {
373
		if(!isset($arguments['id']) || !is_numeric($arguments['id'])) return;
374
375
		if (
376
			   !($page = DataObject::get_by_id('SiteTree', $arguments['id']))         // Get the current page by ID.
377
			&& !($page = Versioned::get_latest_version('SiteTree', $arguments['id'])) // Attempt link to old version.
378
		) {
379
			 return null; // There were no suitable matches at all.
380
		}
381
382
		$link = Convert::raw2att($page->Link());
383
384
		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...
385
			return sprintf('<a href="%s">%s</a>', $link, $parser->parse($content));
0 ignored issues
show
Unused Code introduced by
The call to TextParser::parse() has too many arguments starting with $content.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
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...
386
		} else {
387
			return $link;
388
		}
389
	}
390
391
	/**
392
	 * Return the link for this {@link SiteTree} object, with the {@link Director::baseURL()} included.
393
	 *
394
	 * @param string $action Optional controller action (method).
395
	 *                       Note: URI encoding of this parameter is applied automatically through template casting,
396
	 *                       don't encode the passed parameter. Please use {@link Controller::join_links()} instead to
397
	 *                       append GET parameters.
398
	 * @return string
399
	 */
400
	public function Link($action = null) {
401
		return Controller::join_links(Director::baseURL(), $this->RelativeLink($action));
402
	}
403
404
	/**
405
	 * Get the absolute URL for this page, including protocol and host.
406
	 *
407
	 * @param string $action See {@link Link()}
408
	 * @return string
409
	 */
410
	public function AbsoluteLink($action = null) {
411
		if($this->hasMethod('alternateAbsoluteLink')) {
412
			return $this->alternateAbsoluteLink($action);
0 ignored issues
show
Bug introduced by
The method alternateAbsoluteLink() does not exist on 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...
413
		} else {
414
			return Director::absoluteURL($this->Link($action));
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression \Director::absoluteURL($this->Link($action)); of type string|false adds false to the return on line 414 which is incompatible with the return type documented by SiteTree::AbsoluteLink of type string. It seems like you forgot to handle an error condition.
Loading history...
415
		}
416
	}
417
418
	/**
419
	 * Base link used for previewing. Defaults to absolute URL, in order to account for domain changes, e.g. on multi
420
	 * site setups. Does not contain hints about the stage, see {@link SilverStripeNavigator} for details.
421
	 *
422
	 * @param string $action See {@link Link()}
423
	 * @return string
424
	 */
425
	public function PreviewLink($action = null) {
426
		if($this->hasMethod('alternatePreviewLink')) {
427
			Deprecation::notice('5.0', 'Use updatePreviewLink or override PreviewLink method');
428
			return $this->alternatePreviewLink($action);
0 ignored issues
show
Bug introduced by
The method alternatePreviewLink() does not exist on 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...
429
		}
430
431
		$link = $this->AbsoluteLink($action);
432
		$this->extend('updatePreviewLink', $link, $action);
433
		return $link;
434
	}
435
436
	public function getMimeType() {
437
		return 'text/html';
438
	}
439
440
	/**
441
	 * Return the link for this {@link SiteTree} object relative to the SilverStripe root.
442
	 *
443
	 * By default, if this page is the current home page, and there is no action specified then this will return a link
444
	 * to the root of the site. However, if you set the $action parameter to TRUE then the link will not be rewritten
445
	 * and returned in its full form.
446
	 *
447
	 * @uses RootURLController::get_homepage_link()
448
	 *
449
	 * @param string $action See {@link Link()}
450
	 * @return string
451
	 */
452
	public function RelativeLink($action = null) {
453
		if($this->ParentID && self::config()->nested_urls) {
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<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...
454
			$parent = $this->Parent();
0 ignored issues
show
Bug introduced by
The method Parent() does not exist on SiteTree. Did you maybe mean setParent()?

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...
455
			// If page is removed select parent from version history (for archive page view)
456
			if((!$parent || !$parent->exists()) && $this->IsDeletedFromStage) {
0 ignored issues
show
Documentation introduced by
The property IsDeletedFromStage does not exist on object<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...
457
				$parent = Versioned::get_latest_version('SiteTree', $this->ParentID);
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<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...
458
			}
459
			$base = $parent->RelativeLink($this->URLSegment);
460
		} 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...
461
			// Unset base for root-level homepages.
462
			// Note: Homepages with action parameters (or $action === true)
463
			// need to retain their URLSegment.
464
			$base = null;
465
		} else {
466
			$base = $this->URLSegment;
467
		}
468
469
		$this->extend('updateRelativeLink', $base, $action);
470
471
		// Legacy support: If $action === true, retain URLSegment for homepages,
472
		// but don't append any action
473
		if($action === true) $action = null;
474
475
		return Controller::join_links($base, '/', $action);
476
	}
477
478
	/**
479
	 * Get the absolute URL for this page on the Live site.
480
	 *
481
	 * @param bool $includeStageEqualsLive Whether to append the URL with ?stage=Live to force Live mode
482
	 * @return string
483
	 */
484
	public function getAbsoluteLiveLink($includeStageEqualsLive = true) {
485
		$oldStage = Versioned::get_stage();
486
		Versioned::set_stage(Versioned::LIVE);
487
		$live = Versioned::get_one_by_stage('SiteTree', Versioned::LIVE, array(
0 ignored issues
show
Documentation introduced by
array('"SiteTree"."ID"' => $this->ID) is of type array<string,integer,{"\...e\".\"ID\"":"integer"}>, 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...
488
			'"SiteTree"."ID"' => $this->ID
489
		));
490
		if($live) {
491
			$link = $live->AbsoluteLink();
492
			if($includeStageEqualsLive) $link .= '?stage=Live';
493
		} else {
494
			$link = null;
495
		}
496
497
		Versioned::set_stage($oldStage);
498
		return $link;
499
	}
500
501
	/**
502
	 * Generates a link to edit this page in the CMS.
503
	 *
504
	 * @return string
505
	 */
506
	public function CMSEditLink() {
507
		$link = Controller::join_links(
508
			singleton('CMSPageEditController')->Link('show'),
509
			$this->ID
510
		);
511
		return Director::absoluteURL($link);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The expression \Director::absoluteURL($link); of type string|false adds false to the return on line 511 which is incompatible with the return type declared by the interface CMSPreviewable::CMSEditLink of type string. It seems like you forgot to handle an error condition.
Loading history...
512
	}
513
514
515
	/**
516
	 * Return a CSS identifier generated from this page's link.
517
	 *
518
	 * @return string The URL segment
519
	 */
520
	public function ElementName() {
521
		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...
522
	}
523
524
	/**
525
	 * Returns true if this is the currently active page being used to handle this request.
526
	 *
527
	 * @return bool
528
	 */
529
	public function isCurrent() {
530
		return $this->ID ? $this->ID == Director::get_current_page()->ID : $this === Director::get_current_page();
531
	}
532
533
	/**
534
	 * Check if this page is in the currently active section (e.g. it is either current or one of its children is
535
	 * currently being viewed).
536
	 *
537
	 * @return bool
538
	 */
539
	public function isSection() {
540
		return $this->isCurrent() || (
541
			Director::get_current_page() instanceof SiteTree && in_array($this->ID, Director::get_current_page()->getAncestors()->column())
0 ignored issues
show
Documentation Bug introduced by
The method getAncestors does not exist on object<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...
542
		);
543
	}
544
545
	/**
546
	 * Check if the parent of this page has been removed (or made otherwise unavailable), and is still referenced by
547
	 * this child. Any such orphaned page may still require access via the CMS, but should not be shown as accessible
548
	 * to external users.
549
	 *
550
	 * @return bool
551
	 */
552
	public function isOrphaned() {
553
		// Always false for root pages
554
		if(empty($this->ParentID)) return false;
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<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...
555
556
		// Parent must exist and not be an orphan itself
557
		$parent = $this->Parent();
0 ignored issues
show
Bug introduced by
The method Parent() does not exist on SiteTree. Did you maybe mean setParent()?

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...
558
		return !$parent || !$parent->exists() || $parent->isOrphaned();
559
	}
560
561
	/**
562
	 * Return "link" or "current" depending on if this is the {@link SiteTree::isCurrent()} current page.
563
	 *
564
	 * @return string
565
	 */
566
	public function LinkOrCurrent() {
567
		return $this->isCurrent() ? 'current' : 'link';
568
	}
569
570
	/**
571
	 * Return "link" or "section" depending on if this is the {@link SiteTree::isSeciton()} current section.
572
	 *
573
	 * @return string
574
	 */
575
	public function LinkOrSection() {
576
		return $this->isSection() ? 'section' : 'link';
577
	}
578
579
	/**
580
	 * Return "link", "current" or "section" depending on if this page is the current page, or not on the current page
581
	 * but in the current section.
582
	 *
583
	 * @return string
584
	 */
585
	public function LinkingMode() {
586
		if($this->isCurrent()) {
587
			return 'current';
588
		} elseif($this->isSection()) {
589
			return 'section';
590
		} else {
591
			return 'link';
592
		}
593
	}
594
595
	/**
596
	 * Check if this page is in the given current section.
597
	 *
598
	 * @param string $sectionName Name of the section to check
599
	 * @return bool True if we are in the given section
600
	 */
601
	public function InSection($sectionName) {
602
		$page = Director::get_current_page();
603
		while($page) {
604
			if($sectionName == $page->URLSegment)
605
				return true;
606
			$page = $page->Parent;
607
		}
608
		return false;
609
	}
610
611
	/**
612
	 * Create a duplicate of this node. Doesn't affect joined data - create a custom overloading of this if you need
613
	 * such behaviour.
614
	 *
615
	 * @param bool $doWrite Whether to write the new object before returning it
616
	 * @return self The duplicated object
617
	 */
618
	 public function duplicate($doWrite = true) {
619
620
		$page = parent::duplicate(false);
621
		$page->Sort = 0;
622
		$this->invokeWithExtensions('onBeforeDuplicate', $page);
623
624
		if($doWrite) {
625
			$page->write();
626
627
			$page = $this->duplicateManyManyRelations($this, $page);
628
		}
629
		$this->invokeWithExtensions('onAfterDuplicate', $page);
630
631
		return $page;
632
	}
633
634
	/**
635
	 * Duplicates each child of this node recursively and returns the top-level duplicate node.
636
	 *
637
	 * @return self The duplicated object
638
	 */
639
	public function duplicateWithChildren() {
640
		$clone = $this->duplicate();
641
		$children = $this->AllChildren();
0 ignored issues
show
Documentation Bug introduced by
The method AllChildren does not exist on object<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...
642
643
		if($children) {
644
			foreach($children as $child) {
645
				$childClone = method_exists($child, 'duplicateWithChildren')
646
					? $child->duplicateWithChildren()
647
					: $child->duplicate();
648
				$childClone->ParentID = $clone->ID;
649
				$childClone->write();
650
			}
651
		}
652
653
		return $clone;
654
	}
655
656
	/**
657
	 * Duplicate this node and its children as a child of the node with the given ID
658
	 *
659
	 * @param int $id ID of the new node's new parent
660
	 */
661
	public function duplicateAsChild($id) {
662
		$newSiteTree = $this->duplicate();
663
		$newSiteTree->ParentID = $id;
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<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...
664
		$newSiteTree->Sort = 0;
665
		$newSiteTree->write();
666
	}
667
668
	/**
669
	 * Return a breadcrumb trail to this page. Excludes "hidden" pages (with ShowInMenus=0) by default.
670
	 *
671
	 * @param int $maxDepth The maximum depth to traverse.
672
	 * @param boolean $unlinked Whether to link page titles.
673
	 * @param boolean|string $stopAtPageType ClassName of a page to stop the upwards traversal.
674
	 * @param boolean $showHidden Include pages marked with the attribute ShowInMenus = 0
675
	 * @return HTMLText The breadcrumb trail.
676
	 */
677
	public function Breadcrumbs($maxDepth = 20, $unlinked = false, $stopAtPageType = false, $showHidden = false) {
678
		$pages = $this->getBreadcrumbItems($maxDepth, $stopAtPageType, $showHidden);
679
		$template = new SSViewer('BreadcrumbsTemplate');
680
		return $template->process($this->customise(new ArrayData(array(
681
			"Pages" => $pages,
682
			"Unlinked" => $unlinked
683
		))));
684
	}
685
686
687
	/**
688
	 * Returns a list of breadcrumbs for the current page.
689
	 *
690
	 * @param int $maxDepth The maximum depth to traverse.
691
	 * @param boolean|string $stopAtPageType ClassName of a page to stop the upwards traversal.
692
	 * @param boolean $showHidden Include pages marked with the attribute ShowInMenus = 0
693
	 *
694
	 * @return ArrayList
695
	*/
696
	public function getBreadcrumbItems($maxDepth = 20, $stopAtPageType = false, $showHidden = false) {
697
		$page = $this;
698
		$pages = array();
699
700
		while(
701
			$page
702
 			&& (!$maxDepth || count($pages) < $maxDepth)
703
 			&& (!$stopAtPageType || $page->ClassName != $stopAtPageType)
704
 		) {
705
			if($showHidden || $page->ShowInMenus || ($page->ID == $this->ID)) {
706
				$pages[] = $page;
707
			}
708
709
			$page = $page->Parent;
710
		}
711
712
		return new ArrayList(array_reverse($pages));
713
	}
714
715
716
	/**
717
	 * Make this page a child of another page.
718
	 *
719
	 * If the parent page does not exist, resolve it to a valid ID before updating this page's reference.
720
	 *
721
	 * @param SiteTree|int $item Either the parent object, or the parent ID
722
	 */
723
	public function setParent($item) {
724
		if(is_object($item)) {
725
			if (!$item->exists()) $item->write();
726
			$this->setField("ParentID", $item->ID);
727
		} else {
728
			$this->setField("ParentID", $item);
729
		}
730
	}
731
732
	/**
733
	 * Get the parent of this page.
734
	 *
735
	 * @return SiteTree Parent of this page
736
	 */
737
	public function getParent() {
738
		if ($parentID = $this->getField("ParentID")) {
739
			return DataObject::get_by_id("SiteTree", $parentID);
740
		}
741
	}
742
743
	/**
744
	 * Return a string of the form "parent - page" or "grandparent - parent - page" using page titles
745
	 *
746
	 * @param int $level The maximum amount of levels to traverse.
747
	 * @param string $separator Seperating string
748
	 * @return string The resulting string
749
	 */
750
	public function NestedTitle($level = 2, $separator = " - ") {
751
		$item = $this;
752
		while($item && $level > 0) {
753
			$parts[] = $item->Title;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$parts was never initialized. Although not strictly required by PHP, it is generally a good practice to add $parts = 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...
754
			$item = $item->Parent;
755
			$level--;
756
		}
757
		return implode($separator, array_reverse($parts));
0 ignored issues
show
Bug introduced by
The variable $parts 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...
758
	}
759
760
	/**
761
	 * This function should return true if the current user can execute this action. It can be overloaded to customise
762
	 * the security model for an application.
763
	 *
764
	 * Slightly altered from parent behaviour in {@link DataObject->can()}:
765
	 * - Checks for existence of a method named "can<$perm>()" on the object
766
	 * - Calls decorators and only returns for FALSE "vetoes"
767
	 * - Falls back to {@link Permission::check()}
768
	 * - Does NOT check for many-many relations named "Can<$perm>"
769
	 *
770
	 * @uses DataObjectDecorator->can()
771
	 *
772
	 * @param string $perm The permission to be checked, such as 'View'
773
	 * @param Member $member The member whose permissions need checking. Defaults to the currently logged in user.
774
	 * @param array $context Context argument for canCreate()
775
	 * @return bool True if the the member is allowed to do the given action
776
	 */
777
	public function can($perm, $member = null, $context = array()) {
778 View Code Duplication
		if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
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...
779
			$member = Member::currentUserID();
780
		}
781
782
		if($member && Permission::checkMember($member, "ADMIN")) return true;
783
784
		if(is_string($perm) && method_exists($this, 'can' . ucfirst($perm))) {
785
			$method = 'can' . ucfirst($perm);
786
			return $this->$method($member);
787
		}
788
789
		$results = $this->extend('can', $member);
790
		if($results && is_array($results)) if(!min($results)) return false;
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...
791
792
		return ($member && Permission::checkMember($member, $perm));
793
	}
794
795
	/**
796
	 * This function should return true if the current user can add children to this page. It can be overloaded to
797
	 * customise the security model for an application.
798
	 *
799
	 * Denies permission if any of the following conditions is true:
800
	 * - alternateCanAddChildren() on a extension returns false
801
	 * - canEdit() is not granted
802
	 * - There are no classes defined in {@link $allowed_children}
803
	 *
804
	 * @uses SiteTreeExtension->canAddChildren()
805
	 * @uses canEdit()
806
	 * @uses $allowed_children
807
	 *
808
	 * @param Member|int $member
809
	 * @return bool True if the current user can add children
810
	 */
811
	public function canAddChildren($member = null) {
812
		// Disable adding children to archived pages
813
		if($this->getIsDeletedFromStage()) {
814
			return false;
815
		}
816
817 View Code Duplication
		if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
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...
818
			$member = Member::currentUserID();
819
		}
820
821
		if($member && Permission::checkMember($member, "ADMIN")) return true;
822
823
		// Standard mechanism for accepting permission changes from extensions
824
		$extended = $this->extendedCan('canAddChildren', $member);
825
		if($extended !== null) return $extended;
826
827
		return $this->canEdit($member) && $this->stat('allowed_children') != 'none';
828
	}
829
830
	/**
831
	 * This function should return true if the current user can view this page. It can be overloaded to customise the
832
	 * security model for an application.
833
	 *
834
	 * Denies permission if any of the following conditions is true:
835
	 * - canView() on any extension returns false
836
	 * - "CanViewType" directive is set to "Inherit" and any parent page return false for canView()
837
	 * - "CanViewType" directive is set to "LoggedInUsers" and no user is logged in
838
	 * - "CanViewType" directive is set to "OnlyTheseUsers" and user is not in the given groups
839
	 *
840
	 * @uses DataExtension->canView()
841
	 * @uses ViewerGroups()
842
	 *
843
	 * @param Member|int $member
844
	 * @return bool True if the current user can view this page
845
	 */
846
	public function canView($member = null) {
847 View Code Duplication
		if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
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...
848
			$member = Member::currentUserID();
849
		}
850
851
		// admin override
852
		if($member && Permission::checkMember($member, array("ADMIN", "SITETREE_VIEW_ALL"))) return true;
853
854
		// Orphaned pages (in the current stage) are unavailable, except for admins via the CMS
855
		if($this->isOrphaned()) return false;
856
857
		// Standard mechanism for accepting permission changes from extensions
858
		$extended = $this->extendedCan('canView', $member);
859
		if($extended !== null) return $extended;
860
861
		// check for empty spec
862
		if(!$this->CanViewType || $this->CanViewType == 'Anyone') return true;
863
864
		// check for inherit
865
		if($this->CanViewType == 'Inherit') {
866
			if($this->ParentID) return $this->Parent()->canView($member);
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<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...
Bug introduced by
The method Parent() does not exist on SiteTree. Did you maybe mean setParent()?

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...
867
			else return $this->getSiteConfig()->canViewPages($member);
868
		}
869
870
		// check for any logged-in users
871
		if($this->CanViewType == 'LoggedInUsers' && $member) {
872
			return true;
873
		}
874
875
		// check for specific groups
876
		if($member && is_numeric($member)) $member = DataObject::get_by_id('Member', $member);
877
		if(
878
			$this->CanViewType == 'OnlyTheseUsers'
879
			&& $member
880
			&& $member->inGroups($this->ViewerGroups())
0 ignored issues
show
Documentation Bug introduced by
The method ViewerGroups does not exist on object<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...
881
		) return true;
882
883
		return false;
884
	}
885
886
	/**
887
	 * This function should return true if the current user can delete this page. It can be overloaded to customise the
888
	 * security model for an application.
889
	 *
890
	 * Denies permission if any of the following conditions is true:
891
	 * - canDelete() returns false on any extension
892
	 * - canEdit() returns false
893
	 * - any descendant page returns false for canDelete()
894
	 *
895
	 * @uses canDelete()
896
	 * @uses SiteTreeExtension->canDelete()
897
	 * @uses canEdit()
898
	 *
899
	 * @param Member $member
900
	 * @return bool True if the current user can delete this page
901
	 */
902
	public function canDelete($member = null) {
903 View Code Duplication
		if($member instanceof Member) $memberID = $member->ID;
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...
904
		else if(is_numeric($member)) $memberID = $member;
905
		else $memberID = Member::currentUserID();
906
907
		if($memberID && Permission::checkMember($memberID, array("ADMIN", "SITETREE_EDIT_ALL"))) {
908
			return true;
909
		}
910
911
		// Standard mechanism for accepting permission changes from extensions
912
		$extended = $this->extendedCan('canDelete', $memberID);
913
		if($extended !== null) return $extended;
914
915
		// Regular canEdit logic is handled by can_edit_multiple
916
		$results = self::can_delete_multiple(array($this->ID), $memberID);
917
918
		// If this page no longer exists in stage/live results won't contain the page.
919
		// Fail-over to false
920
		return isset($results[$this->ID]) ? $results[$this->ID] : false;
921
	}
922
923
	/**
924
	 * This function should return true if the current user can create new pages of this class, regardless of class. It
925
	 * can be overloaded to customise the security model for an application.
926
	 *
927
	 * By default, permission to create at the root level is based on the SiteConfig configuration, and permission to
928
	 * create beneath a parent is based on the ability to edit that parent page.
929
	 *
930
	 * Use {@link canAddChildren()} to control behaviour of creating children under this page.
931
	 *
932
	 * @uses $can_create
933
	 * @uses DataExtension->canCreate()
934
	 *
935
	 * @param Member $member
936
	 * @param array $context Optional array which may contain array('Parent' => $parentObj)
937
	 *                       If a parent page is known, it will be checked for validity.
938
	 *                       If omitted, it will be assumed this is to be created as a top level page.
939
	 * @return bool True if the current user can create pages on this class.
940
	 */
941
	public function canCreate($member = null, $context = array()) {
942 View Code Duplication
		if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) {
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...
943
			$member = Member::currentUserID();
944
		}
945
946
		// Check parent (custom canCreate option for SiteTree)
947
		// Block children not allowed for this parent type
948
		$parent = isset($context['Parent']) ? $context['Parent'] : null;
949
		if($parent && !in_array(get_class($this), $parent->allowedChildren())) {
950
			return false;
951
		}
952
953
		// Check permission
954
		if($member && Permission::checkMember($member, "ADMIN")) {
955
			return true;
956
		}
957
958
		// Standard mechanism for accepting permission changes from extensions
959
		$extended = $this->extendedCan(__FUNCTION__, $member, $context);
960
		if($extended !== null) {
961
			return $extended;
962
		}
963
964
		// Fall over to inherited permissions
965
		if($parent) {
966
			return $parent->canAddChildren($member);
967
		} else {
968
			// This doesn't necessarily mean we are creating a root page, but that
969
			// we don't know if there is a parent, so default to this permission
970
			return SiteConfig::current_site_config()->canCreateTopLevel($member);
971
		}
972
	}
973
974
	/**
975
	 * This function should return true if the current user can edit this page. It can be overloaded to customise the
976
	 * security model for an application.
977
	 *
978
	 * Denies permission if any of the following conditions is true:
979
	 * - canEdit() on any extension returns false
980
	 * - canView() return false
981
	 * - "CanEditType" directive is set to "Inherit" and any parent page return false for canEdit()
982
	 * - "CanEditType" directive is set to "LoggedInUsers" and no user is logged in or doesn't have the
983
	 *   CMS_Access_CMSMAIN permission code
984
	 * - "CanEditType" directive is set to "OnlyTheseUsers" and user is not in the given groups
985
	 *
986
	 * @uses canView()
987
	 * @uses EditorGroups()
988
	 * @uses DataExtension->canEdit()
989
	 *
990
	 * @param Member $member Set to false if you want to explicitly test permissions without a valid user (useful for
991
	 *                       unit tests)
992
	 * @return bool True if the current user can edit this page
993
	 */
994
	public function canEdit($member = null) {
995 View Code Duplication
		if($member instanceof Member) $memberID = $member->ID;
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...
996
		else if(is_numeric($member)) $memberID = $member;
997
		else $memberID = Member::currentUserID();
998
999
		if($memberID && Permission::checkMember($memberID, array("ADMIN", "SITETREE_EDIT_ALL"))) return true;
1000
1001
		// Standard mechanism for accepting permission changes from extensions
1002
		$extended = $this->extendedCan('canEdit', $memberID);
1003
		if($extended !== null) return $extended;
1004
1005
		if($this->ID) {
1006
			// Regular canEdit logic is handled by can_edit_multiple
1007
			$results = self::can_edit_multiple(array($this->ID), $memberID);
1008
1009
			// If this page no longer exists in stage/live results won't contain the page.
1010
			// Fail-over to false
1011
			return isset($results[$this->ID]) ? $results[$this->ID] : false;
1012
1013
		// Default for unsaved pages
1014
		} else {
1015
			return $this->getSiteConfig()->canEditPages($member);
1016
		}
1017
	}
1018
1019
	/**
1020
	 * Stub method to get the site config, unless the current class can provide an alternate.
1021
	 *
1022
	 * @return SiteConfig
1023
	 */
1024
	public function getSiteConfig() {
1025
1026
		if($this->hasMethod('alternateSiteConfig')) {
1027
			$altConfig = $this->alternateSiteConfig();
0 ignored issues
show
Bug introduced by
The method alternateSiteConfig() does not exist on SiteTree. Did you maybe mean config()?

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...
1028
			if($altConfig) return $altConfig;
1029
		}
1030
1031
		return SiteConfig::current_site_config();
1032
	}
1033
1034
	/**
1035
	 * Pre-populate the cache of canEdit, canView, canDelete, canPublish permissions. This method will use the static
1036
	 * can_(perm)_multiple method for efficiency.
1037
	 *
1038
	 * @param string          $permission    The permission: edit, view, publish, approve, etc.
1039
	 * @param array           $ids           An array of page IDs
1040
	 * @param callable|string $batchCallback The function/static method to call to calculate permissions.  Defaults
1041
	 *                                       to 'SiteTree::can_(permission)_multiple'
1042
	 */
1043
	static public function prepopulate_permission_cache($permission = 'CanEditType', $ids, $batchCallback = null) {
1044
		if(!$batchCallback) $batchCallback = "SiteTree::can_{$permission}_multiple";
1045
1046
		if(is_callable($batchCallback)) {
1047
			call_user_func($batchCallback, $ids, Member::currentUserID(), false);
1048
		} else {
1049
			user_error("SiteTree::prepopulate_permission_cache can't calculate '$permission' "
1050
				. "with callback '$batchCallback'", E_USER_WARNING);
1051
		}
1052
	}
1053
1054
	/**
1055
	 * This method is NOT a full replacement for the individual can*() methods, e.g. {@link canEdit()}. Rather than
1056
	 * checking (potentially slow) PHP logic, it relies on the database group associations, e.g. the "CanEditType" field
1057
	 * plus the "SiteTree_EditorGroups" many-many table. By batch checking multiple records, we can combine the queries
1058
	 * efficiently.
1059
	 *
1060
	 * Caches based on $typeField data. To invalidate the cache, use {@link SiteTree::reset()} or set the $useCached
1061
	 * property to FALSE.
1062
	 *
1063
	 * @param array  $ids              Of {@link SiteTree} IDs
1064
	 * @param int    $memberID         Member ID
1065
	 * @param string $typeField        A property on the data record, e.g. "CanEditType".
1066
	 * @param string $groupJoinTable   A many-many table name on this record, e.g. "SiteTree_EditorGroups"
1067
	 * @param string $siteConfigMethod Method to call on {@link SiteConfig} for toplevel items, e.g. "canEdit"
1068
	 * @param string $globalPermission If the member doesn't have this permission code, don't bother iterating deeper
1069
	 * @param bool   $useCached
1070
	 * @return array An map of {@link SiteTree} ID keys to boolean values
1071
	 */
1072
	public static function batch_permission_check($ids, $memberID, $typeField, $groupJoinTable, $siteConfigMethod,
1073
												  $globalPermission = null, $useCached = true) {
1074
		if($globalPermission === NULL) $globalPermission = array('CMS_ACCESS_LeftAndMain', 'CMS_ACCESS_CMSMain');
1075
1076
		// Sanitise the IDs
1077
		$ids = array_filter($ids, 'is_numeric');
1078
1079
		// This is the name used on the permission cache
1080
		// converts something like 'CanEditType' to 'edit'.
1081
		$cacheKey = strtolower(substr($typeField, 3, -4)) . "-$memberID";
1082
1083
		// Default result: nothing editable
1084
		$result = array_fill_keys($ids, false);
1085
		if($ids) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $ids 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...
1086
1087
			// Look in the cache for values
1088
			if($useCached && isset(self::$cache_permissions[$cacheKey])) {
1089
				$cachedValues = array_intersect_key(self::$cache_permissions[$cacheKey], $result);
1090
1091
				// If we can't find everything in the cache, then look up the remainder separately
1092
				$uncachedValues = array_diff_key($result, self::$cache_permissions[$cacheKey]);
1093
				if($uncachedValues) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $uncachedValues 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...
1094
					$cachedValues = self::batch_permission_check(array_keys($uncachedValues), $memberID, $typeField, $groupJoinTable, $siteConfigMethod, $globalPermission, false) + $cachedValues;
0 ignored issues
show
Bug introduced by
It seems like $globalPermission defined by array('CMS_ACCESS_LeftAn..., 'CMS_ACCESS_CMSMain') on line 1074 can also be of type array<integer,string,{"0":"string","1":"string"}>; however, SiteTree::batch_permission_check() does only seem to accept string|null, 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...
1095
				}
1096
				return $cachedValues;
1097
			}
1098
1099
			// If a member doesn't have a certain permission then they can't edit anything
1100
			if(!$memberID || ($globalPermission && !Permission::checkMember($memberID, $globalPermission))) {
1101
				return $result;
1102
			}
1103
1104
			// Placeholder for parameterised ID list
1105
			$idPlaceholders = DB::placeholders($ids);
1106
1107
			// If page can't be viewed, don't grant edit permissions to do - implement can_view_multiple(), so this can
1108
			// be enabled
1109
			//$ids = array_keys(array_filter(self::can_view_multiple($ids, $memberID)));
1110
1111
			// Get the groups that the given member belongs to
1112
			$groupIDs = DataObject::get_by_id('Member', $memberID)->Groups()->column("ID");
1113
			$SQL_groupList = implode(", ", $groupIDs);
1114
			if (!$SQL_groupList) $SQL_groupList = '0';
1115
1116
			$combinedStageResult = array();
1117
1118
			foreach(array(Versioned::DRAFT, Versioned::LIVE) as $stage) {
1119
				// Start by filling the array with the pages that actually exist
1120
				$table = ($stage=='Stage') ? "SiteTree" : "SiteTree_$stage";
1121
1122
				if($ids) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $ids 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...
1123
					$idQuery = "SELECT \"ID\" FROM \"$table\" WHERE \"ID\" IN ($idPlaceholders)";
1124
					$stageIds = DB::prepared_query($idQuery, $ids)->column();
1125
				} else {
1126
					$stageIds = array();
1127
				}
1128
				$result = array_fill_keys($stageIds, false);
1129
1130
				// Get the uninherited permissions
1131
				$uninheritedPermissions = Versioned::get_by_stage("SiteTree", $stage)
1132
					->where(array(
1133
						"(\"$typeField\" = 'LoggedInUsers' OR
1134
						(\"$typeField\" = 'OnlyTheseUsers' AND \"$groupJoinTable\".\"SiteTreeID\" IS NOT NULL))
1135
						AND \"SiteTree\".\"ID\" IN ($idPlaceholders)"
1136
						=> $ids
1137
					))
1138
					->leftJoin($groupJoinTable, "\"$groupJoinTable\".\"SiteTreeID\" = \"SiteTree\".\"ID\" AND \"$groupJoinTable\".\"GroupID\" IN ($SQL_groupList)");
1139
1140
				if($uninheritedPermissions) {
1141
					// Set all the relevant items in $result to true
1142
					$result = array_fill_keys($uninheritedPermissions->column('ID'), true) + $result;
1143
				}
1144
1145
				// Get permissions that are inherited
1146
				$potentiallyInherited = Versioned::get_by_stage(
1147
					"SiteTree",
1148
					$stage,
1149
					array("\"$typeField\" = 'Inherit' AND \"SiteTree\".\"ID\" IN ($idPlaceholders)" => $ids)
0 ignored issues
show
Documentation introduced by
array("\"{$typeField}\" ...laceholders})" => $ids) is of type array<string|integer,array>, 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...
1150
				);
1151
1152
				if($potentiallyInherited) {
1153
					// Group $potentiallyInherited by ParentID; we'll look at the permission of all those parents and
1154
					// then see which ones the user has permission on
1155
					$groupedByParent = array();
1156
					foreach($potentiallyInherited as $item) {
1157
						if($item->ParentID) {
1158
							if(!isset($groupedByParent[$item->ParentID])) $groupedByParent[$item->ParentID] = array();
1159
							$groupedByParent[$item->ParentID][] = $item->ID;
1160
						} else {
1161
							// Might return different site config based on record context, e.g. when subsites module
1162
							// is used
1163
							$siteConfig = $item->getSiteConfig();
1164
							$result[$item->ID] = $siteConfig->{$siteConfigMethod}($memberID);
1165
						}
1166
					}
1167
1168
					if($groupedByParent) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $groupedByParent 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...
1169
						$actuallyInherited = self::batch_permission_check(array_keys($groupedByParent), $memberID, $typeField, $groupJoinTable, $siteConfigMethod);
1170
						if($actuallyInherited) {
1171
							$parentIDs = array_keys(array_filter($actuallyInherited));
1172
							foreach($parentIDs as $parentID) {
1173
								// Set all the relevant items in $result to true
1174
								$result = array_fill_keys($groupedByParent[$parentID], true) + $result;
1175
							}
1176
						}
1177
					}
1178
				}
1179
1180
				$combinedStageResult = $combinedStageResult + $result;
1181
1182
			}
1183
		}
1184
1185
		if(isset($combinedStageResult)) {
1186
			// Cache the results
1187
 			if(empty(self::$cache_permissions[$cacheKey])) self::$cache_permissions[$cacheKey] = array();
1188
 			self::$cache_permissions[$cacheKey] = $combinedStageResult + self::$cache_permissions[$cacheKey];
1189
1190
			return $combinedStageResult;
1191
		} else {
1192
			return array();
1193
		}
1194
	}
1195
1196
	/**
1197
	 * Get the 'can edit' information for a number of SiteTree pages.
1198
	 *
1199
	 * @param array $ids       An array of IDs of the SiteTree pages to look up
1200
	 * @param int   $memberID  ID of member
1201
	 * @param bool  $useCached Return values from the permission cache if they exist
1202
	 * @return array A map where the IDs are keys and the values are booleans stating whether the given page can be
1203
	 *                         edited
1204
	 */
1205
	static public function can_edit_multiple($ids, $memberID, $useCached = true) {
1206
		return self::batch_permission_check($ids, $memberID, 'CanEditType', 'SiteTree_EditorGroups', 'canEditPages', null, $useCached);
1207
	}
1208
1209
	/**
1210
	 * Get the 'can edit' information for a number of SiteTree pages.
1211
	 *
1212
	 * @param array $ids       An array of IDs of the SiteTree pages to look up
1213
	 * @param int   $memberID  ID of member
1214
	 * @param bool  $useCached Return values from the permission cache if they exist
1215
	 * @return array
1216
	 */
1217
	static public function can_delete_multiple($ids, $memberID, $useCached = true) {
1218
		$deletable = array();
0 ignored issues
show
Unused Code introduced by
$deletable is not used, you could remove the assignment.

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

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

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

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

Loading history...
1219
		$result = array_fill_keys($ids, false);
1220
		$cacheKey = "delete-$memberID";
1221
1222
		// Look in the cache for values
1223
		if($useCached && isset(self::$cache_permissions[$cacheKey])) {
1224
			$cachedValues = array_intersect_key(self::$cache_permissions[$cacheKey], $result);
1225
1226
			// If we can't find everything in the cache, then look up the remainder separately
1227
			$uncachedValues = array_diff_key($result, self::$cache_permissions[$cacheKey]);
1228
			if($uncachedValues) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $uncachedValues 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...
1229
				$cachedValues = self::can_delete_multiple(array_keys($uncachedValues), $memberID, false)
1230
					+ $cachedValues;
1231
			}
1232
			return $cachedValues;
1233
		}
1234
1235
		// You can only delete pages that you can edit
1236
		$editableIDs = array_keys(array_filter(self::can_edit_multiple($ids, $memberID)));
1237
		if($editableIDs) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $editableIDs 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...
1238
1239
			// You can only delete pages whose children you can delete
1240
			$editablePlaceholders = DB::placeholders($editableIDs);
1241
			$childRecords = SiteTree::get()->where(array(
1242
				"\"SiteTree\".\"ParentID\" IN ($editablePlaceholders)" => $editableIDs
1243
			));
1244
			if($childRecords) {
1245
				$children = $childRecords->map("ID", "ParentID");
1246
1247
				// Find out the children that can be deleted
1248
				$deletableChildren = self::can_delete_multiple($children->keys(), $memberID);
1249
1250
				// Get a list of all the parents that have no undeletable children
1251
				$deletableParents = array_fill_keys($editableIDs, true);
1252
				foreach($deletableChildren as $id => $canDelete) {
1253
					if(!$canDelete) unset($deletableParents[$children[$id]]);
1254
				}
1255
1256
				// Use that to filter the list of deletable parents that have children
1257
				$deletableParents = array_keys($deletableParents);
1258
1259
				// Also get the $ids that don't have children
1260
				$parents = array_unique($children->values());
1261
				$deletableLeafNodes = array_diff($editableIDs, $parents);
1262
1263
				// Combine the two
1264
				$deletable = array_merge($deletableParents, $deletableLeafNodes);
1265
1266
			} else {
1267
				$deletable = $editableIDs;
1268
			}
1269
		} else {
1270
			$deletable = array();
1271
		}
1272
1273
		// Convert the array of deletable IDs into a map of the original IDs with true/false as the value
1274
		return array_fill_keys($deletable, true) + array_fill_keys($ids, false);
1275
	}
1276
1277
	/**
1278
	 * Collate selected descendants of this page.
1279
	 *
1280
	 * {@link $condition} will be evaluated on each descendant, and if it is succeeds, that item will be added to the
1281
	 * $collator array.
1282
	 *
1283
	 * @param string $condition The PHP condition to be evaluated. The page will be called $item
1284
	 * @param array  $collator  An array, passed by reference, to collect all of the matching descendants.
1285
	 * @return bool
1286
	 */
1287
	public function collateDescendants($condition, &$collator) {
1288
		if($children = $this->Children()) {
0 ignored issues
show
Bug introduced by
The method Children() does not exist on 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...
1289
			foreach($children as $item) {
1290
				if(eval("return $condition;")) $collator[] = $item;
1291
				$item->collateDescendants($condition, $collator);
1292
			}
1293
			return true;
1294
		}
1295
	}
1296
1297
	/**
1298
	 * Return the title, description, keywords and language metatags.
1299
	 *
1300
	 * @todo Move <title> tag in separate getter for easier customization and more obvious usage
1301
	 *
1302
	 * @param bool $includeTitle Show default <title>-tag, set to false for custom templating
1303
	 * @return string The XHTML metatags
1304
	 */
1305
	public function MetaTags($includeTitle = true) {
1306
		$tags = "";
1307
		if($includeTitle === true || $includeTitle == 'true') {
1308
			$tags .= "<title>" . Convert::raw2xml($this->Title) . "</title>\n";
1309
		}
1310
1311
		$generator = trim(Config::inst()->get('SiteTree', 'meta_generator'));
1312
		if (!empty($generator)) {
1313
			$tags .= "<meta name=\"generator\" content=\"" . Convert::raw2att($generator) . "\" />\n";
1314
		}
1315
1316
		$charset = Config::inst()->get('ContentNegotiator', 'encoding');
1317
		$tags .= "<meta http-equiv=\"Content-type\" content=\"text/html; charset=$charset\" />\n";
1318
		if($this->MetaDescription) {
1319
			$tags .= "<meta name=\"description\" content=\"" . Convert::raw2att($this->MetaDescription) . "\" />\n";
1320
		}
1321
		if($this->ExtraMeta) {
1322
			$tags .= $this->ExtraMeta . "\n";
1323
		}
1324
1325
		if(Permission::check('CMS_ACCESS_CMSMain')
1326
			&& in_array('CMSPreviewable', class_implements($this))
1327
			&& !$this instanceof ErrorPage
1328
			&& $this->ID > 0
1329
		) {
1330
			$tags .= "<meta name=\"x-page-id\" content=\"{$this->ID}\" />\n";
1331
			$tags .= "<meta name=\"x-cms-edit-link\" content=\"" . $this->CMSEditLink() . "\" />\n";
1332
		}
1333
1334
		$this->extend('MetaTags', $tags);
1335
1336
		return $tags;
1337
	}
1338
1339
	/**
1340
	 * Returns the object that contains the content that a user would associate with this page.
1341
	 *
1342
	 * Ordinarily, this is just the page itself, but for example on RedirectorPages or VirtualPages ContentSource() will
1343
	 * return the page that is linked to.
1344
	 *
1345
	 * @return $this
1346
	 */
1347
	public function ContentSource() {
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
		parent::requireDefaultRecords();
1359
1360
		// default pages
1361
		if($this->class == 'SiteTree' && $this->config()->create_default_pages) {
1362
			if(!SiteTree::get_by_link(Config::inst()->get('RootURLController', 'default_homepage_link'))) {
1363
				$homepage = new Page();
1364
				$homepage->Title = _t('SiteTree.DEFAULTHOMETITLE', 'Home');
1365
				$homepage->Content = _t('SiteTree.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>');
1366
				$homepage->URLSegment = Config::inst()->get('RootURLController', 'default_homepage_link');
1367
				$homepage->Sort = 1;
1368
				$homepage->write();
1369
				$homepage->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
1370
				$homepage->flushCache();
1371
				DB::alteration_message('Home page created', 'created');
1372
			}
1373
1374
			if(DB::query("SELECT COUNT(*) FROM \"SiteTree\"")->value() == 1) {
1375
				$aboutus = new Page();
1376
				$aboutus->Title = _t('SiteTree.DEFAULTABOUTTITLE', 'About Us');
1377
				$aboutus->Content = _t('SiteTree.DEFAULTABOUTCONTENT', '<p>You can fill this page out with your own content, or delete it and create your own pages.<br /></p>');
1378
				$aboutus->Sort = 2;
1379
				$aboutus->write();
1380
				$aboutus->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
1381
				$aboutus->flushCache();
1382
				DB::alteration_message('About Us page created', 'created');
1383
1384
				$contactus = new Page();
1385
				$contactus->Title = _t('SiteTree.DEFAULTCONTACTTITLE', 'Contact Us');
1386
				$contactus->Content = _t('SiteTree.DEFAULTCONTACTCONTENT', '<p>You can fill this page out with your own content, or delete it and create your own pages.<br /></p>');
1387
				$contactus->Sort = 3;
1388
				$contactus->write();
1389
				$contactus->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
1390
				$contactus->flushCache();
1391
				DB::alteration_message('Contact Us page created', 'created');
1392
			}
1393
		}
1394
1395
		// schema migration
1396
		// @todo Move to migration task once infrastructure is implemented
1397
		if($this->class == 'SiteTree') {
1398
			$conn = DB::get_schema();
1399
			// only execute command if fields haven't been renamed to _obsolete_<fieldname> already by the task
1400
			if($conn->hasField('SiteTree' ,'Viewers')) {
1401
				$task = new UpgradeSiteTreePermissionSchemaTask();
1402
				$task->run(new SS_HTTPRequest('GET','/'));
1403
			}
1404
		}
1405
	}
1406
1407
	protected function onBeforeWrite() {
1408
		parent::onBeforeWrite();
1409
1410
		// If Sort hasn't been set, make this page come after it's siblings
1411
		if(!$this->Sort) {
1412
			$parentID = ($this->ParentID) ? $this->ParentID : 0;
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<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...
1413
			$this->Sort = DB::prepared_query(
1414
				"SELECT MAX(\"Sort\") + 1 FROM \"SiteTree\" WHERE \"ParentID\" = ?",
1415
				array($parentID)
1416
			)->value();
1417
		}
1418
1419
		// If there is no URLSegment set, generate one from Title
1420
		$defaultSegment = $this->generateURLSegment(_t(
1421
			'CMSMain.NEWPAGE',
1422
			array('pagetype' => $this->i18n_singular_name())
0 ignored issues
show
Documentation introduced by
array('pagetype' => $this->i18n_singular_name()) is of type array<string,string,{"pagetype":"string"}>, 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...
1423
		));
1424
		if((!$this->URLSegment || $this->URLSegment == $defaultSegment) && $this->Title) {
1425
			$this->URLSegment = $this->generateURLSegment($this->Title);
1426
		} else if($this->isChanged('URLSegment', 2)) {
1427
			// Do a strict check on change level, to avoid double encoding caused by
1428
			// bogus changes through forceChange()
1429
			$filter = URLSegmentFilter::create();
1430
			$this->URLSegment = $filter->filter($this->URLSegment);
1431
			// If after sanitising there is no URLSegment, give it a reasonable default
1432
			if(!$this->URLSegment) $this->URLSegment = "page-$this->ID";
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<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
		$this->extend('augmentSyncLinkTracking');
1465
	}
1466
1467
	public function onBeforeDelete() {
1468
		parent::onBeforeDelete();
1469
1470
		// If deleting this page, delete all its children.
1471
		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<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...
1472
			foreach($children as $child) {
1473
				$child->delete();
1474
			}
1475
		}
1476
	}
1477
1478
	public function onAfterDelete() {
1479
		// Need to flush cache to avoid outdated versionnumber references
1480
		$this->flushCache();
1481
1482
		// Need to mark pages depending to this one as broken
1483
		$dependentPages = $this->DependentPages();
1484
		if($dependentPages) foreach($dependentPages as $page) {
1485
			// $page->write() calls syncLinkTracking, which does all the hard work for us.
1486
			$page->write();
1487
		}
1488
1489
		parent::onAfterDelete();
1490
	}
1491
1492
	public function flushCache($persistent = true) {
1493
		parent::flushCache($persistent);
1494
		$this->_cache_statusFlags = null;
1495
	}
1496
1497
	public function validate() {
1498
		$result = parent::validate();
1499
1500
		// Allowed children validation
1501
		$parent = $this->getParent();
1502
		if($parent && $parent->exists()) {
1503
			// No need to check for subclasses or instanceof, as allowedChildren() already
1504
			// deconstructs any inheritance trees already.
1505
			$allowed = $parent->allowedChildren();
1506
			$subject = ($this instanceof VirtualPage && $this->CopyContentFromID) ? $this->CopyContentFrom() : $this;
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...
Documentation Bug introduced by
The method CopyContentFrom does not exist on object<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...
1507
			if(!in_array($subject->ClassName, $allowed)) {
1508
1509
				$result->error(
1510
					_t(
1511
						'SiteTree.PageTypeNotAllowed',
1512
						'Page type "{type}" not allowed as child of this parent page',
1513
						array('type' => $subject->i18n_singular_name())
0 ignored issues
show
Documentation introduced by
array('type' => $subject->i18n_singular_name()) is of type array<string,?,{"type":"?"}>, 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...
1514
					),
1515
					'ALLOWED_CHILDREN'
1516
				);
1517
			}
1518
		}
1519
1520
		// "Can be root" validation
1521
		if(!$this->stat('can_be_root') && !$this->ParentID) {
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<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...
1522
			$result->error(
1523
				_t(
1524
					'SiteTree.PageTypNotAllowedOnRoot',
1525
					'Page type "{type}" is not allowed on the root level',
1526
					array('type' => $this->i18n_singular_name())
0 ignored issues
show
Documentation introduced by
array('type' => $this->i18n_singular_name()) is of type array<string,string,{"type":"string"}>, 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...
1527
				),
1528
				'CAN_BE_ROOT'
1529
			);
1530
		}
1531
1532
		return $result;
1533
	}
1534
1535
	/**
1536
	 * Returns true if this object has a URLSegment value that does not conflict with any other objects. This method
1537
	 * checks for:
1538
	 *  - A page with the same URLSegment that has a conflict
1539
	 *  - Conflicts with actions on the parent page
1540
	 *  - A conflict caused by a root page having the same URLSegment as a class name
1541
	 *
1542
	 * @return bool
1543
	 */
1544
	public function validURLSegment() {
1545
		if(self::config()->nested_urls && $parent = $this->Parent()) {
0 ignored issues
show
Bug introduced by
The method Parent() does not exist on SiteTree. Did you maybe mean setParent()?

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...
1546
			if($controller = ModelAsController::controller_for($parent)) {
1547
				if($controller instanceof Controller && $controller->hasAction($this->URLSegment)) return false;
1548
			}
1549
		}
1550
1551
		if(!self::config()->nested_urls || !$this->ParentID) {
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<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...
1552
			if(class_exists($this->URLSegment) && is_subclass_of($this->URLSegment, 'RequestHandler')) return false;
1553
		}
1554
1555
		// Filters by url, id, and parent
1556
		$filter = array('"SiteTree"."URLSegment"' => $this->URLSegment);
1557
		if($this->ID) {
1558
			$filter['"SiteTree"."ID" <> ?'] = $this->ID;
1559
		}
1560
		if(self::config()->nested_urls) {
1561
			$filter['"SiteTree"."ParentID"'] = $this->ParentID ? $this->ParentID : 0;
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<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...
1562
		}
1563
1564
		$votes = array_filter(
1565
			(array)$this->extend('augmentValidURLSegment'),
1566
			function($v) {return !is_null($v);}
1567
		);
1568
		if($votes) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $votes of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
1569
			return min($votes);
1570
		}
1571
1572
		// Check existence
1573
		$existingPage = DataObject::get_one('SiteTree', $filter);
1574
		if ($existingPage) return false;
1575
1576
		return !($existingPage);
1577
		}
1578
1579
	/**
1580
	 * Generate a URL segment based on the title provided.
1581
	 *
1582
	 * If {@link Extension}s wish to alter URL segment generation, they can do so by defining
1583
	 * updateURLSegment(&$url, $title).  $url will be passed by reference and should be modified. $title will contain
1584
	 * the title that was originally used as the source of this generated URL. This lets extensions either start from
1585
	 * scratch, or incrementally modify the generated URL.
1586
	 *
1587
	 * @param string $title Page title
1588
	 * @return string Generated url segment
1589
	 */
1590
	public function generateURLSegment($title){
1591
		$filter = URLSegmentFilter::create();
1592
		$t = $filter->filter($title);
1593
1594
		// Fallback to generic page name if path is empty (= no valid, convertable characters)
1595
		if(!$t || $t == '-' || $t == '-1') $t = "page-$this->ID";
1596
1597
		// Hook for extensions
1598
		$this->extend('updateURLSegment', $t, $title);
1599
1600
		return $t;
1601
	}
1602
1603
	/**
1604
	 * Gets the URL segment for the latest draft version of this page.
1605
	 *
1606
	 * @return string
1607
	 */
1608
	public function getStageURLSegment() {
1609
		$stageRecord = Versioned::get_one_by_stage('SiteTree', Versioned::DRAFT, array(
0 ignored issues
show
Documentation introduced by
array('"SiteTree"."ID"' => $this->ID) is of type array<string,integer,{"\...e\".\"ID\"":"integer"}>, 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...
1610
			'"SiteTree"."ID"' => $this->ID
1611
		));
1612
		return ($stageRecord) ? $stageRecord->URLSegment : null;
1613
	}
1614
1615
	/**
1616
	 * Gets the URL segment for the currently published version of this page.
1617
	 *
1618
	 * @return string
1619
	 */
1620
	public function getLiveURLSegment() {
1621
		$liveRecord = Versioned::get_one_by_stage('SiteTree', Versioned::LIVE, array(
0 ignored issues
show
Documentation introduced by
array('"SiteTree"."ID"' => $this->ID) is of type array<string,integer,{"\...e\".\"ID\"":"integer"}>, 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...
1622
			'"SiteTree"."ID"' => $this->ID
1623
		));
1624
		return ($liveRecord) ? $liveRecord->URLSegment : null;
1625
	}
1626
1627
	/**
1628
	 * Returns the pages that depend on this page. This includes virtual pages, pages that link to it, etc.
1629
	 *
1630
	 * @param bool $includeVirtuals Set to false to exlcude virtual pages.
1631
	 * @return ArrayList
1632
	 */
1633
	public function DependentPages($includeVirtuals = true) {
1634
		if(class_exists('Subsite')) {
1635
			$origDisableSubsiteFilter = Subsite::$disable_subsite_filter;
1636
			Subsite::disable_subsite_filter(true);
1637
		}
1638
1639
		// Content links
1640
		$items = new ArrayList();
1641
1642
		// We merge all into a regular SS_List, because DataList doesn't support merge
1643
		if($contentLinks = $this->BackLinkTracking()) {
0 ignored issues
show
Documentation Bug introduced by
The method BackLinkTracking does not exist on object<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...
1644
			$linkList = new ArrayList();
1645
			foreach($contentLinks as $item) {
1646
				$item->DependentLinkType = 'Content link';
1647
				$linkList->push($item);
1648
			}
1649
			$items->merge($linkList);
1650
		}
1651
1652
		// Virtual pages
1653
		if($includeVirtuals) {
1654
			$virtuals = $this->VirtualPages();
1655
			if($virtuals) {
1656
				$virtualList = new ArrayList();
1657
				foreach($virtuals as $item) {
1658
					$item->DependentLinkType = 'Virtual page';
1659
					$virtualList->push($item);
1660
				}
1661
				$items->merge($virtualList);
1662
			}
1663
		}
1664
1665
		// Redirector pages
1666
		$redirectors = RedirectorPage::get()->where(array(
1667
			'"RedirectorPage"."RedirectionType"' => 'Internal',
1668
			'"RedirectorPage"."LinkToID"' => $this->ID
1669
		));
1670
		if($redirectors) {
1671
			$redirectorList = new ArrayList();
1672
			foreach($redirectors as $item) {
1673
				$item->DependentLinkType = 'Redirector page';
1674
				$redirectorList->push($item);
1675
			}
1676
			$items->merge($redirectorList);
1677
		}
1678
1679
		if(class_exists('Subsite')) 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...
1680
1681
		return $items;
1682
	}
1683
1684
	/**
1685
	 * Return all virtual pages that link to this page.
1686
	 *
1687
	 * @return DataList
1688
	 */
1689
	public function VirtualPages() {
1690
		$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 DataObject as the method VirtualPages() does only exist in the following sub-classes of DataObject: 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...
1691
1692
		// Disable subsite filter for these pages
1693
		if($pages instanceof DataList) {
1694
			return $pages->setDataQueryParam('Subsite.filter', false);
1695
		} else {
1696
			return $pages;
1697
		}
1698
	}
1699
1700
	/**
1701
	 * Returns a FieldList with which to create the main editing form.
1702
	 *
1703
	 * You can override this in your child classes to add extra fields - first get the parent fields using
1704
	 * parent::getCMSFields(), then use addFieldToTab() on the FieldList.
1705
	 *
1706
	 * See {@link getSettingsFields()} for a different set of fields concerned with configuration aspects on the record,
1707
	 * e.g. access control.
1708
	 *
1709
	 * @return FieldList The fields to be displayed in the CMS
1710
	 */
1711
	public function getCMSFields() {
1712
		require_once("forms/Form.php");
1713
		// Status / message
1714
		// Create a status message for multiple parents
1715
		if($this->ID && is_numeric($this->ID)) {
1716
			$linkedPages = $this->VirtualPages();
1717
1718
			$parentPageLinks = array();
1719
1720
			if($linkedPages->Count() > 0) {
1721
				foreach($linkedPages as $linkedPage) {
1722
					$parentPage = $linkedPage->Parent;
1723
					if($parentPage) {
1724
						if($parentPage->ID) {
1725
							$parentPageLinks[] = "<a class=\"cmsEditlink\" href=\"admin/pages/edit/show/$linkedPage->ID\">{$parentPage->Title}</a>";
1726
						} else {
1727
							$parentPageLinks[] = "<a class=\"cmsEditlink\" href=\"admin/pages/edit/show/$linkedPage->ID\">" .
1728
								_t('SiteTree.TOPLEVEL', 'Site Content (Top Level)') .
1729
								"</a>";
1730
						}
1731
					}
1732
				}
1733
1734
				$lastParent = array_pop($parentPageLinks);
1735
				$parentList = "'$lastParent'";
1736
1737
				if(count($parentPageLinks) > 0) {
1738
					$parentList = "'" . implode("', '", $parentPageLinks) . "' and "
1739
						. $parentList;
1740
				}
1741
1742
				$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...
1743
					'SiteTree.APPEARSVIRTUALPAGES',
1744
					"This content also appears on the virtual pages in the {title} sections.",
1745
					array('title' => $parentList)
0 ignored issues
show
Documentation introduced by
array('title' => $parentList) is of type array<string,?,{"title":"?"}>, 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...
1746
				);
1747
			}
1748
		}
1749
1750
		if($this->HasBrokenLink || $this->HasBrokenFile) {
0 ignored issues
show
Documentation introduced by
The property HasBrokenLink does not exist on object<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<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...
1751
			$statusMessage[] = _t('SiteTree.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...
1752
		}
1753
1754
		$dependentNote = '';
1755
		$dependentTable = new LiteralField('DependentNote', '<p></p>');
1756
1757
		// Create a table for showing pages linked to this one
1758
		$dependentPages = $this->DependentPages();
1759
		$dependentPagesCount = $dependentPages->Count();
1760
		if($dependentPagesCount) {
1761
			$dependentColumns = array(
1762
				'Title' => $this->fieldLabel('Title'),
1763
				'AbsoluteLink' => _t('SiteTree.DependtPageColumnURL', 'URL'),
1764
				'DependentLinkType' => _t('SiteTree.DependtPageColumnLinkType', 'Link type'),
1765
			);
1766
			if(class_exists('Subsite')) $dependentColumns['Subsite.Title'] = singleton('Subsite')->i18n_singular_name();
1767
1768
			$dependentNote = new LiteralField('DependentNote', '<p>' . _t('SiteTree.DEPENDENT_NOTE', 'The following pages depend on this page. This includes virtual pages, redirector pages, and pages with content links.') . '</p>');
1769
			$dependentTable = GridField::create(
1770
				'DependentPages',
1771
				false,
1772
				$dependentPages
1773
			);
1774
			$dependentTable->getConfig()->getComponentByType('GridFieldDataColumns')
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface GridFieldComponent as the method setDisplayFields() does only exist in the following implementations of said interface: GridFieldDataColumns.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
1775
				->setDisplayFields($dependentColumns)
1776
				->setFieldFormatting(array(
1777
					'Title' => function($value, &$item) {
1778
						return sprintf(
1779
							'<a href="admin/pages/edit/show/%d">%s</a>',
1780
							(int)$item->ID,
1781
							Convert::raw2xml($item->Title)
1782
						);
1783
					},
1784
					'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...
1785
						return sprintf(
1786
							'<a href="%s" target="_blank">%s</a>',
1787
							Convert::raw2xml($value),
1788
							Convert::raw2xml($value)
1789
						);
1790
					}
1791
				));
1792
		}
1793
1794
		$baseLink = Controller::join_links (
1795
			Director::absoluteBaseURL(),
1796
			(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<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...
Bug introduced by
The method Parent() does not exist on SiteTree. Did you maybe mean setParent()?

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...
1797
		);
1798
1799
		$urlsegment = SiteTreeURLSegmentField::create("URLSegment", $this->fieldLabel('URLSegment'))
1800
			->setURLPrefix($baseLink)
1801
			->setDefaultURL($this->generateURLSegment(_t(
1802
				'CMSMain.NEWPAGE',
1803
				array('pagetype' => $this->i18n_singular_name())
0 ignored issues
show
Documentation introduced by
array('pagetype' => $this->i18n_singular_name()) is of type array<string,string,{"pagetype":"string"}>, 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...
1804
			)));
1805
		$helpText = (self::config()->nested_urls && count($this->Children())) ? $this->fieldLabel('LinkChangeNote') : '';
0 ignored issues
show
Bug introduced by
The method Children() does not exist on 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...
1806
		if(!Config::inst()->get('URLSegmentFilter', 'default_allow_multibyte')) {
1807
			$helpText .= $helpText ? '<br />' : '';
1808
			$helpText .= _t('SiteTreeURLSegmentField.HelpChars', ' Special characters are automatically converted or removed.');
1809
		}
1810
		$urlsegment->setHelpText($helpText);
1811
1812
		$fields = new FieldList(
1813
			$rootTab = new TabSet("Root",
1814
				$tabMain = new Tab('Main',
1815
					new TextField("Title", $this->fieldLabel('Title')),
1816
					$urlsegment,
1817
					new TextField("MenuTitle", $this->fieldLabel('MenuTitle')),
1818
					$htmlField = new HtmlEditorField("Content", _t('SiteTree.HTMLEDITORTITLE', "Content", 'HTML editor title')),
1819
					ToggleCompositeField::create('Metadata', _t('SiteTree.MetadataToggle', 'Metadata'),
1820
						array(
1821
							$metaFieldDesc = new TextareaField("MetaDescription", $this->fieldLabel('MetaDescription')),
1822
							$metaFieldExtra = new TextareaField("ExtraMeta",$this->fieldLabel('ExtraMeta'))
1823
						)
1824
					)->setHeadingLevel(4)
1825
				),
1826
				$tabDependent = new Tab('Dependent',
1827
					$dependentNote,
1828
					$dependentTable
1829
				)
1830
			)
1831
		);
1832
		$htmlField->addExtraClass('stacked');
1833
1834
		// Help text for MetaData on page content editor
1835
		$metaFieldDesc
1836
			->setRightTitle(
1837
				_t(
1838
					'SiteTree.METADESCHELP',
1839
					"Search engines use this content for displaying search results (although it will not influence their ranking)."
1840
				)
1841
			)
1842
			->addExtraClass('help');
1843
		$metaFieldExtra
1844
			->setRightTitle(
1845
				_t(
1846
					'SiteTree.METAEXTRAHELP',
1847
					"HTML tags for additional meta information. For example &lt;meta name=\"customName\" content=\"your custom content here\" /&gt;"
1848
				)
1849
			)
1850
			->addExtraClass('help');
1851
1852
		// Conditional dependent pages tab
1853
		if($dependentPagesCount) $tabDependent->setTitle(_t('SiteTree.TABDEPENDENT', "Dependent pages") . " ($dependentPagesCount)");
1854
		else $fields->removeFieldFromTab('Root', 'Dependent');
1855
1856
		$tabMain->setTitle(_t('SiteTree.TABCONTENT', "Main Content"));
1857
1858
		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...
1859
			$obsoleteWarning = _t(
1860
				'SiteTree.OBSOLETECLASS',
1861
				"This page is of obsolete type {type}. Saving will reset its type and you may lose data",
1862
				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...
Documentation introduced by
array('type' => $this->ObsoleteClassName) is of type array<string,?,{"type":"?"}>, 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...
1863
			);
1864
1865
			$fields->addFieldToTab(
1866
				"Root.Main",
1867
				new LiteralField("ObsoleteWarningHeader", "<p class=\"message warning\">$obsoleteWarning</p>"),
1868
				"Title"
1869
			);
1870
		}
1871
1872
		if(file_exists(BASE_PATH . '/install.php')) {
1873
			$fields->addFieldToTab("Root.Main", new LiteralField("InstallWarningHeader",
1874
				"<p class=\"message warning\">" . _t("SiteTree.REMOVE_INSTALL_WARNING",
1875
				"Warning: You should remove install.php from this SilverStripe install for security reasons.")
1876
				. "</p>"), "Title");
1877
		}
1878
1879
		// Backwards compat: Rewrite nested "Content" tabs to toplevel
1880
		$fields->setTabPathRewrites(array(
1881
			'/^Root\.Content\.Main$/' => 'Root.Main',
1882
			'/^Root\.Content\.([^.]+)$/' => 'Root.\\1',
1883
		));
1884
1885
		if(self::$runCMSFieldsExtensions) {
1886
			$this->extend('updateCMSFields', $fields);
1887
		}
1888
1889
		return $fields;
1890
	}
1891
1892
1893
	/**
1894
	 * Returns fields related to configuration aspects on this record, e.g. access control. See {@link getCMSFields()}
1895
	 * for content-related fields.
1896
	 *
1897
	 * @return FieldList
1898
	 */
1899
	public function getSettingsFields() {
1900
		$groupsMap = array();
1901
		foreach(Group::get() as $group) {
1902
			// Listboxfield values are escaped, use ASCII char instead of &raquo;
1903
			$groupsMap[$group->ID] = $group->getBreadcrumbs(' > ');
1904
		}
1905
		asort($groupsMap);
1906
1907
		$fields = new FieldList(
1908
			$rootTab = new TabSet("Root",
1909
				$tabBehaviour = new Tab('Settings',
1910
					new DropdownField(
1911
						"ClassName",
1912
						$this->fieldLabel('ClassName'),
1913
						$this->getClassDropdown()
1914
					),
1915
					$parentTypeSelector = new CompositeField(
1916
						new OptionsetField("ParentType", _t("SiteTree.PAGELOCATION", "Page location"), array(
1917
							"root" => _t("SiteTree.PARENTTYPE_ROOT", "Top-level page"),
1918
							"subpage" => _t("SiteTree.PARENTTYPE_SUBPAGE", "Sub-page underneath a parent page"),
1919
						)),
1920
						$parentIDField = new TreeDropdownField("ParentID", $this->fieldLabel('ParentID'), 'SiteTree', 'ID', 'MenuTitle')
1921
					),
1922
					$visibility = new FieldGroup(
1923
						new CheckboxField("ShowInMenus", $this->fieldLabel('ShowInMenus')),
1924
						new CheckboxField("ShowInSearch", $this->fieldLabel('ShowInSearch'))
1925
					),
1926
					$viewersOptionsField = new OptionsetField(
1927
						"CanViewType",
1928
						_t('SiteTree.ACCESSHEADER', "Who can view this page?")
1929
					),
1930
					$viewerGroupsField = ListboxField::create("ViewerGroups", _t('SiteTree.VIEWERGROUPS', "Viewer Groups"))
1931
						->setSource($groupsMap)
1932
						->setAttribute(
1933
							'data-placeholder',
1934
							_t('SiteTree.GroupPlaceholder', 'Click to select group')
1935
						),
1936
					$editorsOptionsField = new OptionsetField(
1937
						"CanEditType",
1938
						_t('SiteTree.EDITHEADER', "Who can edit this page?")
1939
					),
1940
					$editorGroupsField = ListboxField::create("EditorGroups", _t('SiteTree.EDITORGROUPS', "Editor Groups"))
1941
						->setSource($groupsMap)
1942
						->setAttribute(
1943
							'data-placeholder',
1944
							_t('SiteTree.GroupPlaceholder', 'Click to select group')
1945
						)
1946
				)
1947
			)
1948
		);
1949
1950
		$visibility->setTitle($this->fieldLabel('Visibility'));
1951
1952
1953
		// This filter ensures that the ParentID dropdown selection does not show this node,
1954
		// or its descendents, as this causes vanishing bugs
1955
		$parentIDField->setFilterFunction(create_function('$node', "return \$node->ID != {$this->ID};"));
1956
		$parentTypeSelector->addExtraClass('parentTypeSelector');
1957
1958
		$tabBehaviour->setTitle(_t('SiteTree.TABBEHAVIOUR', "Behavior"));
1959
1960
		// Make page location fields read-only if the user doesn't have the appropriate permission
1961
		if(!Permission::check("SITETREE_REORGANISE")) {
1962
			$fields->makeFieldReadonly('ParentType');
1963
			if($this->ParentType == 'root') {
0 ignored issues
show
Documentation introduced by
The property ParentType does not exist on object<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...
1964
				$fields->removeByName('ParentID');
1965
			} else {
1966
				$fields->makeFieldReadonly('ParentID');
1967
			}
1968
		}
1969
1970
		$viewersOptionsSource = array();
1971
		$viewersOptionsSource["Inherit"] = _t('SiteTree.INHERIT', "Inherit from parent page");
1972
		$viewersOptionsSource["Anyone"] = _t('SiteTree.ACCESSANYONE', "Anyone");
1973
		$viewersOptionsSource["LoggedInUsers"] = _t('SiteTree.ACCESSLOGGEDIN', "Logged-in users");
1974
		$viewersOptionsSource["OnlyTheseUsers"] = _t('SiteTree.ACCESSONLYTHESE', "Only these people (choose from list)");
1975
		$viewersOptionsField->setSource($viewersOptionsSource);
1976
1977
		$editorsOptionsSource = array();
1978
		$editorsOptionsSource["Inherit"] = _t('SiteTree.INHERIT', "Inherit from parent page");
1979
		$editorsOptionsSource["LoggedInUsers"] = _t('SiteTree.EDITANYONE', "Anyone who can log-in to the CMS");
1980
		$editorsOptionsSource["OnlyTheseUsers"] = _t('SiteTree.EDITONLYTHESE', "Only these people (choose from list)");
1981
		$editorsOptionsField->setSource($editorsOptionsSource);
1982
1983
		if(!Permission::check('SITETREE_GRANT_ACCESS')) {
1984
			$fields->makeFieldReadonly($viewersOptionsField);
1985
			if($this->CanViewType == 'OnlyTheseUsers') {
1986
				$fields->makeFieldReadonly($viewerGroupsField);
1987
			} else {
1988
				$fields->removeByName('ViewerGroups');
1989
			}
1990
1991
			$fields->makeFieldReadonly($editorsOptionsField);
1992
			if($this->CanEditType == 'OnlyTheseUsers') {
1993
				$fields->makeFieldReadonly($editorGroupsField);
1994
			} else {
1995
				$fields->removeByName('EditorGroups');
1996
			}
1997
		}
1998
1999
		if(self::$runCMSFieldsExtensions) {
2000
			$this->extend('updateSettingsFields', $fields);
2001
		}
2002
2003
		return $fields;
2004
	}
2005
2006
	/**
2007
	 * @param bool $includerelations A boolean value to indicate if the labels returned should include relation fields
2008
	 * @return array
2009
	 */
2010
	public function fieldLabels($includerelations = true) {
2011
		$cacheKey = $this->class . '_' . $includerelations;
2012
		if(!isset(self::$_cache_field_labels[$cacheKey])) {
2013
			$labels = parent::fieldLabels($includerelations);
2014
			$labels['Title'] = _t('SiteTree.PAGETITLE', "Page name");
2015
			$labels['MenuTitle'] = _t('SiteTree.MENUTITLE', "Navigation label");
2016
			$labels['MetaDescription'] = _t('SiteTree.METADESC', "Meta Description");
2017
			$labels['ExtraMeta'] = _t('SiteTree.METAEXTRA', "Custom Meta Tags");
2018
			$labels['ClassName'] = _t('SiteTree.PAGETYPE', "Page type", 'Classname of a page object');
2019
			$labels['ParentType'] = _t('SiteTree.PARENTTYPE', "Page location");
2020
			$labels['ParentID'] = _t('SiteTree.PARENTID', "Parent page");
2021
			$labels['ShowInMenus'] =_t('SiteTree.SHOWINMENUS', "Show in menus?");
2022
			$labels['ShowInSearch'] = _t('SiteTree.SHOWINSEARCH', "Show in search?");
2023
			$labels['ProvideComments'] = _t('SiteTree.ALLOWCOMMENTS', "Allow comments on this page?");
2024
			$labels['ViewerGroups'] = _t('SiteTree.VIEWERGROUPS', "Viewer Groups");
2025
			$labels['EditorGroups'] = _t('SiteTree.EDITORGROUPS', "Editor Groups");
2026
			$labels['URLSegment'] = _t('SiteTree.URLSegment', 'URL Segment', 'URL for this page');
2027
			$labels['Content'] = _t('SiteTree.Content', 'Content', 'Main HTML Content for a page');
2028
			$labels['CanViewType'] = _t('SiteTree.Viewers', 'Viewers Groups');
2029
			$labels['CanEditType'] = _t('SiteTree.Editors', 'Editors Groups');
2030
			$labels['Comments'] = _t('SiteTree.Comments', 'Comments');
2031
			$labels['Visibility'] = _t('SiteTree.Visibility', 'Visibility');
2032
			$labels['LinkChangeNote'] = _t (
2033
				'SiteTree.LINKCHANGENOTE', 'Changing this page\'s link will also affect the links of all child pages.'
2034
			);
2035
2036
			if($includerelations){
2037
				$labels['Parent'] = _t('SiteTree.has_one_Parent', 'Parent Page', 'The parent page in the site hierarchy');
2038
				$labels['LinkTracking'] = _t('SiteTree.many_many_LinkTracking', 'Link Tracking');
2039
				$labels['ImageTracking'] = _t('SiteTree.many_many_ImageTracking', 'Image Tracking');
2040
				$labels['BackLinkTracking'] = _t('SiteTree.many_many_BackLinkTracking', 'Backlink Tracking');
2041
			}
2042
2043
			self::$_cache_field_labels[$cacheKey] = $labels;
2044
		}
2045
2046
		return self::$_cache_field_labels[$cacheKey];
2047
	}
2048
2049
	/**
2050
	 * Get the actions available in the CMS for this page - eg Save, Publish.
2051
	 *
2052
	 * Frontend scripts and styles know how to handle the following FormFields:
2053
	 * - top-level FormActions appear as standalone buttons
2054
	 * - top-level CompositeField with FormActions within appear as grouped buttons
2055
	 * - TabSet & Tabs appear as a drop ups
2056
	 * - FormActions within the Tab are restyled as links
2057
	 * - major actions can provide alternate states for richer presentation (see ssui.button widget extension)
2058
	 *
2059
	 * @return FieldList The available actions for this page.
2060
	 */
2061
	public function getCMSActions() {
2062
		$existsOnLive = $this->isPublished();
0 ignored issues
show
Documentation Bug introduced by
The method isPublished does not exist on object<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...
2063
2064
		// Major actions appear as buttons immediately visible as page actions.
2065
		$majorActions = CompositeField::create()->setName('MajorActions')->setTag('fieldset')->addExtraClass('ss-ui-buttonset noborder');
2066
2067
		// Minor options are hidden behind a drop-up and appear as links (although they are still FormActions).
2068
		$rootTabSet = new TabSet('ActionMenus');
2069
		$moreOptions = new Tab(
2070
			'MoreOptions',
2071
			_t('SiteTree.MoreOptions', 'More options', 'Expands a view for more buttons')
2072
		);
2073
		$rootTabSet->push($moreOptions);
2074
		$rootTabSet->addExtraClass('ss-ui-action-tabset action-menus noborder');
2075
2076
		// Render page information into the "more-options" drop-up, on the top.
2077
		$live = Versioned::get_one_by_stage('SiteTree', Versioned::LIVE, array(
0 ignored issues
show
Documentation introduced by
array('"SiteTree"."ID"' => $this->ID) is of type array<string,integer,{"\...e\".\"ID\"":"integer"}>, 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...
2078
			'"SiteTree"."ID"' => $this->ID
2079
		));
2080
		$moreOptions->push(
2081
			new LiteralField('Information',
2082
				$this->customise(array(
2083
					'Live' => $live,
2084
					'ExistsOnLive' => $existsOnLive
2085
				))->renderWith('SiteTree_Information')
2086
			)
2087
		);
2088
2089
		$moreOptions->push(AddToCampaignHandler_FormAction::create());
2090
2091
		// "readonly"/viewing version that isn't the current version of the record
2092
		$stageOrLiveRecord = Versioned::get_one_by_stage($this->class, Versioned::get_stage(), array(
0 ignored issues
show
Documentation introduced by
array('"SiteTree"."ID"' => $this->ID) is of type array<string,integer,{"\...e\".\"ID\"":"integer"}>, 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...
2093
			'"SiteTree"."ID"' => $this->ID
2094
		));
2095
		if($stageOrLiveRecord && $stageOrLiveRecord->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...
2096
			$moreOptions->push(FormAction::create('email', _t('CMSMain.EMAIL', 'Email')));
2097
			$moreOptions->push(FormAction::create('rollback', _t('CMSMain.ROLLBACK', 'Roll back to this version')));
2098
2099
			$actions = new FieldList(array($majorActions, $rootTabSet));
2100
2101
			// getCMSActions() can be extended with updateCMSActions() on a extension
2102
			$this->extend('updateCMSActions', $actions);
2103
2104
			return $actions;
2105
		}
2106
2107
		if($this->isPublished() && $this->canPublish() && !$this->getIsDeletedFromStage() && $this->canUnpublish()) {
0 ignored issues
show
Documentation Bug introduced by
The method isPublished does not exist on object<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...
Documentation Bug introduced by
The method canPublish does not exist on object<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...
Documentation Bug introduced by
The method canUnpublish does not exist on object<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
			// "unpublish"
2109
			$moreOptions->push(
2110
				FormAction::create('unpublish', _t('SiteTree.BUTTONUNPUBLISH', 'Unpublish'), 'delete')
2111
					->setDescription(_t('SiteTree.BUTTONUNPUBLISHDESC', 'Remove this page from the published site'))
2112
					->addExtraClass('ss-ui-action-destructive')
2113
			);
2114
		}
2115
2116
		if($this->stagesDiffer(Versioned::DRAFT, Versioned::LIVE) && !$this->getIsDeletedFromStage()) {
0 ignored issues
show
Documentation Bug introduced by
The method stagesDiffer does not exist on object<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...
2117
			if($this->isPublished() && $this->canEdit())	{
0 ignored issues
show
Documentation Bug introduced by
The method isPublished does not exist on object<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...
2118
				// "rollback"
2119
				$moreOptions->push(
2120
					FormAction::create('rollback', _t('SiteTree.BUTTONCANCELDRAFT', 'Cancel draft changes'), 'delete')
2121
						->setDescription(_t('SiteTree.BUTTONCANCELDRAFTDESC', 'Delete your draft and revert to the currently published page'))
2122
				);
2123
			}
2124
		}
2125
2126
		if($this->canEdit()) {
2127
			if($this->getIsDeletedFromStage()) {
2128
				// The usual major actions are not available, so we provide alternatives here.
2129
				if($existsOnLive) {
2130
					// "restore"
2131
					$majorActions->push(FormAction::create('revert',_t('CMSMain.RESTORE','Restore')));
2132
					if($this->canDelete() && $this->canUnpublish()) {
0 ignored issues
show
Documentation Bug introduced by
The method canUnpublish does not exist on object<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...
2133
						// "delete from live"
2134
						$majorActions->push(
2135
							FormAction::create('deletefromlive',_t('CMSMain.DELETEFP','Delete'))
2136
								->addExtraClass('ss-ui-action-destructive')
2137
						);
2138
					}
2139
				} else {
2140
					// Determine if we should force a restore to root (where once it was a subpage)
2141
					$restoreToRoot = $this->isParentArchived();
2142
2143
					// "restore"
2144
					$title = $restoreToRoot
2145
						? _t('CMSMain.RESTORE_TO_ROOT','Restore draft at top level')
2146
						: _t('CMSMain.RESTORE','Restore draft');
2147
					$description = $restoreToRoot
2148
						? _t('CMSMain.RESTORE_TO_ROOT_DESC','Restore the archived version to draft as a top level page')
2149
						: _t('CMSMain.RESTORE_DESC', 'Restore the archived version to draft');
2150
					$majorActions->push(
2151
						FormAction::create('restore', $title)
2152
							->setDescription($description)
2153
							->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...
2154
							->setAttribute('data-icon', 'decline')
2155
					);
2156
				}
2157
			} else {
2158
					if($this->canDelete()) {
2159
						// delete
2160
						$moreOptions->push(
2161
							FormAction::create('delete',_t('CMSMain.DELETE','Delete draft'))
2162
								->addExtraClass('delete ss-ui-action-destructive')
2163
						);
2164
					}
2165
				if($this->canArchive()) {
0 ignored issues
show
Documentation Bug introduced by
The method canArchive does not exist on object<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...
2166
					// "archive"
2167
					$moreOptions->push(
2168
						FormAction::create('archive',_t('CMSMain.ARCHIVE','Archive'))
2169
							->setDescription(_t(
2170
								'SiteTree.BUTTONARCHIVEDESC',
2171
								'Unpublish and send to archive'
2172
							))
2173
							->addExtraClass('delete ss-ui-action-destructive')
2174
					);
2175
				}
2176
2177
				// "save", supports an alternate state that is still clickable, but notifies the user that the action is not needed.
2178
				$majorActions->push(
2179
					FormAction::create('save', _t('SiteTree.BUTTONSAVED', 'Saved'))
2180
						->setAttribute('data-icon', 'accept')
2181
						->setAttribute('data-icon-alternate', 'addpage')
2182
						->setAttribute('data-text-alternate', _t('CMSMain.SAVEDRAFT','Save draft'))
2183
				);
2184
			}
2185
		}
2186
2187
		if($this->canPublish() && !$this->getIsDeletedFromStage()) {
0 ignored issues
show
Documentation Bug introduced by
The method canPublish does not exist on object<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...
2188
			// "publish", as with "save", it supports an alternate state to show when action is needed.
2189
			$majorActions->push(
2190
				$publish = FormAction::create('publish', _t('SiteTree.BUTTONPUBLISHED', 'Published'))
2191
					->setAttribute('data-icon', 'accept')
2192
					->setAttribute('data-icon-alternate', 'disk')
2193
					->setAttribute('data-text-alternate', _t('SiteTree.BUTTONSAVEPUBLISH', 'Save & publish'))
2194
			);
2195
2196
			// Set up the initial state of the button to reflect the state of the underlying SiteTree object.
2197
			if($this->stagesDiffer(Versioned::DRAFT, Versioned::LIVE)) {
0 ignored issues
show
Documentation Bug introduced by
The method stagesDiffer does not exist on object<SiteTree>? Since you implemented __call, maybe consider adding a @method annotation.

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

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

class ParentClass {
    private $data = array();

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

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

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
2198
				$publish->addExtraClass('ss-ui-alternate');
2199
			}
2200
		}
2201
2202
		$actions = new FieldList(array($majorActions, $rootTabSet));
2203
2204
		// Hook for extensions to add/remove actions.
2205
		$this->extend('updateCMSActions', $actions);
2206
2207
		return $actions;
2208
	}
2209
2210
	public function onAfterPublish() {
2211
		// Force live sort order to match stage sort order
2212
		DB::prepared_query('UPDATE "SiteTree_Live"
2213
			SET "Sort" = (SELECT "SiteTree"."Sort" FROM "SiteTree" WHERE "SiteTree_Live"."ID" = "SiteTree"."ID")
2214
			WHERE EXISTS (SELECT "SiteTree"."Sort" FROM "SiteTree" WHERE "SiteTree_Live"."ID" = "SiteTree"."ID") AND "ParentID" = ?',
2215
			array($this->ParentID)
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<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...
2216
		);
2217
		}
2218
2219
	/**
2220
	 * Update draft dependant pages
2221
	 */
2222
	public function onAfterRevertToLive() {
2223
		// Use an alias to get the updates made by $this->publish
2224
		/** @var SiteTree $stageSelf */
2225
		$stageSelf = Versioned::get_by_stage('SiteTree', Versioned::DRAFT)->byID($this->ID);
2226
		$stageSelf->writeWithoutVersion();
0 ignored issues
show
Documentation Bug introduced by
The method writeWithoutVersion does not exist on object<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...
2227
2228
		// Need to update pages linking to this one as no longer broken
2229
		foreach($stageSelf->DependentPages() as $page) {
2230
			/** @var SiteTree $page */
2231
			$page->writeWithoutVersion();
0 ignored issues
show
Documentation Bug introduced by
The method writeWithoutVersion does not exist on object<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...
2232
		}
2233
	}
2234
2235
	/**
2236
	 * Determine if this page references a parent which is archived, and not available in stage
2237
	 *
2238
	 * @return bool True if there is an archived parent
2239
	 */
2240
	protected function isParentArchived() {
2241
		if($parentID = $this->ParentID) {
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<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...
2242
			$parentPage = Versioned::get_latest_version("SiteTree", $parentID);
2243
			if(!$parentPage || $parentPage->IsDeletedFromStage) {
2244
				return true;
2245
			}
2246
		}
2247
		return false;
2248
	}
2249
2250
	/**
2251
	 * Restore the content in the active copy of this SiteTree page to the stage site.
2252
	 *
2253
	 * @return self
2254
	 */
2255
	public function doRestoreToStage() {
2256
		$this->invokeWithExtensions('onBeforeRestoreToStage', $this);
2257
2258
		// Ensure that the parent page is restored, otherwise restore to root
2259
		if($this->isParentArchived()) {
2260
			$this->ParentID = 0;
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<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...
2261
		}
2262
2263
		// if no record can be found on draft stage (meaning it has been "deleted from draft" before),
2264
		// create an empty record
2265
		if(!DB::prepared_query("SELECT \"ID\" FROM \"SiteTree\" WHERE \"ID\" = ?", array($this->ID))->value()) {
2266
			$conn = DB::get_conn();
2267
			if(method_exists($conn, 'allowPrimaryKeyEditing')) $conn->allowPrimaryKeyEditing('SiteTree', true);
0 ignored issues
show
Bug introduced by
The method allowPrimaryKeyEditing() does not seem to exist on object<SS_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...
2268
			DB::prepared_query("INSERT INTO \"SiteTree\" (\"ID\") VALUES (?)", array($this->ID));
2269
			if(method_exists($conn, 'allowPrimaryKeyEditing')) $conn->allowPrimaryKeyEditing('SiteTree', false);
0 ignored issues
show
Bug introduced by
The method allowPrimaryKeyEditing() does not seem to exist on object<SS_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...
2270
		}
2271
2272
		$oldStage = Versioned::get_stage();
2273
		Versioned::set_stage(Versioned::DRAFT);
2274
		$this->forceChange();
2275
		$this->write();
2276
2277
		$result = DataObject::get_by_id($this->class, $this->ID);
2278
2279
		// Need to update pages linking to this one as no longer broken
2280
		foreach($result->DependentPages(false) as $page) {
2281
			// $page->write() calls syncLinkTracking, which does all the hard work for us.
2282
			$page->write();
2283
		}
2284
2285
		Versioned::set_stage($oldStage);
2286
2287
		$this->invokeWithExtensions('onAfterRestoreToStage', $this);
2288
2289
		return $result;
2290
	}
2291
2292
	/**
2293
	 * Check if this page is new - that is, if it has yet to have been written to the database.
2294
	 *
2295
	 * @return bool
2296
	 */
2297
	public function isNew() {
2298
		/**
2299
		 * This check was a problem for a self-hosted site, and may indicate a bug in the interpreter on their server,
2300
		 * or a bug here. Changing the condition from empty($this->ID) to !$this->ID && !$this->record['ID'] fixed this.
2301
		 */
2302
		if(empty($this->ID)) return true;
2303
2304
		if(is_numeric($this->ID)) return false;
2305
2306
		return stripos($this->ID, 'new') === 0;
2307
	}
2308
2309
	/**
2310
	 * Get the class dropdown used in the CMS to change the class of a page. This returns the list of options in the
2311
	 * dropdown as a Map from class name to singular name. Filters by {@link SiteTree->canCreate()}, as well as
2312
	 * {@link SiteTree::$needs_permission}.
2313
	 *
2314
	 * @return array
2315
	 */
2316
	protected function getClassDropdown() {
2317
		$classes = self::page_type_classes();
2318
		$currentClass = null;
2319
		$result = array();
0 ignored issues
show
Unused Code introduced by
$result is not used, you could remove the assignment.

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

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

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

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

Loading history...
2320
2321
		$result = array();
2322
		foreach($classes as $class) {
2323
			$instance = singleton($class);
2324
2325
			// if the current page type is this the same as the class type always show the page type in the list
2326
			if ($this->ClassName != $instance->ClassName) {
2327
				if($instance instanceof HiddenClass) continue;
2328
				if(!$instance->canCreate(null, array('Parent' => $this->ParentID ? $this->Parent() : null))) continue;
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<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...
Bug introduced by
The method Parent() does not exist on SiteTree. Did you maybe mean setParent()?

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...
2329
			}
2330
2331
			if($perms = $instance->stat('need_permission')) {
2332
				if(!$this->can($perms)) continue;
2333
			}
2334
2335
			$pageTypeName = $instance->i18n_singular_name();
2336
2337
			$currentClass = $class;
2338
			$result[$class] = $pageTypeName;
2339
2340
			// If we're in translation mode, the link between the translated pagetype title and the actual classname
2341
			// might not be obvious, so we add it in parantheses. Example: class "RedirectorPage" has the title
2342
			// "Weiterleitung" in German, so it shows up as "Weiterleitung (RedirectorPage)"
2343
			if(i18n::get_lang_from_locale(i18n::get_locale()) != 'en') {
2344
				$result[$class] = $result[$class] .  " ({$class})";
2345
			}
2346
		}
2347
2348
		// sort alphabetically, and put current on top
2349
		asort($result);
2350
		if($currentClass) {
2351
			$currentPageTypeName = $result[$currentClass];
2352
			unset($result[$currentClass]);
2353
			$result = array_reverse($result);
2354
			$result[$currentClass] = $currentPageTypeName;
2355
			$result = array_reverse($result);
2356
		}
2357
2358
		return $result;
2359
	}
2360
2361
	/**
2362
	 * Returns an array of the class names of classes that are allowed to be children of this class.
2363
	 *
2364
	 * @return string[]
2365
	 */
2366
	public function allowedChildren() {
2367
		$allowedChildren = array();
2368
		$candidates = $this->stat('allowed_children');
2369
		if($candidates && $candidates != "none" && $candidates != "SiteTree_root") {
2370
			foreach($candidates as $candidate) {
0 ignored issues
show
Bug introduced by
The expression $candidates of type array|integer|double|string|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
2371
				// If a classname is prefixed by "*", such as "*Page", then only that class is allowed - no subclasses.
2372
				// Otherwise, the class and all its subclasses are allowed.
2373
				if(substr($candidate,0,1) == '*') {
2374
					$allowedChildren[] = substr($candidate,1);
2375
				} else {
2376
					$subclasses = ClassInfo::subclassesFor($candidate);
2377
					foreach($subclasses as $subclass) {
0 ignored issues
show
Bug introduced by
The expression $subclasses of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
2378
						if($subclass != "SiteTree_root") $allowedChildren[] = $subclass;
2379
					}
2380
				}
2381
			}
2382
		}
2383
2384
		return $allowedChildren;
2385
	}
2386
2387
	/**
2388
	 * Returns the class name of the default class for children of this page.
2389
	 *
2390
	 * @return string
2391
	 */
2392
	public function defaultChild() {
2393
		$default = $this->stat('default_child');
2394
		$allowed = $this->allowedChildren();
2395
		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...
2396
			if(!$default || !in_array($default, $allowed))
2397
				$default = reset($allowed);
2398
			return $default;
2399
		}
2400
	}
2401
2402
	/**
2403
	 * Returns the class name of the default class for the parent of this page.
2404
	 *
2405
	 * @return string
2406
	 */
2407
	public function defaultParent() {
2408
		return $this->stat('default_parent');
2409
	}
2410
2411
	/**
2412
	 * Get the title for use in menus for this page. If the MenuTitle field is set it returns that, else it returns the
2413
	 * Title field.
2414
	 *
2415
	 * @return string
2416
	 */
2417
	public function getMenuTitle(){
2418
		if($value = $this->getField("MenuTitle")) {
2419
			return $value;
2420
		} else {
2421
			return $this->getField("Title");
2422
		}
2423
	}
2424
2425
2426
	/**
2427
	 * Set the menu title for this page.
2428
	 *
2429
	 * @param string $value
2430
	 */
2431
	public function setMenuTitle($value) {
2432
		if($value == $this->getField("Title")) {
2433
			$this->setField("MenuTitle", null);
2434
		} else {
2435
			$this->setField("MenuTitle", $value);
2436
		}
2437
	}
2438
2439
	/**
2440
	 * A flag provides the user with additional data about the current page status, for example a "removed from draft"
2441
	 * status. Each page can have more than one status flag. Returns a map of a unique key to a (localized) title for
2442
	 * the flag. The unique key can be reused as a CSS class. Use the 'updateStatusFlags' extension point to customize
2443
	 * the flags.
2444
	 *
2445
	 * Example (simple):
2446
	 *   "deletedonlive" => "Deleted"
2447
	 *
2448
	 * Example (with optional title attribute):
2449
	 *   "deletedonlive" => array('text' => "Deleted", 'title' => 'This page has been deleted')
2450
	 *
2451
	 * @param bool $cached Whether to serve the fields from cache; false regenerate them
2452
	 * @return array
2453
	 */
2454
	public function getStatusFlags($cached = true) {
2455
		if(!$this->_cache_statusFlags || !$cached) {
2456
			$flags = array();
2457
			if($this->getIsDeletedFromStage()) {
2458
				if($this->isPublished()) {
0 ignored issues
show
Documentation Bug introduced by
The method isPublished does not exist on object<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...
2459
					$flags['removedfromdraft'] = array(
2460
						'text' => _t('SiteTree.REMOVEDFROMDRAFTSHORT', 'Removed from draft'),
2461
						'title' => _t('SiteTree.REMOVEDFROMDRAFTHELP', 'Page is published, but has been deleted from draft'),
2462
					);
2463
				} else {
2464
					$flags['archived'] = array(
2465
						'text' => _t('SiteTree.ARCHIVEDPAGESHORT', 'Archived'),
2466
						'title' => _t('SiteTree.ARCHIVEDPAGEHELP', 'Page is removed from draft and live'),
2467
					);
2468
				}
2469
			} else if($this->getIsAddedToStage()) {
2470
				$flags['addedtodraft'] = array(
2471
					'text' => _t('SiteTree.ADDEDTODRAFTSHORT', 'Draft'),
2472
					'title' => _t('SiteTree.ADDEDTODRAFTHELP', "Page has not been published yet")
2473
				);
2474
			} else if($this->getIsModifiedOnStage()) {
2475
				$flags['modified'] = array(
2476
					'text' => _t('SiteTree.MODIFIEDONDRAFTSHORT', 'Modified'),
2477
					'title' => _t('SiteTree.MODIFIEDONDRAFTHELP', 'Page has unpublished changes'),
2478
				);
2479
			}
2480
2481
			$this->extend('updateStatusFlags', $flags);
2482
2483
			$this->_cache_statusFlags = $flags;
2484
		}
2485
2486
		return $this->_cache_statusFlags;
2487
	}
2488
2489
	/**
2490
	 * getTreeTitle will return three <span> html DOM elements, an empty <span> with the class 'jstree-pageicon' in
2491
	 * front, following by a <span> wrapping around its MenutTitle, then following by a <span> indicating its
2492
	 * publication status.
2493
	 *
2494
	 * @return string An HTML string ready to be directly used in a template
2495
	 */
2496
	public function getTreeTitle() {
2497
		// Build the list of candidate children
2498
		$children = array();
2499
		$candidates = static::page_type_classes();
2500
		foreach($this->allowedChildren() as $childClass) {
2501
			if(!in_array($childClass, $candidates)) continue;
2502
			$child = singleton($childClass);
2503
			if($child->canCreate(null, array('Parent' => $this))) {
2504
				$children[$childClass] = $child->i18n_singular_name();
2505
			}
2506
		}
2507
		$flags = $this->getStatusFlags();
2508
		$treeTitle = sprintf(
2509
			"<span class=\"jstree-pageicon\"></span><span class=\"item\" data-allowedchildren=\"%s\">%s</span>",
2510
			Convert::raw2att(Convert::raw2json($children)),
2511
			Convert::raw2xml(str_replace(array("\n","\r"),"",$this->MenuTitle))
2512
		);
2513
		foreach($flags as $class => $data) {
2514
			if(is_string($data)) $data = array('text' => $data);
2515
			$treeTitle .= sprintf(
2516
				"<span class=\"badge %s\"%s>%s</span>",
2517
				'status-' . Convert::raw2xml($class),
2518
				(isset($data['title'])) ? sprintf(' title="%s"', Convert::raw2xml($data['title'])) : '',
2519
				Convert::raw2xml($data['text'])
2520
			);
2521
		}
2522
2523
		return $treeTitle;
2524
	}
2525
2526
	/**
2527
	 * Returns the page in the current page stack of the given level. Level(1) will return the main menu item that
2528
	 * we're currently inside, etc.
2529
	 *
2530
	 * @param int $level
2531
	 * @return SiteTree
2532
	 */
2533
	public function Level($level) {
2534
		$parent = $this;
2535
		$stack = array($parent);
2536
		while($parent = $parent->Parent) {
2537
			array_unshift($stack, $parent);
2538
		}
2539
2540
		return isset($stack[$level-1]) ? $stack[$level-1] : null;
2541
	}
2542
2543
	/**
2544
	 * Gets the depth of this page in the sitetree, where 1 is the root level
2545
	 *
2546
	 * @return int
2547
	 */
2548
	public function getPageLevel() {
2549
		if($this->ParentID) {
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<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...
2550
			return 1 + $this->Parent()->getPageLevel();
0 ignored issues
show
Bug introduced by
The method Parent() does not exist on SiteTree. Did you maybe mean setParent()?

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...
2551
		}
2552
		return 1;
2553
	}
2554
2555
	/**
2556
	 * Return the CSS classes to apply to this node in the CMS tree.
2557
	 *
2558
	 * @param string $numChildrenMethod
2559
	 * @return string
2560
	 */
2561
	public function CMSTreeClasses($numChildrenMethod="numChildren") {
2562
		$classes = sprintf('class-%s', $this->class);
2563
		if($this->HasBrokenFile || $this->HasBrokenLink) {
0 ignored issues
show
Documentation introduced by
The property HasBrokenFile does not exist on object<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<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...
2564
			$classes .= " BrokenLink";
2565
		}
2566
2567
		if(!$this->canAddChildren()) {
2568
			$classes .= " nochildren";
2569
		}
2570
2571
		if(!$this->canEdit() && !$this->canAddChildren()) {
2572
			if (!$this->canView()) {
2573
				$classes .= " disabled";
2574
			} else {
2575
				$classes .= " edit-disabled";
2576
			}
2577
		}
2578
2579
		if(!$this->ShowInMenus) {
2580
			$classes .= " notinmenu";
2581
		}
2582
2583
		//TODO: Add integration
2584
		/*
2585
		if($this->hasExtension('Translatable') && $controller->Locale != Translatable::default_locale() && !$this->isTranslation())
2586
			$classes .= " untranslated ";
2587
		*/
2588
		$classes .= $this->markingClasses($numChildrenMethod);
0 ignored issues
show
Documentation Bug introduced by
The method markingClasses does not exist on object<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...
2589
2590
		return $classes;
2591
	}
2592
2593
	/**
2594
	 * Compares current draft with live version, and returns true if no draft version of this page exists  but the page
2595
	 * is still published (eg, after triggering "Delete from draft site" in the CMS).
2596
	 *
2597
	 * @return bool
2598
	 */
2599
	public function getIsDeletedFromStage() {
2600
		if(!$this->ID) return true;
2601
		if($this->isNew()) return false;
2602
2603
		$stageVersion = Versioned::get_versionnumber_by_stage('SiteTree', Versioned::DRAFT, $this->ID);
2604
2605
		// Return true for both completely deleted pages and for pages just deleted from stage
2606
		return !($stageVersion);
2607
	}
2608
2609
	/**
2610
	 * Return true if this page exists on the live site
2611
	 *
2612
	 * @return bool
2613
	 */
2614
	public function getExistsOnLive() {
2615
		return $this->isPublished();
0 ignored issues
show
Documentation Bug introduced by
The method isPublished does not exist on object<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...
2616
	}
2617
2618
	/**
2619
	 * Compares current draft with live version, and returns true if these versions differ, meaning there have been
2620
	 * unpublished changes to the draft site.
2621
	 *
2622
	 * @return bool
2623
	 */
2624
	public function getIsModifiedOnStage() {
2625
		// New unsaved pages could be never be published
2626
		if($this->isNew()) return false;
2627
2628
		$stageVersion = Versioned::get_versionnumber_by_stage('SiteTree', 'Stage', $this->ID);
2629
		$liveVersion =	Versioned::get_versionnumber_by_stage('SiteTree', 'Live', $this->ID);
2630
2631
		$isModified = ($stageVersion && $stageVersion != $liveVersion);
2632
		$this->extend('getIsModifiedOnStage', $isModified);
2633
2634
		return $isModified;
2635
	}
2636
2637
	/**
2638
	 * Compares current draft with live version, and returns true if no live version exists, meaning the page was never
2639
	 * published.
2640
	 *
2641
	 * @return bool
2642
	 */
2643
	public function getIsAddedToStage() {
2644
		// New unsaved pages could be never be published
2645
		if($this->isNew()) return false;
2646
2647
		$stageVersion = Versioned::get_versionnumber_by_stage('SiteTree', 'Stage', $this->ID);
2648
		$liveVersion =	Versioned::get_versionnumber_by_stage('SiteTree', 'Live', $this->ID);
2649
2650
		return ($stageVersion && !$liveVersion);
2651
	}
2652
2653
	/**
2654
	 * Stops extendCMSFields() being called on getCMSFields(). This is useful when you need access to fields added by
2655
	 * subclasses of SiteTree in a extension. Call before calling parent::getCMSFields(), and reenable afterwards.
2656
	 */
2657
	static public function disableCMSFieldsExtensions() {
2658
		self::$runCMSFieldsExtensions = false;
2659
	}
2660
2661
	/**
2662
	 * Reenables extendCMSFields() being called on getCMSFields() after it has been disabled by
2663
	 * disableCMSFieldsExtensions().
2664
	 */
2665
	static public function enableCMSFieldsExtensions() {
2666
		self::$runCMSFieldsExtensions = true;
2667
	}
2668
2669
	public function providePermissions() {
2670
		return array(
2671
			'SITETREE_GRANT_ACCESS' => array(
2672
				'name' => _t('SiteTree.PERMISSION_GRANTACCESS_DESCRIPTION', 'Manage access rights for content'),
2673
				'help' => _t('SiteTree.PERMISSION_GRANTACCESS_HELP',  'Allow setting of page-specific access restrictions in the "Pages" section.'),
2674
				'category' => _t('Permissions.PERMISSIONS_CATEGORY', 'Roles and access permissions'),
2675
				'sort' => 100
2676
			),
2677
			'SITETREE_VIEW_ALL' => array(
2678
				'name' => _t('SiteTree.VIEW_ALL_DESCRIPTION', 'View any page'),
2679
				'category' => _t('Permissions.CONTENT_CATEGORY', 'Content permissions'),
2680
				'sort' => -100,
2681
				'help' => _t('SiteTree.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')
2682
			),
2683
			'SITETREE_EDIT_ALL' => array(
2684
				'name' => _t('SiteTree.EDIT_ALL_DESCRIPTION', 'Edit any page'),
2685
				'category' => _t('Permissions.CONTENT_CATEGORY', 'Content permissions'),
2686
				'sort' => -50,
2687
				'help' => _t('SiteTree.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')
2688
			),
2689
			'SITETREE_REORGANISE' => array(
2690
				'name' => _t('SiteTree.REORGANISE_DESCRIPTION', 'Change site structure'),
2691
				'category' => _t('Permissions.CONTENT_CATEGORY', 'Content permissions'),
2692
				'help' => _t('SiteTree.REORGANISE_HELP', 'Rearrange pages in the site tree through drag&drop.'),
2693
				'sort' => 100
2694
			),
2695
			'VIEW_DRAFT_CONTENT' => array(
2696
				'name' => _t('SiteTree.VIEW_DRAFT_CONTENT', 'View draft content'),
2697
				'category' => _t('Permissions.CONTENT_CATEGORY', 'Content permissions'),
2698
				'help' => _t('SiteTree.VIEW_DRAFT_CONTENT_HELP', 'Applies to viewing pages outside of the CMS in draft mode. Useful for external collaborators without CMS access.'),
2699
				'sort' => 100
2700
			)
2701
		);
2702
	}
2703
2704
	/**
2705
	 * Return the translated Singular name.
2706
	 *
2707
	 * @return string
2708
	 */
2709
	public function i18n_singular_name() {
2710
		// Convert 'Page' to 'SiteTree' for correct localization lookups
2711
		$class = ($this->class == 'Page') ? 'SiteTree' : $this->class;
2712
		return _t($class.'.SINGULARNAME', $this->singular_name());
2713
	}
2714
2715
	/**
2716
	 * Overloaded to also provide entities for 'Page' class which is usually located in custom code, hence textcollector
2717
	 * picks it up for the wrong folder.
2718
	 *
2719
	 * @return array
2720
	 */
2721
	public function provideI18nEntities() {
2722
		$entities = parent::provideI18nEntities();
2723
2724
		if(isset($entities['Page.SINGULARNAME'])) $entities['Page.SINGULARNAME'][3] = CMS_DIR;
2725
		if(isset($entities['Page.PLURALNAME'])) $entities['Page.PLURALNAME'][3] = CMS_DIR;
2726
2727
		$entities[$this->class . '.DESCRIPTION'] = array(
2728
			$this->stat('description'),
2729
			'Description of the page type (shown in the "add page" dialog)'
2730
		);
2731
2732
		$entities['SiteTree.SINGULARNAME'][0] = 'Page';
2733
		$entities['SiteTree.PLURALNAME'][0] = 'Pages';
2734
2735
		return $entities;
0 ignored issues
show
Best Practice introduced by
The expression return $entities; seems to be an array, but some of its elements' types (null) are incompatible with the return type of the parent method DataObject::provideI18nEntities of type array<*,array<array|inte...double|string|boolean>>.

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

Let’s take a look at an example:

class Author {
    private $name;

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

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

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

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

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

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

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

Loading history...
2736
	}
2737
2738
	/**
2739
	 * Returns 'root' if the current page has no parent, or 'subpage' otherwise
2740
	 *
2741
	 * @return string
2742
	 */
2743
	public function getParentType() {
2744
		return $this->ParentID == 0 ? 'root' : 'subpage';
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<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...
2745
	}
2746
2747
	/**
2748
	 * Clear the permissions cache for SiteTree
2749
	 */
2750
	public static function reset() {
2751
		self::$cache_permissions = array();
2752
	}
2753
2754
	static public function on_db_reset() {
2755
		self::$cache_permissions = array();
2756
	}
2757
2758
}
2759