Completed
Push — master ( 53daaf...e5aad3 )
by Daniel
03:49
created

SiteTree::generateURLSegment()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
rs 9.2
cc 4
eloc 6
nc 2
nop 1
1
<?php
2
3
use SilverStripe\ORM\DataObject;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, DataObject.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
4
use SilverStripe\ORM\Hierarchy\Hierarchy;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Hierarchy.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
5
use SilverStripe\ORM\ManyManyList;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, ManyManyList.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
6
use SilverStripe\ORM\Versioning\Versioned;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Versioned.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
7
use SilverStripe\ORM\ArrayList;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, ArrayList.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
8
use SilverStripe\ORM\DB;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, DB.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
9
use SilverStripe\ORM\DataList;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, DataList.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
10
use SilverStripe\ORM\HiddenClass;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, HiddenClass.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
11
use SilverStripe\Security\Member;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Member.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
12
use SilverStripe\Security\Permission;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Permission.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
13
use SilverStripe\Security\Group;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Group.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
14
use SilverStripe\Security\PermissionProvider;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, PermissionProvider.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
15
16
17
/**
18
 * Basic data-object representing all pages within the site tree. All page types that live within the hierarchy should
19
 * inherit from this. In addition, it contains a number of static methods for querying the site tree and working with
20
 * draft and published states.
21
 *
22
 * <h2>URLs</h2>
23
 * A page is identified during request handling via its "URLSegment" database column. As pages can be nested, the full
24
 * path of a URL might contain multiple segments. Each segment is stored in its filtered representation (through
25
 * {@link URLSegmentFilter}). The full path is constructed via {@link Link()}, {@link RelativeLink()} and
26
 * {@link AbsoluteLink()}. You can allow these segments to contain multibyte characters through
27
 * {@link URLSegmentFilter::$default_allow_multibyte}.
28
 *
29
 * @property string URLSegment
30
 * @property string Title
31
 * @property string MenuTitle
32
 * @property string Content HTML content of the page.
33
 * @property string MetaDescription
34
 * @property string ExtraMeta
35
 * @property string ShowInMenus
36
 * @property string ShowInSearch
37
 * @property string Sort Integer value denoting the sort order.
38
 * @property string ReportClass
39
 * @property string CanViewType Type of restriction for viewing this object.
40
 * @property string CanEditType Type of restriction for editing this object.
41
 *
42
 * @method ManyManyList ViewerGroups List of groups that can view this object.
43
 * @method ManyManyList EditorGroups List of groups that can edit this object.
44
 *
45
 * @mixin Hierarchy
46
 * @mixin Versioned
47
 * @mixin SiteTreeLinkTracking
48
 *
49
 * @package cms
50
 */
51
class SiteTree extends DataObject implements PermissionProvider,i18nEntityProvider,CMSPreviewable {
52
53
	/**
54
	 * Indicates what kind of children this page type can have.
55
	 * This can be an array of allowed child classes, or the string "none" -
56
	 * indicating that this page type can't have children.
57
	 * If a classname is prefixed by "*", such as "*Page", then only that
58
	 * class is allowed - no subclasses. Otherwise, the class and all its
59
	 * subclasses are allowed.
60
	 * To control allowed children on root level (no parent), use {@link $can_be_root}.
61
	 *
62
	 * Note that this setting is cached when used in the CMS, use the "flush" query parameter to clear it.
63
	 *
64
	 * @config
65
	 * @var array
66
	 */
67
	private static $allowed_children = array("SiteTree");
68
69
	/**
70
	 * The default child class for this page.
71
	 * Note: Value might be cached, see {@link $allowed_chilren}.
72
	 *
73
	 * @config
74
	 * @var string
75
	 */
76
	private static $default_child = "Page";
77
78
	/**
79
	 * Default value for SiteTree.ClassName enum
80
	 * {@see DBClassName::getDefault}
81
	 *
82
	 * @config
83
	 * @var string
84
	 */
85
	private static $default_classname = "Page";
86
87
	/**
88
	 * The default parent class for this page.
89
	 * Note: Value might be cached, see {@link $allowed_chilren}.
90
	 *
91
	 * @config
92
	 * @var string
93
	 */
94
	private static $default_parent = null;
95
96
	/**
97
	 * Controls whether a page can be in the root of the site tree.
98
	 * Note: Value might be cached, see {@link $allowed_chilren}.
99
	 *
100
	 * @config
101
	 * @var bool
102
	 */
103
	private static $can_be_root = true;
104
105
	/**
106
	 * List of permission codes a user can have to allow a user to create a page of this type.
107
	 * Note: Value might be cached, see {@link $allowed_chilren}.
108
	 *
109
	 * @config
110
	 * @var array
111
	 */
112
	private static $need_permission = null;
113
114
	/**
115
	 * If you extend a class, and don't want to be able to select the old class
116
	 * in the cms, set this to the old class name. Eg, if you extended Product
117
	 * to make ImprovedProduct, then you would set $hide_ancestor to Product.
118
	 *
119
	 * @config
120
	 * @var string
121
	 */
122
	private static $hide_ancestor = null;
123
124
	private static $db = array(
125
		"URLSegment" => "Varchar(255)",
126
		"Title" => "Varchar(255)",
127
		"MenuTitle" => "Varchar(100)",
128
		"Content" => "HTMLText",
129
		"MetaDescription" => "Text",
130
		"ExtraMeta" => "HTMLFragment(['whitelist' => ['meta', 'link']])",
131
		"ShowInMenus" => "Boolean",
132
		"ShowInSearch" => "Boolean",
133
		"Sort" => "Int",
134
		"HasBrokenFile" => "Boolean",
135
		"HasBrokenLink" => "Boolean",
136
		"ReportClass" => "Varchar",
137
		"CanViewType" => "Enum('Anyone, LoggedInUsers, OnlyTheseUsers, Inherit', 'Inherit')",
138
		"CanEditType" => "Enum('LoggedInUsers, OnlyTheseUsers, Inherit', 'Inherit')",
139
	);
140
141
	private static $indexes = array(
142
		"URLSegment" => true,
143
	);
144
145
	private static $many_many = array(
146
		"ViewerGroups" => "SilverStripe\\Security\\Group",
147
		"EditorGroups" => "SilverStripe\\Security\\Group",
148
	);
149
150
	private static $has_many = array(
151
		"VirtualPages" => "VirtualPage.CopyContentFrom"
152
	);
153
154
	private static $owned_by = array(
155
		"VirtualPages"
156
	);
157
158
	private static $casting = array(
159
		"Breadcrumbs" => "HTMLFragment",
160
		"LastEdited" => "Datetime",
161
		"Created" => "Datetime",
162
		'Link' => 'Text',
163
		'RelativeLink' => 'Text',
164
		'AbsoluteLink' => 'Text',
165
		'CMSEditLink' => 'Text',
166
		'TreeTitle' => 'HTMLFragment',
167
		'MetaTags' => 'HTMLFragment',
168
	);
169
170
	private static $defaults = array(
171
		"ShowInMenus" => 1,
172
		"ShowInSearch" => 1,
173
		"CanViewType" => "Inherit",
174
		"CanEditType" => "Inherit"
175
	);
176
177
	private static $versioning = array(
178
		"Stage",  "Live"
179
	);
180
181
	private static $default_sort = "\"Sort\"";
182
183
	/**
184
	 * If this is false, the class cannot be created in the CMS by regular content authors, only by ADMINs.
185
	 * @var boolean
186
	 * @config
187
	 */
188
	private static $can_create = true;
189
190
	/**
191
	 * Icon to use in the CMS page tree. This should be the full filename, relative to the webroot.
192
	 * Also supports custom CSS rule contents (applied to the correct selector for the tree UI implementation).
193
	 *
194
	 * @see CMSMain::generateTreeStylingCSS()
195
	 * @config
196
	 * @var string
197
	 */
198
	private static $icon = null;
199
200
	/**
201
	 * @config
202
	 * @var string Description of the class functionality, typically shown to a user
203
	 * when selecting which page type to create. Translated through {@link provideI18nEntities()}.
204
	 */
205
	private static $description = 'Generic content page';
206
207
	private static $extensions = array(
208
		'SilverStripe\ORM\Hierarchy\Hierarchy',
209
		'SilverStripe\ORM\Versioning\Versioned',
210
		"SiteTreeLinkTracking"
211
	);
212
213
	private static $searchable_fields = array(
214
		'Title',
215
		'Content',
216
	);
217
218
	private static $field_labels = array(
219
		'URLSegment' => 'URL'
220
	);
221
222
	/**
223
	 * @config
224
	 */
225
	private static $nested_urls = true;
226
227
	/**
228
	 * @config
229
	*/
230
	private static $create_default_pages = true;
231
232
	/**
233
	 * This controls whether of not extendCMSFields() is called by getCMSFields.
234
	 */
235
	private static $runCMSFieldsExtensions = true;
236
237
	/**
238
	 * Cache for canView/Edit/Publish/Delete permissions.
239
	 * Keyed by permission type (e.g. 'edit'), with an array
240
	 * of IDs mapped to their boolean permission ability (true=allow, false=deny).
241
	 * See {@link batch_permission_check()} for details.
242
	 */
243
	private static $cache_permissions = array();
244
245
	/**
246
	 * @config
247
	 * @var boolean
248
	 */
249
	private static $enforce_strict_hierarchy = true;
250
251
	/**
252
	 * The value used for the meta generator tag. Leave blank to omit the tag.
253
	 *
254
	 * @config
255
	 * @var string
256
	 */
257
	private static $meta_generator = 'SilverStripe - http://silverstripe.org';
258
259
	protected $_cache_statusFlags = null;
260
261
	/**
262
	 * Fetches the {@link SiteTree} object that maps to a link.
263
	 *
264
	 * If you have enabled {@link SiteTree::config()->nested_urls} on this site, then you can use a nested link such as
265
	 * "about-us/staff/", and this function will traverse down the URL chain and grab the appropriate link.
266
	 *
267
	 * Note that if no model can be found, this method will fall over to a extended alternateGetByLink method provided
268
	 * by a extension attached to {@link SiteTree}
269
	 *
270
	 * @param string $link  The link of the page to search for
271
	 * @param bool   $cache True (default) to use caching, false to force a fresh search from the database
272
	 * @return SiteTree
273
	 */
274
	static public function get_by_link($link, $cache = true) {
275
		if(trim($link, '/')) {
276
			$link = trim(Director::makeRelative($link), '/');
277
		} else {
278
			$link = RootURLController::get_homepage_link();
279
		}
280
281
		$parts = preg_split('|/+|', $link);
282
283
		// Grab the initial root level page to traverse down from.
284
		$URLSegment = array_shift($parts);
285
		$conditions = array('"SiteTree"."URLSegment"' => rawurlencode($URLSegment));
286
		if(self::config()->nested_urls) {
287
			$conditions[] = array('"SiteTree"."ParentID"' => 0);
288
		}
289
		$sitetree = DataObject::get_one('SiteTree', $conditions, $cache);
290
291
		/// Fall back on a unique URLSegment for b/c.
292
		if(	!$sitetree
293
			&& self::config()->nested_urls
294
			&& $page = DataObject::get_one('SiteTree', array(
295
				'"SiteTree"."URLSegment"' => $URLSegment
296
			), $cache)
297
		) {
298
			return $page;
299
		}
300
301
		// Attempt to grab an alternative page from extensions.
302
		if(!$sitetree) {
303
			$parentID = self::config()->nested_urls ? 0 : null;
304
305 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...
306
				foreach($alternatives as $alternative) if($alternative) $sitetree = $alternative;
307
			}
308
309
			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...
310
		}
311
312
		// Check if we have any more URL parts to parse.
313
		if(!self::config()->nested_urls || !count($parts)) return $sitetree;
314
315
		// Traverse down the remaining URL segments and grab the relevant SiteTree objects.
316
		foreach($parts as $segment) {
317
			$next = DataObject::get_one('SiteTree', array(
318
					'"SiteTree"."URLSegment"' => $segment,
319
					'"SiteTree"."ParentID"' => $sitetree->ID
320
				),
321
				$cache
322
			);
323
324
			if(!$next) {
325
				$parentID = (int) $sitetree->ID;
326
327 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...
328
					foreach($alternatives as $alternative) if($alternative) $next = $alternative;
329
				}
330
331
				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...
332
			}
333
334
			$sitetree->destroy();
335
			$sitetree = $next;
336
		}
337
338
		return $sitetree;
339
	}
340
341
	/**
342
	 * Return a subclass map of SiteTree that shouldn't be hidden through {@link SiteTree::$hide_ancestor}
343
	 *
344
	 * @return array
345
	 */
346
	public static function page_type_classes() {
347
		$classes = ClassInfo::getValidSubClasses();
348
349
		$baseClassIndex = array_search('SiteTree', $classes);
350
		if($baseClassIndex !== FALSE) unset($classes[$baseClassIndex]);
351
352
		$kill_ancestors = array();
353
354
		// figure out if there are any classes we don't want to appear
355
		foreach($classes as $class) {
356
			$instance = singleton($class);
357
358
			// do any of the progeny want to hide an ancestor?
359
			if($ancestor_to_hide = $instance->stat('hide_ancestor')) {
360
				// note for killing later
361
				$kill_ancestors[] = $ancestor_to_hide;
362
			}
363
		}
364
365
		// If any of the descendents don't want any of the elders to show up, cruelly render the elders surplus to
366
		// requirements
367
		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...
368
			$kill_ancestors = array_unique($kill_ancestors);
369
			foreach($kill_ancestors as $mark) {
370
				// unset from $classes
371
				$idx = array_search($mark, $classes, true);
372
				if ($idx !== false) {
373
					unset($classes[$idx]);
374
				}
375
			}
376
		}
377
378
		return $classes;
379
	}
380
381
	/**
382
	 * Replace a "[sitetree_link id=n]" shortcode with a link to the page with the corresponding ID.
383
	 *
384
	 * @param array      $arguments
385
	 * @param string     $content
386
	 * @param TextParser $parser
387
	 * @return string
388
	 */
389
	static public function link_shortcode_handler($arguments, $content = null, $parser = null) {
390
		if(!isset($arguments['id']) || !is_numeric($arguments['id'])) return;
391
392
		if (
393
			   !($page = DataObject::get_by_id('SiteTree', $arguments['id']))         // Get the current page by ID.
394
			&& !($page = Versioned::get_latest_version('SiteTree', $arguments['id'])) // Attempt link to old version.
395
		) {
396
			 return null; // There were no suitable matches at all.
397
		}
398
399
		$link = Convert::raw2att($page->Link());
400
401
		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...
402
			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...
403
		} else {
404
			return $link;
405
		}
406
	}
407
408
	/**
409
	 * Return the link for this {@link SiteTree} object, with the {@link Director::baseURL()} included.
410
	 *
411
	 * @param string $action Optional controller action (method).
412
	 *                       Note: URI encoding of this parameter is applied automatically through template casting,
413
	 *                       don't encode the passed parameter. Please use {@link Controller::join_links()} instead to
414
	 *                       append GET parameters.
415
	 * @return string
416
	 */
417
	public function Link($action = null) {
418
		return Controller::join_links(Director::baseURL(), $this->RelativeLink($action));
419
	}
420
421
	/**
422
	 * Get the absolute URL for this page, including protocol and host.
423
	 *
424
	 * @param string $action See {@link Link()}
425
	 * @return string
426
	 */
427
	public function AbsoluteLink($action = null) {
428
		if($this->hasMethod('alternateAbsoluteLink')) {
429
			return $this->alternateAbsoluteLink($action);
430
		} else {
431
			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 431 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...
432
		}
433
	}
434
435
	/**
436
	 * Base link used for previewing. Defaults to absolute URL, in order to account for domain changes, e.g. on multi
437
	 * site setups. Does not contain hints about the stage, see {@link SilverStripeNavigator} for details.
438
	 *
439
	 * @param string $action See {@link Link()}
440
	 * @return string
441
	 */
442
	public function PreviewLink($action = null) {
443
		if($this->hasMethod('alternatePreviewLink')) {
444
			Deprecation::notice('5.0', 'Use updatePreviewLink or override PreviewLink method');
445
			return $this->alternatePreviewLink($action);
446
		}
447
448
		$link = $this->AbsoluteLink($action);
449
		$this->extend('updatePreviewLink', $link, $action);
450
		return $link;
451
	}
452
453
	public function getMimeType() {
454
		return 'text/html';
455
	}
456
457
	/**
458
	 * Return the link for this {@link SiteTree} object relative to the SilverStripe root.
459
	 *
460
	 * By default, if this page is the current home page, and there is no action specified then this will return a link
461
	 * to the root of the site. However, if you set the $action parameter to TRUE then the link will not be rewritten
462
	 * and returned in its full form.
463
	 *
464
	 * @uses RootURLController::get_homepage_link()
465
	 *
466
	 * @param string $action See {@link Link()}
467
	 * @return string
468
	 */
469
	public function RelativeLink($action = null) {
470
		if($this->ParentID && self::config()->nested_urls) {
471
			$parent = $this->Parent();
472
			// If page is removed select parent from version history (for archive page view)
473
			if((!$parent || !$parent->exists()) && $this->IsDeletedFromStage) {
474
				$parent = Versioned::get_latest_version('SiteTree', $this->ParentID);
475
			}
476
			$base = $parent->RelativeLink($this->URLSegment);
477
		} 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...
478
			// Unset base for root-level homepages.
479
			// Note: Homepages with action parameters (or $action === true)
480
			// need to retain their URLSegment.
481
			$base = null;
482
		} else {
483
			$base = $this->URLSegment;
484
		}
485
486
		$this->extend('updateRelativeLink', $base, $action);
487
488
		// Legacy support: If $action === true, retain URLSegment for homepages,
489
		// but don't append any action
490
		if($action === true) $action = null;
491
492
		return Controller::join_links($base, '/', $action);
493
	}
494
495
	/**
496
	 * Get the absolute URL for this page on the Live site.
497
	 *
498
	 * @param bool $includeStageEqualsLive Whether to append the URL with ?stage=Live to force Live mode
499
	 * @return string
500
	 */
501
	public function getAbsoluteLiveLink($includeStageEqualsLive = true) {
502
		$oldReadingMode = Versioned::get_reading_mode();
503
		Versioned::set_stage(Versioned::LIVE);
504
		$live = Versioned::get_one_by_stage('SiteTree', Versioned::LIVE, array(
505
			'"SiteTree"."ID"' => $this->ID
506
		));
507
		if($live) {
508
			$link = $live->AbsoluteLink();
509
			if($includeStageEqualsLive) $link .= '?stage=Live';
510
		} else {
511
			$link = null;
512
		}
513
514
		Versioned::set_reading_mode($oldReadingMode);
515
		return $link;
516
	}
517
518
	/**
519
	 * Generates a link to edit this page in the CMS.
520
	 *
521
	 * @return string
522
	 */
523
	public function CMSEditLink() {
524
		$link = Controller::join_links(
525
			singleton('CMSPageEditController')->Link('show'),
526
			$this->ID
527
		);
528
		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 528 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...
529
	}
530
531
532
	/**
533
	 * Return a CSS identifier generated from this page's link.
534
	 *
535
	 * @return string The URL segment
536
	 */
537
	public function ElementName() {
538
		return str_replace('/', '-', trim($this->RelativeLink(true), '/'));
539
	}
540
541
	/**
542
	 * Returns true if this is the currently active page being used to handle this request.
543
	 *
544
	 * @return bool
545
	 */
546
	public function isCurrent() {
547
		return $this->ID ? $this->ID == Director::get_current_page()->ID : $this === Director::get_current_page();
548
	}
549
550
	/**
551
	 * Check if this page is in the currently active section (e.g. it is either current or one of its children is
552
	 * currently being viewed).
553
	 *
554
	 * @return bool
555
	 */
556
	public function isSection() {
557
		return $this->isCurrent() || (
558
			Director::get_current_page() instanceof SiteTree && in_array($this->ID, Director::get_current_page()->getAncestors()->column())
559
		);
560
	}
561
562
	/**
563
	 * Check if the parent of this page has been removed (or made otherwise unavailable), and is still referenced by
564
	 * this child. Any such orphaned page may still require access via the CMS, but should not be shown as accessible
565
	 * to external users.
566
	 *
567
	 * @return bool
568
	 */
569
	public function isOrphaned() {
570
		// Always false for root pages
571
		if(empty($this->ParentID)) return false;
572
573
		// Parent must exist and not be an orphan itself
574
		$parent = $this->Parent();
575
		return !$parent || !$parent->exists() || $parent->isOrphaned();
576
	}
577
578
	/**
579
	 * Return "link" or "current" depending on if this is the {@link SiteTree::isCurrent()} current page.
580
	 *
581
	 * @return string
582
	 */
583
	public function LinkOrCurrent() {
584
		return $this->isCurrent() ? 'current' : 'link';
585
	}
586
587
	/**
588
	 * Return "link" or "section" depending on if this is the {@link SiteTree::isSeciton()} current section.
589
	 *
590
	 * @return string
591
	 */
592
	public function LinkOrSection() {
593
		return $this->isSection() ? 'section' : 'link';
594
	}
595
596
	/**
597
	 * Return "link", "current" or "section" depending on if this page is the current page, or not on the current page
598
	 * but in the current section.
599
	 *
600
	 * @return string
601
	 */
602
	public function LinkingMode() {
603
		if($this->isCurrent()) {
604
			return 'current';
605
		} elseif($this->isSection()) {
606
			return 'section';
607
		} else {
608
			return 'link';
609
		}
610
	}
611
612
	/**
613
	 * Check if this page is in the given current section.
614
	 *
615
	 * @param string $sectionName Name of the section to check
616
	 * @return bool True if we are in the given section
617
	 */
618
	public function InSection($sectionName) {
619
		$page = Director::get_current_page();
620
		while($page) {
621
			if($sectionName == $page->URLSegment)
622
				return true;
623
			$page = $page->Parent;
624
		}
625
		return false;
626
	}
627
628
	/**
629
	 * Reset Sort on duped page
630
	 *
631
	 * @param SiteTree $original
632
	 * @param bool $doWrite
633
	 */
634
	public function onBeforeDuplicate($original, $doWrite) {
635
		$this->Sort = 0;
636
	}
637
638
	/**
639
	 * Duplicates each child of this node recursively and returns the top-level duplicate node.
640
	 *
641
	 * @return self The duplicated object
642
	 */
643
	public function duplicateWithChildren() {
644
		$clone = $this->duplicate();
645
		$children = $this->AllChildren();
646
647
		if($children) {
648
			foreach($children as $child) {
649
				$childClone = method_exists($child, 'duplicateWithChildren')
650
					? $child->duplicateWithChildren()
651
					: $child->duplicate();
652
				$childClone->ParentID = $clone->ID;
653
				$childClone->write();
654
			}
655
		}
656
657
		return $clone;
658
	}
659
660
	/**
661
	 * Duplicate this node and its children as a child of the node with the given ID
662
	 *
663
	 * @param int $id ID of the new node's new parent
664
	 */
665
	public function duplicateAsChild($id) {
666
		$newSiteTree = $this->duplicate();
667
		$newSiteTree->ParentID = $id;
668
		$newSiteTree->Sort = 0;
669
		$newSiteTree->write();
670
	}
671
672
	/**
673
	 * Return a breadcrumb trail to this page. Excludes "hidden" pages (with ShowInMenus=0) by default.
674
	 *
675
	 * @param int $maxDepth The maximum depth to traverse.
676
	 * @param boolean $unlinked Whether to link page titles.
677
	 * @param boolean|string $stopAtPageType ClassName of a page to stop the upwards traversal.
678
	 * @param boolean $showHidden Include pages marked with the attribute ShowInMenus = 0
679
	 * @return string The breadcrumb trail.
680
	 */
681
	public function Breadcrumbs($maxDepth = 20, $unlinked = false, $stopAtPageType = false, $showHidden = false) {
682
		$pages = $this->getBreadcrumbItems($maxDepth, $stopAtPageType, $showHidden);
683
		$template = new SSViewer('BreadcrumbsTemplate');
684
		return $template->process($this->customise(new ArrayData(array(
685
			"Pages" => $pages,
686
			"Unlinked" => $unlinked
687
		))));
688
	}
689
690
691
	/**
692
	 * Returns a list of breadcrumbs for the current page.
693
	 *
694
	 * @param int $maxDepth The maximum depth to traverse.
695
	 * @param boolean|string $stopAtPageType ClassName of a page to stop the upwards traversal.
696
	 * @param boolean $showHidden Include pages marked with the attribute ShowInMenus = 0
697
	 *
698
	 * @return ArrayList
699
	*/
700
	public function getBreadcrumbItems($maxDepth = 20, $stopAtPageType = false, $showHidden = false) {
701
		$page = $this;
702
		$pages = array();
703
704
		while(
705
			$page
706
 			&& (!$maxDepth || count($pages) < $maxDepth)
707
 			&& (!$stopAtPageType || $page->ClassName != $stopAtPageType)
708
 		) {
709
			if($showHidden || $page->ShowInMenus || ($page->ID == $this->ID)) {
710
				$pages[] = $page;
711
			}
712
713
			$page = $page->Parent;
714
		}
715
716
		return new ArrayList(array_reverse($pages));
717
	}
718
719
720
	/**
721
	 * Make this page a child of another page.
722
	 *
723
	 * If the parent page does not exist, resolve it to a valid ID before updating this page's reference.
724
	 *
725
	 * @param SiteTree|int $item Either the parent object, or the parent ID
726
	 */
727
	public function setParent($item) {
728
		if(is_object($item)) {
729
			if (!$item->exists()) $item->write();
730
			$this->setField("ParentID", $item->ID);
731
		} else {
732
			$this->setField("ParentID", $item);
733
		}
734
	}
735
736
	/**
737
	 * Get the parent of this page.
738
	 *
739
	 * @return SiteTree Parent of this page
740
	 */
741
	public function getParent() {
742
		if ($parentID = $this->getField("ParentID")) {
743
			return DataObject::get_by_id("SiteTree", $parentID);
744
		}
745
	}
746
747
	/**
748
	 * Return a string of the form "parent - page" or "grandparent - parent - page" using page titles
749
	 *
750
	 * @param int $level The maximum amount of levels to traverse.
751
	 * @param string $separator Seperating string
752
	 * @return string The resulting string
753
	 */
754
	public function NestedTitle($level = 2, $separator = " - ") {
755
		$item = $this;
756
		$parts = [];
757
		while($item && $level > 0) {
758
			$parts[] = $item->Title;
759
			$item = $item->Parent;
760
			$level--;
761
		}
762
		return implode($separator, array_reverse($parts));
763
	}
764
765
	/**
766
	 * This function should return true if the current user can execute this action. It can be overloaded to customise
767
	 * the security model for an application.
768
	 *
769
	 * Slightly altered from parent behaviour in {@link DataObject->can()}:
770
	 * - Checks for existence of a method named "can<$perm>()" on the object
771
	 * - Calls decorators and only returns for FALSE "vetoes"
772
	 * - Falls back to {@link Permission::check()}
773
	 * - Does NOT check for many-many relations named "Can<$perm>"
774
	 *
775
	 * @uses DataObjectDecorator->can()
776
	 *
777
	 * @param string $perm The permission to be checked, such as 'View'
778
	 * @param Member $member The member whose permissions need checking. Defaults to the currently logged in user.
779
	 * @param array $context Context argument for canCreate()
780
	 * @return bool True if the the member is allowed to do the given action
781
	 */
782
	public function can($perm, $member = null, $context = array()) {
783 View Code Duplication
		if(!$member || !($member instanceof Member) || is_numeric($member)) {
0 ignored issues
show
Bug introduced by
The class SilverStripe\Security\Member does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
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...
784
			$member = Member::currentUserID();
785
		}
786
787
		if($member && Permission::checkMember($member, "ADMIN")) return true;
788
789
		if(is_string($perm) && method_exists($this, 'can' . ucfirst($perm))) {
790
			$method = 'can' . ucfirst($perm);
791
			return $this->$method($member);
792
		}
793
794
		$results = $this->extend('can', $member);
795
		if($results && is_array($results)) if(!min($results)) return false;
796
797
		return ($member && Permission::checkMember($member, $perm));
798
	}
799
800
	/**
801
	 * This function should return true if the current user can add children to this page. It can be overloaded to
802
	 * customise the security model for an application.
803
	 *
804
	 * Denies permission if any of the following conditions is true:
805
	 * - alternateCanAddChildren() on a extension returns false
806
	 * - canEdit() is not granted
807
	 * - There are no classes defined in {@link $allowed_children}
808
	 *
809
	 * @uses SiteTreeExtension->canAddChildren()
810
	 * @uses canEdit()
811
	 * @uses $allowed_children
812
	 *
813
	 * @param Member|int $member
814
	 * @return bool True if the current user can add children
815
	 */
816
	public function canAddChildren($member = null) {
817
		// Disable adding children to archived pages
818
		if($this->getIsDeletedFromStage()) {
819
			return false;
820
		}
821
822 View Code Duplication
		if(!$member || !($member instanceof Member) || is_numeric($member)) {
0 ignored issues
show
Bug introduced by
The class SilverStripe\Security\Member does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
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...
823
			$member = Member::currentUserID();
824
		}
825
826
		// Standard mechanism for accepting permission changes from extensions
827
		$extended = $this->extendedCan('canAddChildren', $member);
828
		if($extended !== null) {
829
			return $extended;
830
		}
831
832
		// Default permissions
833
		if($member && Permission::checkMember($member, "ADMIN")) {
834
			return true;
835
		}
836
837
		return $this->canEdit($member) && $this->stat('allowed_children') != 'none';
838
	}
839
840
	/**
841
	 * This function should return true if the current user can view this page. It can be overloaded to customise the
842
	 * security model for an application.
843
	 *
844
	 * Denies permission if any of the following conditions is true:
845
	 * - canView() on any extension returns false
846
	 * - "CanViewType" directive is set to "Inherit" and any parent page return false for canView()
847
	 * - "CanViewType" directive is set to "LoggedInUsers" and no user is logged in
848
	 * - "CanViewType" directive is set to "OnlyTheseUsers" and user is not in the given groups
849
	 *
850
	 * @uses DataExtension->canView()
851
	 * @uses ViewerGroups()
852
	 *
853
	 * @param Member|int $member
854
	 * @return bool True if the current user can view this page
855
	 */
856
	public function canView($member = null) {
857 View Code Duplication
		if(!$member || !($member instanceof Member) || is_numeric($member)) {
0 ignored issues
show
Bug introduced by
The class SilverStripe\Security\Member does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
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...
858
			$member = Member::currentUserID();
859
		}
860
861
		// Standard mechanism for accepting permission changes from extensions
862
		$extended = $this->extendedCan('canView', $member);
863
		if($extended !== null) {
864
			return $extended;
865
		}
866
867
		// admin override
868
		if($member && Permission::checkMember($member, array("ADMIN", "SITETREE_VIEW_ALL"))) {
869
			return true;
870
		}
871
872
		// Orphaned pages (in the current stage) are unavailable, except for admins via the CMS
873
		if($this->isOrphaned()) {
874
			return false;
875
		}
876
877
		// check for empty spec
878
		if(!$this->CanViewType || $this->CanViewType == 'Anyone') {
879
			return true;
880
		}
881
882
		// check for inherit
883
		if($this->CanViewType == 'Inherit') {
884
			if($this->ParentID) return $this->Parent()->canView($member);
885
			else return $this->getSiteConfig()->canViewPages($member);
886
		}
887
888
		// check for any logged-in users
889
		if($this->CanViewType == 'LoggedInUsers' && $member) {
890
			return true;
891
		}
892
893
		// check for specific groups
894
		if($member && is_numeric($member)) {
895
			$member = DataObject::get_by_id('SilverStripe\\Security\\Member', $member);
896
		}
897
		if(
898
			$this->CanViewType == 'OnlyTheseUsers'
899
			&& $member
900
			&& $member->inGroups($this->ViewerGroups())
901
		) return true;
902
903
		return false;
904
	}
905
906
	/**
907
	 * This function should return true if the current user can delete this page. It can be overloaded to customise the
908
	 * security model for an application.
909
	 *
910
	 * Denies permission if any of the following conditions is true:
911
	 * - canDelete() returns false on any extension
912
	 * - canEdit() returns false
913
	 * - any descendant page returns false for canDelete()
914
	 *
915
	 * @uses canDelete()
916
	 * @uses SiteTreeExtension->canDelete()
917
	 * @uses canEdit()
918
	 *
919
	 * @param Member $member
920
	 * @return bool True if the current user can delete this page
921
	 */
922
	public function canDelete($member = null) {
923 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...
Bug introduced by
The class SilverStripe\Security\Member does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
924
		else if(is_numeric($member)) $memberID = $member;
925
		else $memberID = Member::currentUserID();
926
927
		// Standard mechanism for accepting permission changes from extensions
928
		$extended = $this->extendedCan('canDelete', $memberID);
929
		if($extended !== null) {
930
			return $extended;
931
		}
932
933
		// Default permission check
934
		if($memberID && Permission::checkMember($memberID, array("ADMIN", "SITETREE_EDIT_ALL"))) {
935
			return true;
936
		}
937
938
		// Regular canEdit logic is handled by can_edit_multiple
939
		$results = self::can_delete_multiple(array($this->ID), $memberID);
940
941
		// If this page no longer exists in stage/live results won't contain the page.
942
		// Fail-over to false
943
		return isset($results[$this->ID]) ? $results[$this->ID] : false;
944
	}
945
946
	/**
947
	 * This function should return true if the current user can create new pages of this class, regardless of class. It
948
	 * can be overloaded to customise the security model for an application.
949
	 *
950
	 * By default, permission to create at the root level is based on the SiteConfig configuration, and permission to
951
	 * create beneath a parent is based on the ability to edit that parent page.
952
	 *
953
	 * Use {@link canAddChildren()} to control behaviour of creating children under this page.
954
	 *
955
	 * @uses $can_create
956
	 * @uses DataExtension->canCreate()
957
	 *
958
	 * @param Member $member
959
	 * @param array $context Optional array which may contain array('Parent' => $parentObj)
960
	 *                       If a parent page is known, it will be checked for validity.
961
	 *                       If omitted, it will be assumed this is to be created as a top level page.
962
	 * @return bool True if the current user can create pages on this class.
963
	 */
964
	public function canCreate($member = null, $context = array()) {
965 View Code Duplication
		if(!$member || !(is_a($member, 'SilverStripe\\Security\\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...
966
			$member = Member::currentUserID();
967
		}
968
969
		// Check parent (custom canCreate option for SiteTree)
970
		// Block children not allowed for this parent type
971
		$parent = isset($context['Parent']) ? $context['Parent'] : null;
972
		if($parent && !in_array(get_class($this), $parent->allowedChildren())) {
973
			return false;
974
		}
975
976
		// Standard mechanism for accepting permission changes from extensions
977
		$extended = $this->extendedCan(__FUNCTION__, $member, $context);
978
		if($extended !== null) {
979
			return $extended;
980
		}
981
982
		// Check permission
983
		if($member && Permission::checkMember($member, "ADMIN")) {
984
			return true;
985
		}
986
987
		// Fall over to inherited permissions
988
		if($parent) {
989
			return $parent->canAddChildren($member);
990
		} else {
991
			// This doesn't necessarily mean we are creating a root page, but that
992
			// we don't know if there is a parent, so default to this permission
993
			return SiteConfig::current_site_config()->canCreateTopLevel($member);
994
		}
995
	}
996
997
	/**
998
	 * This function should return true if the current user can edit this page. It can be overloaded to customise the
999
	 * security model for an application.
1000
	 *
1001
	 * Denies permission if any of the following conditions is true:
1002
	 * - canEdit() on any extension returns false
1003
	 * - canView() return false
1004
	 * - "CanEditType" directive is set to "Inherit" and any parent page return false for canEdit()
1005
	 * - "CanEditType" directive is set to "LoggedInUsers" and no user is logged in or doesn't have the
1006
	 *   CMS_Access_CMSMAIN permission code
1007
	 * - "CanEditType" directive is set to "OnlyTheseUsers" and user is not in the given groups
1008
	 *
1009
	 * @uses canView()
1010
	 * @uses EditorGroups()
1011
	 * @uses DataExtension->canEdit()
1012
	 *
1013
	 * @param Member $member Set to false if you want to explicitly test permissions without a valid user (useful for
1014
	 *                       unit tests)
1015
	 * @return bool True if the current user can edit this page
1016
	 */
1017
	public function canEdit($member = null) {
1018 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...
Bug introduced by
The class SilverStripe\Security\Member does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
1019
		else if(is_numeric($member)) $memberID = $member;
1020
		else $memberID = Member::currentUserID();
1021
1022
		// Standard mechanism for accepting permission changes from extensions
1023
		$extended = $this->extendedCan('canEdit', $memberID);
1024
		if($extended !== null) {
1025
			return $extended;
1026
		}
1027
1028
		// Default permissions
1029
		if($memberID && Permission::checkMember($memberID, array("ADMIN", "SITETREE_EDIT_ALL"))) {
1030
			return true;
1031
		}
1032
1033
		if($this->ID) {
1034
			// Regular canEdit logic is handled by can_edit_multiple
1035
			$results = self::can_edit_multiple(array($this->ID), $memberID);
1036
1037
			// If this page no longer exists in stage/live results won't contain the page.
1038
			// Fail-over to false
1039
			return isset($results[$this->ID]) ? $results[$this->ID] : false;
1040
1041
		// Default for unsaved pages
1042
		} else {
1043
			return $this->getSiteConfig()->canEditPages($member);
1044
		}
1045
	}
1046
1047
	/**
1048
	 * Stub method to get the site config, unless the current class can provide an alternate.
1049
	 *
1050
	 * @return SiteConfig
1051
	 */
1052
	public function getSiteConfig() {
1053
		$configs = $this->invokeWithExtensions('alternateSiteConfig');
1054
		foreach(array_filter($configs) as $config) {
1055
			return $config;
1056
		}
1057
1058
		return SiteConfig::current_site_config();
1059
	}
1060
1061
	/**
1062
	 * Pre-populate the cache of canEdit, canView, canDelete, canPublish permissions. This method will use the static
1063
	 * can_(perm)_multiple method for efficiency.
1064
	 *
1065
	 * @param string          $permission    The permission: edit, view, publish, approve, etc.
1066
	 * @param array           $ids           An array of page IDs
1067
	 * @param callable|string $batchCallback The function/static method to call to calculate permissions.  Defaults
1068
	 *                                       to 'SiteTree::can_(permission)_multiple'
1069
	 */
1070
	static public function prepopulate_permission_cache($permission = 'CanEditType', $ids, $batchCallback = null) {
1071
		if(!$batchCallback) $batchCallback = "SiteTree::can_{$permission}_multiple";
1072
1073
		if(is_callable($batchCallback)) {
1074
			call_user_func($batchCallback, $ids, Member::currentUserID(), false);
1075
		} else {
1076
			user_error("SiteTree::prepopulate_permission_cache can't calculate '$permission' "
1077
				. "with callback '$batchCallback'", E_USER_WARNING);
1078
		}
1079
	}
1080
1081
	/**
1082
	 * This method is NOT a full replacement for the individual can*() methods, e.g. {@link canEdit()}. Rather than
1083
	 * checking (potentially slow) PHP logic, it relies on the database group associations, e.g. the "CanEditType" field
1084
	 * plus the "SiteTree_EditorGroups" many-many table. By batch checking multiple records, we can combine the queries
1085
	 * efficiently.
1086
	 *
1087
	 * Caches based on $typeField data. To invalidate the cache, use {@link SiteTree::reset()} or set the $useCached
1088
	 * property to FALSE.
1089
	 *
1090
	 * @param array  $ids              Of {@link SiteTree} IDs
1091
	 * @param int    $memberID         Member ID
1092
	 * @param string $typeField        A property on the data record, e.g. "CanEditType".
1093
	 * @param string $groupJoinTable   A many-many table name on this record, e.g. "SiteTree_EditorGroups"
1094
	 * @param string $siteConfigMethod Method to call on {@link SiteConfig} for toplevel items, e.g. "canEdit"
1095
	 * @param string $globalPermission If the member doesn't have this permission code, don't bother iterating deeper
1096
	 * @param bool   $useCached
1097
	 * @return array An map of {@link SiteTree} ID keys to boolean values
1098
	 */
1099
	public static function batch_permission_check($ids, $memberID, $typeField, $groupJoinTable, $siteConfigMethod,
1100
												  $globalPermission = null, $useCached = true) {
1101
		if($globalPermission === NULL) $globalPermission = array('CMS_ACCESS_LeftAndMain', 'CMS_ACCESS_CMSMain');
1102
1103
		// Sanitise the IDs
1104
		$ids = array_filter($ids, 'is_numeric');
1105
1106
		// This is the name used on the permission cache
1107
		// converts something like 'CanEditType' to 'edit'.
1108
		$cacheKey = strtolower(substr($typeField, 3, -4)) . "-$memberID";
1109
1110
		// Default result: nothing editable
1111
		$result = array_fill_keys($ids, false);
1112
		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...
1113
1114
			// Look in the cache for values
1115
			if($useCached && isset(self::$cache_permissions[$cacheKey])) {
1116
				$cachedValues = array_intersect_key(self::$cache_permissions[$cacheKey], $result);
1117
1118
				// If we can't find everything in the cache, then look up the remainder separately
1119
				$uncachedValues = array_diff_key($result, self::$cache_permissions[$cacheKey]);
1120
				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...
1121
					$cachedValues = self::batch_permission_check(array_keys($uncachedValues), $memberID, $typeField, $groupJoinTable, $siteConfigMethod, $globalPermission, false) + $cachedValues;
1122
				}
1123
				return $cachedValues;
1124
			}
1125
1126
			// If a member doesn't have a certain permission then they can't edit anything
1127
			if(!$memberID || ($globalPermission && !Permission::checkMember($memberID, $globalPermission))) {
1128
				return $result;
1129
			}
1130
1131
			// Placeholder for parameterised ID list
1132
			$idPlaceholders = DB::placeholders($ids);
1133
1134
			// If page can't be viewed, don't grant edit permissions to do - implement can_view_multiple(), so this can
1135
			// be enabled
1136
			//$ids = array_keys(array_filter(self::can_view_multiple($ids, $memberID)));
1137
1138
			// Get the groups that the given member belongs to
1139
			$groupIDs = DataObject::get_by_id('SilverStripe\\Security\\Member', $memberID)->Groups()->column("ID");
1140
			$SQL_groupList = implode(", ", $groupIDs);
1141
			if (!$SQL_groupList) $SQL_groupList = '0';
1142
1143
			$combinedStageResult = array();
1144
1145
			foreach(array(Versioned::DRAFT, Versioned::LIVE) as $stage) {
1146
				// Start by filling the array with the pages that actually exist
1147
				$table = ($stage=='Stage') ? "SiteTree" : "SiteTree_$stage";
1148
1149
				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...
1150
					$idQuery = "SELECT \"ID\" FROM \"$table\" WHERE \"ID\" IN ($idPlaceholders)";
1151
					$stageIds = DB::prepared_query($idQuery, $ids)->column();
1152
				} else {
1153
					$stageIds = array();
1154
				}
1155
				$result = array_fill_keys($stageIds, false);
1156
1157
				// Get the uninherited permissions
1158
				$uninheritedPermissions = Versioned::get_by_stage("SiteTree", $stage)
1159
					->where(array(
1160
						"(\"$typeField\" = 'LoggedInUsers' OR
1161
						(\"$typeField\" = 'OnlyTheseUsers' AND \"$groupJoinTable\".\"SiteTreeID\" IS NOT NULL))
1162
						AND \"SiteTree\".\"ID\" IN ($idPlaceholders)"
1163
						=> $ids
1164
					))
1165
					->leftJoin($groupJoinTable, "\"$groupJoinTable\".\"SiteTreeID\" = \"SiteTree\".\"ID\" AND \"$groupJoinTable\".\"GroupID\" IN ($SQL_groupList)");
1166
1167
				if($uninheritedPermissions) {
1168
					// Set all the relevant items in $result to true
1169
					$result = array_fill_keys($uninheritedPermissions->column('ID'), true) + $result;
1170
				}
1171
1172
				// Get permissions that are inherited
1173
				$potentiallyInherited = Versioned::get_by_stage(
1174
					"SiteTree",
1175
					$stage,
1176
					array("\"$typeField\" = 'Inherit' AND \"SiteTree\".\"ID\" IN ($idPlaceholders)" => $ids)
1177
				);
1178
1179
				if($potentiallyInherited) {
1180
					// Group $potentiallyInherited by ParentID; we'll look at the permission of all those parents and
1181
					// then see which ones the user has permission on
1182
					$groupedByParent = array();
1183
					foreach($potentiallyInherited as $item) {
1184
						/** @var SiteTree $item */
1185
						if($item->ParentID) {
1186
							if(!isset($groupedByParent[$item->ParentID])) $groupedByParent[$item->ParentID] = array();
1187
							$groupedByParent[$item->ParentID][] = $item->ID;
1188
						} else {
1189
							// Might return different site config based on record context, e.g. when subsites module
1190
							// is used
1191
							$siteConfig = $item->getSiteConfig();
1192
							$result[$item->ID] = $siteConfig->{$siteConfigMethod}($memberID);
1193
						}
1194
					}
1195
1196
					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...
1197
						$actuallyInherited = self::batch_permission_check(array_keys($groupedByParent), $memberID, $typeField, $groupJoinTable, $siteConfigMethod);
1198
						if($actuallyInherited) {
1199
							$parentIDs = array_keys(array_filter($actuallyInherited));
1200
							foreach($parentIDs as $parentID) {
1201
								// Set all the relevant items in $result to true
1202
								$result = array_fill_keys($groupedByParent[$parentID], true) + $result;
1203
							}
1204
						}
1205
					}
1206
				}
1207
1208
				$combinedStageResult = $combinedStageResult + $result;
1209
1210
			}
1211
		}
1212
1213
		if(isset($combinedStageResult)) {
1214
			// Cache the results
1215
 			if(empty(self::$cache_permissions[$cacheKey])) self::$cache_permissions[$cacheKey] = array();
1216
 			self::$cache_permissions[$cacheKey] = $combinedStageResult + self::$cache_permissions[$cacheKey];
1217
			return $combinedStageResult;
1218
		} else {
1219
			return array();
1220
		}
1221
	}
1222
1223
	/**
1224
	 * Get the 'can edit' information for a number of SiteTree pages.
1225
	 *
1226
	 * @param array $ids       An array of IDs of the SiteTree pages to look up
1227
	 * @param int   $memberID  ID of member
1228
	 * @param bool  $useCached Return values from the permission cache if they exist
1229
	 * @return array A map where the IDs are keys and the values are booleans stating whether the given page can be
1230
	 *                         edited
1231
	 */
1232
	static public function can_edit_multiple($ids, $memberID, $useCached = true) {
1233
		return self::batch_permission_check($ids, $memberID, 'CanEditType', 'SiteTree_EditorGroups', 'canEditPages', null, $useCached);
1234
	}
1235
1236
	/**
1237
	 * Get the 'can edit' information for a number of SiteTree pages.
1238
	 *
1239
	 * @param array $ids       An array of IDs of the SiteTree pages to look up
1240
	 * @param int   $memberID  ID of member
1241
	 * @param bool  $useCached Return values from the permission cache if they exist
1242
	 * @return array
1243
	 */
1244
	static public function can_delete_multiple($ids, $memberID, $useCached = true) {
1245
		$deletable = array();
1246
		$result = array_fill_keys($ids, false);
1247
		$cacheKey = "delete-$memberID";
1248
1249
		// Look in the cache for values
1250
		if($useCached && isset(self::$cache_permissions[$cacheKey])) {
1251
			$cachedValues = array_intersect_key(self::$cache_permissions[$cacheKey], $result);
1252
1253
			// If we can't find everything in the cache, then look up the remainder separately
1254
			$uncachedValues = array_diff_key($result, self::$cache_permissions[$cacheKey]);
1255
			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...
1256
				$cachedValues = self::can_delete_multiple(array_keys($uncachedValues), $memberID, false)
1257
					+ $cachedValues;
1258
			}
1259
			return $cachedValues;
1260
		}
1261
1262
		// You can only delete pages that you can edit
1263
		$editableIDs = array_keys(array_filter(self::can_edit_multiple($ids, $memberID)));
1264
		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...
1265
1266
			// You can only delete pages whose children you can delete
1267
			$editablePlaceholders = DB::placeholders($editableIDs);
1268
			$childRecords = SiteTree::get()->where(array(
1269
				"\"SiteTree\".\"ParentID\" IN ($editablePlaceholders)" => $editableIDs
1270
			));
1271
			if($childRecords) {
1272
				$children = $childRecords->map("ID", "ParentID");
1273
1274
				// Find out the children that can be deleted
1275
				$deletableChildren = self::can_delete_multiple($children->keys(), $memberID);
1276
1277
				// Get a list of all the parents that have no undeletable children
1278
				$deletableParents = array_fill_keys($editableIDs, true);
1279
				foreach($deletableChildren as $id => $canDelete) {
1280
					if(!$canDelete) unset($deletableParents[$children[$id]]);
1281
				}
1282
1283
				// Use that to filter the list of deletable parents that have children
1284
				$deletableParents = array_keys($deletableParents);
1285
1286
				// Also get the $ids that don't have children
1287
				$parents = array_unique($children->values());
1288
				$deletableLeafNodes = array_diff($editableIDs, $parents);
1289
1290
				// Combine the two
1291
				$deletable = array_merge($deletableParents, $deletableLeafNodes);
1292
1293
			} else {
1294
				$deletable = $editableIDs;
1295
			}
1296
		}
1297
1298
		// Convert the array of deletable IDs into a map of the original IDs with true/false as the value
1299
		return array_fill_keys($deletable, true) + array_fill_keys($ids, false);
1300
	}
1301
1302
	/**
1303
	 * Collate selected descendants of this page.
1304
	 *
1305
	 * {@link $condition} will be evaluated on each descendant, and if it is succeeds, that item will be added to the
1306
	 * $collator array.
1307
	 *
1308
	 * @param string $condition The PHP condition to be evaluated. The page will be called $item
1309
	 * @param array  $collator  An array, passed by reference, to collect all of the matching descendants.
1310
	 * @return bool
1311
	 */
1312
	public function collateDescendants($condition, &$collator) {
1313
		if($children = $this->Children()) {
1314
			foreach($children as $item) {
1315
1316
				if(eval("return $condition;")) {
1317
					$collator[] = $item;
1318
				}
1319
				/** @var SiteTree $item */
1320
				$item->collateDescendants($condition, $collator);
1321
			}
1322
			return true;
1323
		}
1324
	}
1325
1326
	/**
1327
	 * Return the title, description, keywords and language metatags.
1328
	 *
1329
	 * @todo Move <title> tag in separate getter for easier customization and more obvious usage
1330
	 *
1331
	 * @param bool $includeTitle Show default <title>-tag, set to false for custom templating
1332
	 * @return string The XHTML metatags
1333
	 */
1334
	public function MetaTags($includeTitle = true) {
1335
		$tags = array();
1336
		if($includeTitle && strtolower($includeTitle) != 'false') {
1337
			$tags[] = FormField::create_tag('title', array(), $this->obj('Title')->forTemplate());
1338
		}
1339
1340
		$generator = trim(Config::inst()->get('SiteTree', 'meta_generator'));
1341
		if (!empty($generator)) {
1342
			$tags[] = FormField::create_tag('meta', array(
1343
				'name' => 'generator',
1344
				'content' => $generator,
1345
			));
1346
		}
1347
1348
		$charset = Config::inst()->get('ContentNegotiator', 'encoding');
1349
		$tags[] = FormField::create_tag('meta', array(
1350
			'http-equiv' => 'Content-Type',
1351
			'content' => 'text/html; charset=' . $charset,
1352
		));
1353
		if($this->MetaDescription) {
1354
			$tags[] = FormField::create_tag('meta', array(
1355
				'name' => 'description',
1356
				'content' => $this->MetaDescription,
1357
			));
1358
		}
1359
1360
		if(Permission::check('CMS_ACCESS_CMSMain')
1361
			&& in_array('CMSPreviewable', class_implements($this))
1362
			&& !$this instanceof ErrorPage
1363
			&& $this->ID > 0
1364
		) {
1365
			$tags[] = FormField::create_tag('meta', array(
1366
				'name' => 'x-page-id',
1367
				'content' => $this->obj('ID')->forTemplate(),
1368
			));
1369
			$tags[] = FormField::create_tag('meta', array(
1370
				'name' => 'x-cms-edit-link',
1371
				'content' => $this->obj('CMSEditLink')->forTemplate(),
1372
			));
1373
		}
1374
1375
		$tags = implode("\n", $tags);
1376
		if($this->ExtraMeta) {
1377
			$tags .= $this->obj('ExtraMeta')->forTemplate();
1378
		}
1379
1380
		$this->extend('MetaTags', $tags);
1381
1382
		return $tags;
1383
	}
1384
1385
	/**
1386
	 * Returns the object that contains the content that a user would associate with this page.
1387
	 *
1388
	 * Ordinarily, this is just the page itself, but for example on RedirectorPages or VirtualPages ContentSource() will
1389
	 * return the page that is linked to.
1390
	 *
1391
	 * @return $this
1392
	 */
1393
	public function ContentSource() {
1394
		return $this;
1395
	}
1396
1397
	/**
1398
	 * Add default records to database.
1399
	 *
1400
	 * This function is called whenever the database is built, after the database tables have all been created. Overload
1401
	 * this to add default records when the database is built, but make sure you call parent::requireDefaultRecords().
1402
	 */
1403
	public function requireDefaultRecords() {
1404
		parent::requireDefaultRecords();
1405
1406
		// default pages
1407
		if($this->class == 'SiteTree' && $this->config()->create_default_pages) {
1408
			if(!SiteTree::get_by_link(Config::inst()->get('RootURLController', 'default_homepage_link'))) {
1409
				$homepage = new Page();
1410
				$homepage->Title = _t('SiteTree.DEFAULTHOMETITLE', 'Home');
1411
				$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>');
1412
				$homepage->URLSegment = Config::inst()->get('RootURLController', 'default_homepage_link');
1413
				$homepage->Sort = 1;
1414
				$homepage->write();
1415
				$homepage->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
1416
				$homepage->flushCache();
1417
				DB::alteration_message('Home page created', 'created');
1418
			}
1419
1420
			if(DB::query("SELECT COUNT(*) FROM \"SiteTree\"")->value() == 1) {
1421
				$aboutus = new Page();
1422
				$aboutus->Title = _t('SiteTree.DEFAULTABOUTTITLE', 'About Us');
1423
				$aboutus->Content = _t('SiteTree.DEFAULTABOUTCONTENT', '<p>You can fill this page out with your own content, or delete it and create your own pages.</p>');
1424
				$aboutus->Sort = 2;
1425
				$aboutus->write();
1426
				$aboutus->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
1427
				$aboutus->flushCache();
1428
				DB::alteration_message('About Us page created', 'created');
1429
1430
				$contactus = new Page();
1431
				$contactus->Title = _t('SiteTree.DEFAULTCONTACTTITLE', 'Contact Us');
1432
				$contactus->Content = _t('SiteTree.DEFAULTCONTACTCONTENT', '<p>You can fill this page out with your own content, or delete it and create your own pages.</p>');
1433
				$contactus->Sort = 3;
1434
				$contactus->write();
1435
				$contactus->copyVersionToStage(Versioned::DRAFT, Versioned::LIVE);
1436
				$contactus->flushCache();
1437
				DB::alteration_message('Contact Us page created', 'created');
1438
			}
1439
		}
1440
1441
		// schema migration
1442
		// @todo Move to migration task once infrastructure is implemented
1443
		if($this->class == 'SiteTree') {
1444
			$conn = DB::get_schema();
1445
			// only execute command if fields haven't been renamed to _obsolete_<fieldname> already by the task
1446
			if($conn->hasField('SiteTree' ,'Viewers')) {
1447
				$task = new UpgradeSiteTreePermissionSchemaTask();
1448
				$task->run(new SS_HTTPRequest('GET','/'));
1449
			}
1450
		}
1451
	}
1452
1453
	protected function onBeforeWrite() {
1454
		parent::onBeforeWrite();
1455
1456
		// If Sort hasn't been set, make this page come after it's siblings
1457
		if(!$this->Sort) {
1458
			$parentID = ($this->ParentID) ? $this->ParentID : 0;
1459
			$this->Sort = DB::prepared_query(
1460
				"SELECT MAX(\"Sort\") + 1 FROM \"SiteTree\" WHERE \"ParentID\" = ?",
1461
				array($parentID)
1462
			)->value();
1463
		}
1464
1465
		// If there is no URLSegment set, generate one from Title
1466
		$defaultSegment = $this->generateURLSegment(_t(
1467
			'CMSMain.NEWPAGE',
1468
			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...
1469
		));
1470
		if((!$this->URLSegment || $this->URLSegment == $defaultSegment) && $this->Title) {
1471
			$this->URLSegment = $this->generateURLSegment($this->Title);
1472
		} else if($this->isChanged('URLSegment', 2)) {
1473
			// Do a strict check on change level, to avoid double encoding caused by
1474
			// bogus changes through forceChange()
1475
			$filter = URLSegmentFilter::create();
1476
			$this->URLSegment = $filter->filter($this->URLSegment);
1477
			// If after sanitising there is no URLSegment, give it a reasonable default
1478
			if(!$this->URLSegment) $this->URLSegment = "page-$this->ID";
1479
		}
1480
1481
		// Ensure that this object has a non-conflicting URLSegment value.
1482
		$count = 2;
1483
		while(!$this->validURLSegment()) {
1484
			$this->URLSegment = preg_replace('/-[0-9]+$/', null, $this->URLSegment) . '-' . $count;
1485
			$count++;
1486
		}
1487
1488
		$this->syncLinkTracking();
1489
1490
		// Check to see if we've only altered fields that shouldn't affect versioning
1491
		$fieldsIgnoredByVersioning = array('HasBrokenLink', 'Status', 'HasBrokenFile', 'ToDo', 'VersionID', 'SaveCount');
1492
		$changedFields = array_keys($this->getChangedFields(true, 2));
1493
1494
		// This more rigorous check is inline with the test that write() does to decide whether or not to write to the
1495
		// DB. We use that to avoid cluttering the system with a migrateVersion() call that doesn't get used
1496
		$oneChangedFields = array_keys($this->getChangedFields(true, 1));
1497
1498
		if($oneChangedFields && !array_diff($changedFields, $fieldsIgnoredByVersioning)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $oneChangedFields 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...
1499
			// This will have the affect of preserving the versioning
1500
			$this->migrateVersion($this->Version);
1501
		}
1502
	}
1503
1504
	/**
1505
	 * Trigger synchronisation of link tracking
1506
	 *
1507
	 * {@see SiteTreeLinkTracking::augmentSyncLinkTracking}
1508
	 */
1509
	public function syncLinkTracking() {
1510
		$this->extend('augmentSyncLinkTracking');
1511
	}
1512
1513
	public function onBeforeDelete() {
1514
		parent::onBeforeDelete();
1515
1516
		// If deleting this page, delete all its children.
1517
		if(SiteTree::config()->enforce_strict_hierarchy && $children = $this->AllChildren()) {
1518
			foreach($children as $child) {
1519
				$child->delete();
1520
			}
1521
		}
1522
	}
1523
1524
	public function onAfterDelete() {
1525
		// Need to flush cache to avoid outdated versionnumber references
1526
		$this->flushCache();
1527
1528
		// Need to mark pages depending to this one as broken
1529
		$dependentPages = $this->DependentPages();
1530
		if($dependentPages) foreach($dependentPages as $page) {
1531
			// $page->write() calls syncLinkTracking, which does all the hard work for us.
1532
			$page->write();
1533
		}
1534
1535
		parent::onAfterDelete();
1536
	}
1537
1538
	public function flushCache($persistent = true) {
1539
		parent::flushCache($persistent);
1540
		$this->_cache_statusFlags = null;
1541
	}
1542
1543
	public function validate() {
1544
		$result = parent::validate();
1545
1546
		// Allowed children validation
1547
		$parent = $this->getParent();
1548
		if($parent && $parent->exists()) {
1549
			// No need to check for subclasses or instanceof, as allowedChildren() already
1550
			// deconstructs any inheritance trees already.
1551
			$allowed = $parent->allowedChildren();
1552
			$subject = ($this instanceof VirtualPage && $this->CopyContentFromID) ? $this->CopyContentFrom() : $this;
1553
			if(!in_array($subject->ClassName, $allowed)) {
1554
1555
				$result->error(
1556
					_t(
1557
						'SiteTree.PageTypeNotAllowed',
1558
						'Page type "{type}" not allowed as child of this parent page',
1559
						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...
1560
					),
1561
					'ALLOWED_CHILDREN'
1562
				);
1563
			}
1564
		}
1565
1566
		// "Can be root" validation
1567
		if(!$this->stat('can_be_root') && !$this->ParentID) {
1568
			$result->error(
1569
				_t(
1570
					'SiteTree.PageTypNotAllowedOnRoot',
1571
					'Page type "{type}" is not allowed on the root level',
1572
					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...
1573
				),
1574
				'CAN_BE_ROOT'
1575
			);
1576
		}
1577
1578
		return $result;
1579
	}
1580
1581
	/**
1582
	 * Returns true if this object has a URLSegment value that does not conflict with any other objects. This method
1583
	 * checks for:
1584
	 *  - A page with the same URLSegment that has a conflict
1585
	 *  - Conflicts with actions on the parent page
1586
	 *  - A conflict caused by a root page having the same URLSegment as a class name
1587
	 *
1588
	 * @return bool
1589
	 */
1590
	public function validURLSegment() {
1591
		if(self::config()->nested_urls && $parent = $this->Parent()) {
1592
			if($controller = ModelAsController::controller_for($parent)) {
1593
				if($controller instanceof Controller && $controller->hasAction($this->URLSegment)) return false;
1594
			}
1595
		}
1596
1597
		if(!self::config()->nested_urls || !$this->ParentID) {
1598
			if(class_exists($this->URLSegment) && is_subclass_of($this->URLSegment, 'RequestHandler')) return false;
1599
		}
1600
1601
		// Filters by url, id, and parent
1602
		$filter = array('"SiteTree"."URLSegment"' => $this->URLSegment);
1603
		if($this->ID) {
1604
			$filter['"SiteTree"."ID" <> ?'] = $this->ID;
1605
		}
1606
		if(self::config()->nested_urls) {
1607
			$filter['"SiteTree"."ParentID"'] = $this->ParentID ? $this->ParentID : 0;
1608
		}
1609
1610
		$votes = array_filter(
1611
			(array)$this->extend('augmentValidURLSegment'),
1612
			function($v) {return !is_null($v);}
1613
		);
1614
		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...
1615
			return min($votes);
1616
		}
1617
1618
		// Check existence
1619
		$existingPage = DataObject::get_one('SiteTree', $filter);
1620
		if ($existingPage) return false;
1621
1622
		return !($existingPage);
1623
		}
1624
1625
	/**
1626
	 * Generate a URL segment based on the title provided.
1627
	 *
1628
	 * If {@link Extension}s wish to alter URL segment generation, they can do so by defining
1629
	 * updateURLSegment(&$url, $title).  $url will be passed by reference and should be modified. $title will contain
1630
	 * the title that was originally used as the source of this generated URL. This lets extensions either start from
1631
	 * scratch, or incrementally modify the generated URL.
1632
	 *
1633
	 * @param string $title Page title
1634
	 * @return string Generated url segment
1635
	 */
1636
	public function generateURLSegment($title){
1637
		$filter = URLSegmentFilter::create();
1638
		$t = $filter->filter($title);
1639
1640
		// Fallback to generic page name if path is empty (= no valid, convertable characters)
1641
		if(!$t || $t == '-' || $t == '-1') $t = "page-$this->ID";
1642
1643
		// Hook for extensions
1644
		$this->extend('updateURLSegment', $t, $title);
1645
1646
		return $t;
1647
	}
1648
1649
	/**
1650
	 * Gets the URL segment for the latest draft version of this page.
1651
	 *
1652
	 * @return string
1653
	 */
1654
	public function getStageURLSegment() {
1655
		$stageRecord = Versioned::get_one_by_stage('SiteTree', Versioned::DRAFT, array(
1656
			'"SiteTree"."ID"' => $this->ID
1657
		));
1658
		return ($stageRecord) ? $stageRecord->URLSegment : null;
1659
	}
1660
1661
	/**
1662
	 * Gets the URL segment for the currently published version of this page.
1663
	 *
1664
	 * @return string
1665
	 */
1666
	public function getLiveURLSegment() {
1667
		$liveRecord = Versioned::get_one_by_stage('SiteTree', Versioned::LIVE, array(
1668
			'"SiteTree"."ID"' => $this->ID
1669
		));
1670
		return ($liveRecord) ? $liveRecord->URLSegment : null;
1671
	}
1672
1673
	/**
1674
	 * Returns the pages that depend on this page. This includes virtual pages, pages that link to it, etc.
1675
	 *
1676
	 * @param bool $includeVirtuals Set to false to exlcude virtual pages.
1677
	 * @return ArrayList
1678
	 */
1679
	public function DependentPages($includeVirtuals = true) {
1680
		if(class_exists('Subsite')) {
1681
			$origDisableSubsiteFilter = Subsite::$disable_subsite_filter;
1682
			Subsite::disable_subsite_filter(true);
1683
		}
1684
1685
		// Content links
1686
		$items = new ArrayList();
1687
1688
		// We merge all into a regular SS_List, because DataList doesn't support merge
1689
		if($contentLinks = $this->BackLinkTracking()) {
1690
			$linkList = new ArrayList();
1691
			foreach($contentLinks as $item) {
1692
				$item->DependentLinkType = 'Content link';
1693
				$linkList->push($item);
1694
			}
1695
			$items->merge($linkList);
1696
		}
1697
1698
		// Virtual pages
1699
		if($includeVirtuals) {
1700
			$virtuals = $this->VirtualPages();
1701
			if($virtuals) {
1702
				$virtualList = new ArrayList();
1703
				foreach($virtuals as $item) {
1704
					$item->DependentLinkType = 'Virtual page';
1705
					$virtualList->push($item);
1706
				}
1707
				$items->merge($virtualList);
1708
			}
1709
		}
1710
1711
		// Redirector pages
1712
		$redirectors = RedirectorPage::get()->where(array(
1713
			'"RedirectorPage"."RedirectionType"' => 'Internal',
1714
			'"RedirectorPage"."LinkToID"' => $this->ID
1715
		));
1716
		if($redirectors) {
1717
			$redirectorList = new ArrayList();
1718
			foreach($redirectors as $item) {
1719
				$item->DependentLinkType = 'Redirector page';
1720
				$redirectorList->push($item);
1721
			}
1722
			$items->merge($redirectorList);
1723
		}
1724
1725
		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...
1726
1727
		return $items;
1728
	}
1729
1730
	/**
1731
	 * Return all virtual pages that link to this page.
1732
	 *
1733
	 * @return DataList
1734
	 */
1735
	public function VirtualPages() {
1736
		$pages = parent::VirtualPages();
1737
1738
		// Disable subsite filter for these pages
1739
		if($pages instanceof DataList) {
0 ignored issues
show
Bug introduced by
The class SilverStripe\ORM\DataList does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
1740
			return $pages->setDataQueryParam('Subsite.filter', false);
1741
		} else {
1742
			return $pages;
1743
		}
1744
	}
1745
1746
	/**
1747
	 * Returns a FieldList with which to create the main editing form.
1748
	 *
1749
	 * You can override this in your child classes to add extra fields - first get the parent fields using
1750
	 * parent::getCMSFields(), then use addFieldToTab() on the FieldList.
1751
	 *
1752
	 * See {@link getSettingsFields()} for a different set of fields concerned with configuration aspects on the record,
1753
	 * e.g. access control.
1754
	 *
1755
	 * @return FieldList The fields to be displayed in the CMS
1756
	 */
1757
	public function getCMSFields() {
1758
		require_once("forms/Form.php");
1759
		// Status / message
1760
		// Create a status message for multiple parents
1761
		if($this->ID && is_numeric($this->ID)) {
1762
			$linkedPages = $this->VirtualPages();
1763
1764
			$parentPageLinks = array();
1765
1766
			if($linkedPages->Count() > 0) {
1767
				foreach($linkedPages as $linkedPage) {
1768
					$parentPage = $linkedPage->Parent;
1769
					if($parentPage) {
1770
						if($parentPage->ID) {
1771
							$parentPageLinks[] = "<a class=\"cmsEditlink\" href=\"admin/pages/edit/show/$linkedPage->ID\">{$parentPage->Title}</a>";
1772
						} else {
1773
							$parentPageLinks[] = "<a class=\"cmsEditlink\" href=\"admin/pages/edit/show/$linkedPage->ID\">" .
1774
								_t('SiteTree.TOPLEVEL', 'Site Content (Top Level)') .
1775
								"</a>";
1776
						}
1777
					}
1778
				}
1779
1780
				$lastParent = array_pop($parentPageLinks);
1781
				$parentList = "'$lastParent'";
1782
1783
				if(count($parentPageLinks) > 0) {
1784
					$parentList = "'" . implode("', '", $parentPageLinks) . "' and "
1785
						. $parentList;
1786
				}
1787
1788
				$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...
1789
					'SiteTree.APPEARSVIRTUALPAGES',
1790
					"This content also appears on the virtual pages in the {title} sections.",
1791
					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...
1792
				);
1793
			}
1794
		}
1795
1796
		if($this->HasBrokenLink || $this->HasBrokenFile) {
1797
			$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...
1798
		}
1799
1800
		$dependentNote = '';
1801
		$dependentTable = new LiteralField('DependentNote', '<p></p>');
1802
1803
		// Create a table for showing pages linked to this one
1804
		$dependentPages = $this->DependentPages();
1805
		$dependentPagesCount = $dependentPages->Count();
1806
		if($dependentPagesCount) {
1807
			$dependentColumns = array(
1808
				'Title' => $this->fieldLabel('Title'),
1809
				'AbsoluteLink' => _t('SiteTree.DependtPageColumnURL', 'URL'),
1810
				'DependentLinkType' => _t('SiteTree.DependtPageColumnLinkType', 'Link type'),
1811
			);
1812
			if(class_exists('Subsite')) $dependentColumns['Subsite.Title'] = singleton('Subsite')->i18n_singular_name();
1813
1814
			$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>');
1815
			$dependentTable = GridField::create(
1816
				'DependentPages',
1817
				false,
1818
				$dependentPages
1819
			);
1820
			$dependentTable->getConfig()->getComponentByType('GridFieldDataColumns')
1821
				->setDisplayFields($dependentColumns)
1822
				->setFieldFormatting(array(
1823
					'Title' => function($value, &$item) {
1824
						return sprintf(
1825
							'<a href="admin/pages/edit/show/%d">%s</a>',
1826
							(int)$item->ID,
1827
							Convert::raw2xml($item->Title)
1828
						);
1829
					},
1830
					'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...
1831
						return sprintf(
1832
							'<a href="%s" target="_blank">%s</a>',
1833
							Convert::raw2xml($value),
1834
							Convert::raw2xml($value)
1835
						);
1836
					}
1837
				));
1838
		}
1839
1840
		$baseLink = Controller::join_links (
1841
			Director::absoluteBaseURL(),
1842
			(self::config()->nested_urls && $this->ParentID ? $this->Parent()->RelativeLink(true) : null)
1843
		);
1844
1845
		$urlsegment = SiteTreeURLSegmentField::create("URLSegment", $this->fieldLabel('URLSegment'))
1846
			->setURLPrefix($baseLink)
1847
			->setDefaultURL($this->generateURLSegment(_t(
1848
				'CMSMain.NEWPAGE',
1849
				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...
1850
			)));
1851
		$helpText = (self::config()->nested_urls && count($this->Children())) ? $this->fieldLabel('LinkChangeNote') : '';
1852
		if(!Config::inst()->get('URLSegmentFilter', 'default_allow_multibyte')) {
1853
			$helpText .= $helpText ? '<br />' : '';
1854
			$helpText .= _t('SiteTreeURLSegmentField.HelpChars', ' Special characters are automatically converted or removed.');
1855
		}
1856
		$urlsegment->setHelpText($helpText);
1857
1858
		$fields = new FieldList(
1859
			$rootTab = new TabSet("Root",
1860
				$tabMain = new Tab('Main',
1861
					new TextField("Title", $this->fieldLabel('Title')),
1862
					$urlsegment,
1863
					new TextField("MenuTitle", $this->fieldLabel('MenuTitle')),
1864
					$htmlField = new HTMLEditorField("Content", _t('SiteTree.HTMLEDITORTITLE', "Content", 'HTML editor title')),
1865
					ToggleCompositeField::create('Metadata', _t('SiteTree.MetadataToggle', 'Metadata'),
1866
						array(
1867
							$metaFieldDesc = new TextareaField("MetaDescription", $this->fieldLabel('MetaDescription')),
1868
							$metaFieldExtra = new TextareaField("ExtraMeta",$this->fieldLabel('ExtraMeta'))
1869
						)
1870
					)->setHeadingLevel(4)
1871
				),
1872
				$tabDependent = new Tab('Dependent',
1873
					$dependentNote,
1874
					$dependentTable
1875
				)
1876
			)
1877
		);
1878
		$htmlField->addExtraClass('stacked');
1879
1880
		// Help text for MetaData on page content editor
1881
		$metaFieldDesc
1882
			->setRightTitle(
1883
				_t(
1884
					'SiteTree.METADESCHELP',
1885
					"Search engines use this content for displaying search results (although it will not influence their ranking)."
1886
				)
1887
			)
1888
			->addExtraClass('help');
1889
		$metaFieldExtra
1890
			->setRightTitle(
1891
				_t(
1892
					'SiteTree.METAEXTRAHELP',
1893
					"HTML tags for additional meta information. For example &lt;meta name=\"customName\" content=\"your custom content here\" /&gt;"
1894
				)
1895
			)
1896
			->addExtraClass('help');
1897
1898
		// Conditional dependent pages tab
1899
		if($dependentPagesCount) $tabDependent->setTitle(_t('SiteTree.TABDEPENDENT', "Dependent pages") . " ($dependentPagesCount)");
1900
		else $fields->removeFieldFromTab('Root', 'Dependent');
1901
1902
		$tabMain->setTitle(_t('SiteTree.TABCONTENT', "Main Content"));
1903
1904
		if($this->ObsoleteClassName) {
1905
			$obsoleteWarning = _t(
1906
				'SiteTree.OBSOLETECLASS',
1907
				"This page is of obsolete type {type}. Saving will reset its type and you may lose data",
1908
				array('type' => $this->ObsoleteClassName)
0 ignored issues
show
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...
1909
			);
1910
1911
			$fields->addFieldToTab(
1912
				"Root.Main",
1913
				new LiteralField("ObsoleteWarningHeader", "<p class=\"message warning\">$obsoleteWarning</p>"),
1914
				"Title"
1915
			);
1916
		}
1917
1918
		if(file_exists(BASE_PATH . '/install.php')) {
1919
			$fields->addFieldToTab("Root.Main", new LiteralField("InstallWarningHeader",
1920
				"<p class=\"message warning\">" . _t("SiteTree.REMOVE_INSTALL_WARNING",
1921
				"Warning: You should remove install.php from this SilverStripe install for security reasons.")
1922
				. "</p>"), "Title");
1923
		}
1924
1925
		// Backwards compat: Rewrite nested "Content" tabs to toplevel
1926
		$fields->setTabPathRewrites(array(
1927
			'/^Root\.Content\.Main$/' => 'Root.Main',
1928
			'/^Root\.Content\.([^.]+)$/' => 'Root.\\1',
1929
		));
1930
1931
		if(self::$runCMSFieldsExtensions) {
1932
			$this->extend('updateCMSFields', $fields);
1933
		}
1934
1935
		return $fields;
1936
	}
1937
1938
1939
	/**
1940
	 * Returns fields related to configuration aspects on this record, e.g. access control. See {@link getCMSFields()}
1941
	 * for content-related fields.
1942
	 *
1943
	 * @return FieldList
1944
	 */
1945
	public function getSettingsFields() {
1946
		$groupsMap = array();
1947
		foreach(Group::get() as $group) {
1948
			// Listboxfield values are escaped, use ASCII char instead of &raquo;
1949
			$groupsMap[$group->ID] = $group->getBreadcrumbs(' > ');
1950
		}
1951
		asort($groupsMap);
1952
1953
		$fields = new FieldList(
1954
			$rootTab = new TabSet("Root",
1955
				$tabBehaviour = new Tab('Settings',
1956
					new DropdownField(
1957
						"ClassName",
1958
						$this->fieldLabel('ClassName'),
1959
						$this->getClassDropdown()
1960
					),
1961
					$parentTypeSelector = new CompositeField(
1962
						new OptionsetField("ParentType", _t("SiteTree.PAGELOCATION", "Page location"), array(
1963
							"root" => _t("SiteTree.PARENTTYPE_ROOT", "Top-level page"),
1964
							"subpage" => _t("SiteTree.PARENTTYPE_SUBPAGE", "Sub-page underneath a parent page"),
1965
						)),
1966
						$parentIDField = new TreeDropdownField("ParentID", $this->fieldLabel('ParentID'), 'SiteTree', 'ID', 'MenuTitle')
1967
					),
1968
					$visibility = new FieldGroup(
1969
						new CheckboxField("ShowInMenus", $this->fieldLabel('ShowInMenus')),
1970
						new CheckboxField("ShowInSearch", $this->fieldLabel('ShowInSearch'))
1971
					),
1972
					$viewersOptionsField = new OptionsetField(
1973
						"CanViewType",
1974
						_t('SiteTree.ACCESSHEADER', "Who can view this page?")
1975
					),
1976
					$viewerGroupsField = ListboxField::create("ViewerGroups", _t('SiteTree.VIEWERGROUPS', "Viewer Groups"))
1977
						->setSource($groupsMap)
1978
						->setAttribute(
1979
							'data-placeholder',
1980
							_t('SiteTree.GroupPlaceholder', 'Click to select group')
1981
						),
1982
					$editorsOptionsField = new OptionsetField(
1983
						"CanEditType",
1984
						_t('SiteTree.EDITHEADER', "Who can edit this page?")
1985
					),
1986
					$editorGroupsField = ListboxField::create("EditorGroups", _t('SiteTree.EDITORGROUPS', "Editor Groups"))
1987
						->setSource($groupsMap)
1988
						->setAttribute(
1989
							'data-placeholder',
1990
							_t('SiteTree.GroupPlaceholder', 'Click to select group')
1991
						)
1992
				)
1993
			)
1994
		);
1995
1996
		$visibility->setTitle($this->fieldLabel('Visibility'));
1997
1998
1999
		// This filter ensures that the ParentID dropdown selection does not show this node,
2000
		// or its descendents, as this causes vanishing bugs
2001
		$parentIDField->setFilterFunction(create_function('$node', "return \$node->ID != {$this->ID};"));
2002
		$parentTypeSelector->addExtraClass('parentTypeSelector');
2003
2004
		$tabBehaviour->setTitle(_t('SiteTree.TABBEHAVIOUR', "Behavior"));
2005
2006
		// Make page location fields read-only if the user doesn't have the appropriate permission
2007
		if(!Permission::check("SITETREE_REORGANISE")) {
2008
			$fields->makeFieldReadonly('ParentType');
2009
			if($this->ParentType == 'root') {
2010
				$fields->removeByName('ParentID');
2011
			} else {
2012
				$fields->makeFieldReadonly('ParentID');
2013
			}
2014
		}
2015
2016
		$viewersOptionsSource = array();
2017
		$viewersOptionsSource["Inherit"] = _t('SiteTree.INHERIT', "Inherit from parent page");
2018
		$viewersOptionsSource["Anyone"] = _t('SiteTree.ACCESSANYONE', "Anyone");
2019
		$viewersOptionsSource["LoggedInUsers"] = _t('SiteTree.ACCESSLOGGEDIN', "Logged-in users");
2020
		$viewersOptionsSource["OnlyTheseUsers"] = _t('SiteTree.ACCESSONLYTHESE', "Only these people (choose from list)");
2021
		$viewersOptionsField->setSource($viewersOptionsSource);
2022
2023
		$editorsOptionsSource = array();
2024
		$editorsOptionsSource["Inherit"] = _t('SiteTree.INHERIT', "Inherit from parent page");
2025
		$editorsOptionsSource["LoggedInUsers"] = _t('SiteTree.EDITANYONE', "Anyone who can log-in to the CMS");
2026
		$editorsOptionsSource["OnlyTheseUsers"] = _t('SiteTree.EDITONLYTHESE', "Only these people (choose from list)");
2027
		$editorsOptionsField->setSource($editorsOptionsSource);
2028
2029
		if(!Permission::check('SITETREE_GRANT_ACCESS')) {
2030
			$fields->makeFieldReadonly($viewersOptionsField);
2031
			if($this->CanViewType == 'OnlyTheseUsers') {
2032
				$fields->makeFieldReadonly($viewerGroupsField);
2033
			} else {
2034
				$fields->removeByName('ViewerGroups');
2035
			}
2036
2037
			$fields->makeFieldReadonly($editorsOptionsField);
2038
			if($this->CanEditType == 'OnlyTheseUsers') {
2039
				$fields->makeFieldReadonly($editorGroupsField);
2040
			} else {
2041
				$fields->removeByName('EditorGroups');
2042
			}
2043
		}
2044
2045
		if(self::$runCMSFieldsExtensions) {
2046
			$this->extend('updateSettingsFields', $fields);
2047
		}
2048
2049
		return $fields;
2050
	}
2051
2052
	/**
2053
	 * @param bool $includerelations A boolean value to indicate if the labels returned should include relation fields
2054
	 * @return array
2055
	 */
2056
	public function fieldLabels($includerelations = true) {
2057
		$cacheKey = $this->class . '_' . $includerelations;
2058
		if(!isset(self::$_cache_field_labels[$cacheKey])) {
2059
			$labels = parent::fieldLabels($includerelations);
2060
			$labels['Title'] = _t('SiteTree.PAGETITLE', "Page name");
2061
			$labels['MenuTitle'] = _t('SiteTree.MENUTITLE', "Navigation label");
2062
			$labels['MetaDescription'] = _t('SiteTree.METADESC', "Meta Description");
2063
			$labels['ExtraMeta'] = _t('SiteTree.METAEXTRA', "Custom Meta Tags");
2064
			$labels['ClassName'] = _t('SiteTree.PAGETYPE', "Page type", 'Classname of a page object');
2065
			$labels['ParentType'] = _t('SiteTree.PARENTTYPE', "Page location");
2066
			$labels['ParentID'] = _t('SiteTree.PARENTID', "Parent page");
2067
			$labels['ShowInMenus'] =_t('SiteTree.SHOWINMENUS', "Show in menus?");
2068
			$labels['ShowInSearch'] = _t('SiteTree.SHOWINSEARCH', "Show in search?");
2069
			$labels['ProvideComments'] = _t('SiteTree.ALLOWCOMMENTS', "Allow comments on this page?");
2070
			$labels['ViewerGroups'] = _t('SiteTree.VIEWERGROUPS', "Viewer Groups");
2071
			$labels['EditorGroups'] = _t('SiteTree.EDITORGROUPS', "Editor Groups");
2072
			$labels['URLSegment'] = _t('SiteTree.URLSegment', 'URL Segment', 'URL for this page');
2073
			$labels['Content'] = _t('SiteTree.Content', 'Content', 'Main HTML Content for a page');
2074
			$labels['CanViewType'] = _t('SiteTree.Viewers', 'Viewers Groups');
2075
			$labels['CanEditType'] = _t('SiteTree.Editors', 'Editors Groups');
2076
			$labels['Comments'] = _t('SiteTree.Comments', 'Comments');
2077
			$labels['Visibility'] = _t('SiteTree.Visibility', 'Visibility');
2078
			$labels['LinkChangeNote'] = _t (
2079
				'SiteTree.LINKCHANGENOTE', 'Changing this page\'s link will also affect the links of all child pages.'
2080
			);
2081
2082
			if($includerelations){
2083
				$labels['Parent'] = _t('SiteTree.has_one_Parent', 'Parent Page', 'The parent page in the site hierarchy');
2084
				$labels['LinkTracking'] = _t('SiteTree.many_many_LinkTracking', 'Link Tracking');
2085
				$labels['ImageTracking'] = _t('SiteTree.many_many_ImageTracking', 'Image Tracking');
2086
				$labels['BackLinkTracking'] = _t('SiteTree.many_many_BackLinkTracking', 'Backlink Tracking');
2087
			}
2088
2089
			self::$_cache_field_labels[$cacheKey] = $labels;
2090
		}
2091
2092
		return self::$_cache_field_labels[$cacheKey];
2093
	}
2094
2095
	/**
2096
	 * Get the actions available in the CMS for this page - eg Save, Publish.
2097
	 *
2098
	 * Frontend scripts and styles know how to handle the following FormFields:
2099
	 * - top-level FormActions appear as standalone buttons
2100
	 * - top-level CompositeField with FormActions within appear as grouped buttons
2101
	 * - TabSet & Tabs appear as a drop ups
2102
	 * - FormActions within the Tab are restyled as links
2103
	 * - major actions can provide alternate states for richer presentation (see ssui.button widget extension)
2104
	 *
2105
	 * @return FieldList The available actions for this page.
2106
	 */
2107
	public function getCMSActions() {
2108
		$existsOnLive = $this->isPublished();
2109
2110
		// Major actions appear as buttons immediately visible as page actions.
2111
		$majorActions = CompositeField::create()->setName('MajorActions')->setTag('fieldset')->addExtraClass('btn-group ss-ui-buttonset noborder');
2112
2113
		// Minor options are hidden behind a drop-up and appear as links (although they are still FormActions).
2114
		$rootTabSet = new TabSet('ActionMenus');
2115
		$moreOptions = new Tab(
2116
			'MoreOptions',
2117
			_t('SiteTree.MoreOptions', 'More options', 'Expands a view for more buttons')
2118
		);
2119
		$rootTabSet->push($moreOptions);
2120
		$rootTabSet->addExtraClass('ss-ui-action-tabset action-menus noborder');
2121
2122
		// Render page information into the "more-options" drop-up, on the top.
2123
		$live = Versioned::get_one_by_stage('SiteTree', Versioned::LIVE, array(
2124
			'"SiteTree"."ID"' => $this->ID
2125
		));
2126
		$moreOptions->push(
2127
			new LiteralField('Information',
2128
				$this->customise(array(
2129
					'Live' => $live,
2130
					'ExistsOnLive' => $existsOnLive
2131
				))->renderWith('SiteTree_Information')
2132
			)
2133
		);
2134
2135
		$moreOptions->push(AddToCampaignHandler_FormAction::create());
2136
2137
		// "readonly"/viewing version that isn't the current version of the record
2138
		$stageOrLiveRecord = Versioned::get_one_by_stage($this->class, Versioned::get_stage(), array(
2139
			'"SiteTree"."ID"' => $this->ID
2140
		));
2141
		if($stageOrLiveRecord && $stageOrLiveRecord->Version != $this->Version) {
2142
			$moreOptions->push(FormAction::create('email', _t('CMSMain.EMAIL', 'Email')));
2143
			$moreOptions->push(FormAction::create('rollback', _t('CMSMain.ROLLBACK', 'Roll back to this version')));
2144
2145
			$actions = new FieldList(array($majorActions, $rootTabSet));
2146
2147
			// getCMSActions() can be extended with updateCMSActions() on a extension
2148
			$this->extend('updateCMSActions', $actions);
2149
2150
			return $actions;
2151
		}
2152
2153
		if($this->isPublished() && $this->canPublish() && !$this->getIsDeletedFromStage() && $this->canUnpublish()) {
2154
			// "unpublish"
2155
			$moreOptions->push(
2156
				FormAction::create('unpublish', _t('SiteTree.BUTTONUNPUBLISH', 'Unpublish'), 'delete')
2157
					->setDescription(_t('SiteTree.BUTTONUNPUBLISHDESC', 'Remove this page from the published site'))
2158
					->addExtraClass('ss-ui-action-destructive')
2159
			);
2160
		}
2161
2162
		if($this->stagesDiffer(Versioned::DRAFT, Versioned::LIVE) && !$this->getIsDeletedFromStage()) {
2163
			if($this->isPublished() && $this->canEdit())	{
2164
				// "rollback"
2165
				$moreOptions->push(
2166
					FormAction::create('rollback', _t('SiteTree.BUTTONCANCELDRAFT', 'Cancel draft changes'), 'delete')
2167
						->setDescription(_t('SiteTree.BUTTONCANCELDRAFTDESC', 'Delete your draft and revert to the currently published page'))
2168
				);
2169
			}
2170
		}
2171
2172
		if($this->canEdit()) {
2173
			if($this->getIsDeletedFromStage()) {
2174
				// The usual major actions are not available, so we provide alternatives here.
2175
				if($existsOnLive) {
2176
					// "restore"
2177
					$majorActions->push(FormAction::create('revert',_t('CMSMain.RESTORE','Restore')));
2178
					if($this->canDelete() && $this->canUnpublish()) {
2179
						// "delete from live"
2180
						$majorActions->push(
2181
							FormAction::create('deletefromlive',_t('CMSMain.DELETEFP','Delete'))
2182
								->addExtraClass('ss-ui-action-destructive')
2183
						);
2184
					}
2185
				} else {
2186
					// Determine if we should force a restore to root (where once it was a subpage)
2187
					$restoreToRoot = $this->isParentArchived();
2188
2189
					// "restore"
2190
					$title = $restoreToRoot
2191
						? _t('CMSMain.RESTORE_TO_ROOT','Restore draft at top level')
2192
						: _t('CMSMain.RESTORE','Restore draft');
2193
					$description = $restoreToRoot
2194
						? _t('CMSMain.RESTORE_TO_ROOT_DESC','Restore the archived version to draft as a top level page')
2195
						: _t('CMSMain.RESTORE_DESC', 'Restore the archived version to draft');
2196
					$majorActions->push(
2197
						FormAction::create('restore', $title)
2198
							->setDescription($description)
2199
							->setAttribute('data-to-root', $restoreToRoot)
2200
							->setAttribute('data-icon', 'decline')
2201
					);
2202
				}
2203
			} else {
2204
					if($this->canDelete()) {
2205
						// delete
2206
						$moreOptions->push(
2207
							FormAction::create('delete',_t('CMSMain.DELETE','Delete draft'))
2208
								->addExtraClass('delete ss-ui-action-destructive')
2209
						);
2210
					}
2211
				if($this->canArchive()) {
2212
					// "archive"
2213
					$moreOptions->push(
2214
						FormAction::create('archive',_t('CMSMain.ARCHIVE','Archive'))
2215
							->setDescription(_t(
2216
								'SiteTree.BUTTONARCHIVEDESC',
2217
								'Unpublish and send to archive'
2218
							))
2219
							->addExtraClass('delete ss-ui-action-destructive')
2220
					);
2221
				}
2222
2223
				// "save", supports an alternate state that is still clickable, but notifies the user that the action is not needed.
2224
				$majorActions->push(
2225
					FormAction::create('save', _t('SiteTree.BUTTONSAVED', 'Saved'))
2226
						->setAttribute('data-icon', 'accept')
2227
						->setAttribute('data-icon-alternate', 'addpage')
2228
						->setAttribute('data-text-alternate', _t('CMSMain.SAVEDRAFT','Save draft'))
2229
				);
2230
			}
2231
		}
2232
2233
		if($this->canPublish() && !$this->getIsDeletedFromStage()) {
2234
			// "publish", as with "save", it supports an alternate state to show when action is needed.
2235
			$majorActions->push(
2236
				$publish = FormAction::create('publish', _t('SiteTree.BUTTONPUBLISHED', 'Published'))
2237
					->setAttribute('data-icon', 'accept')
2238
					->setAttribute('data-icon-alternate', 'disk')
2239
					->setAttribute('data-text-alternate', _t('SiteTree.BUTTONSAVEPUBLISH', 'Save & publish'))
2240
			);
2241
2242
			// Set up the initial state of the button to reflect the state of the underlying SiteTree object.
2243
			if($this->stagesDiffer(Versioned::DRAFT, Versioned::LIVE)) {
2244
				$publish->addExtraClass('ss-ui-alternate');
2245
			}
2246
		}
2247
2248
		$actions = new FieldList(array($majorActions, $rootTabSet));
2249
2250
		// Hook for extensions to add/remove actions.
2251
		$this->extend('updateCMSActions', $actions);
2252
2253
		return $actions;
2254
	}
2255
2256
	public function onAfterPublish() {
2257
		// Force live sort order to match stage sort order
2258
		DB::prepared_query('UPDATE "SiteTree_Live"
2259
			SET "Sort" = (SELECT "SiteTree"."Sort" FROM "SiteTree" WHERE "SiteTree_Live"."ID" = "SiteTree"."ID")
2260
			WHERE EXISTS (SELECT "SiteTree"."Sort" FROM "SiteTree" WHERE "SiteTree_Live"."ID" = "SiteTree"."ID") AND "ParentID" = ?',
2261
			array($this->ParentID)
2262
		);
2263
		}
2264
2265
	/**
2266
	 * Update draft dependant pages
2267
	 */
2268
	public function onAfterRevertToLive() {
2269
		// Use an alias to get the updates made by $this->publish
2270
		/** @var SiteTree $stageSelf */
2271
		$stageSelf = Versioned::get_by_stage('SiteTree', Versioned::DRAFT)->byID($this->ID);
2272
		$stageSelf->writeWithoutVersion();
2273
2274
		// Need to update pages linking to this one as no longer broken
2275
		foreach($stageSelf->DependentPages() as $page) {
2276
			/** @var SiteTree $page */
2277
			$page->writeWithoutVersion();
2278
		}
2279
	}
2280
2281
	/**
2282
	 * Determine if this page references a parent which is archived, and not available in stage
2283
	 *
2284
	 * @return bool True if there is an archived parent
2285
	 */
2286
	protected function isParentArchived() {
2287
		if($parentID = $this->ParentID) {
2288
			$parentPage = Versioned::get_latest_version("SiteTree", $parentID);
2289
			if(!$parentPage || $parentPage->IsDeletedFromStage) {
2290
				return true;
2291
			}
2292
		}
2293
		return false;
2294
	}
2295
2296
	/**
2297
	 * Restore the content in the active copy of this SiteTree page to the stage site.
2298
	 *
2299
	 * @return self
2300
	 */
2301
	public function doRestoreToStage() {
2302
		$this->invokeWithExtensions('onBeforeRestoreToStage', $this);
2303
2304
		// Ensure that the parent page is restored, otherwise restore to root
2305
		if($this->isParentArchived()) {
2306
			$this->ParentID = 0;
2307
		}
2308
2309
		// if no record can be found on draft stage (meaning it has been "deleted from draft" before),
2310
		// create an empty record
2311
		if(!DB::prepared_query("SELECT \"ID\" FROM \"SiteTree\" WHERE \"ID\" = ?", array($this->ID))->value()) {
2312
			$conn = DB::get_conn();
2313
			if(method_exists($conn, 'allowPrimaryKeyEditing')) $conn->allowPrimaryKeyEditing('SiteTree', true);
2314
			DB::prepared_query("INSERT INTO \"SiteTree\" (\"ID\") VALUES (?)", array($this->ID));
2315
			if(method_exists($conn, 'allowPrimaryKeyEditing')) $conn->allowPrimaryKeyEditing('SiteTree', false);
2316
		}
2317
2318
		$oldReadingMode = Versioned::get_reading_mode();
2319
		Versioned::set_stage(Versioned::DRAFT);
2320
		$this->forceChange();
2321
		$this->write();
2322
2323
		$result = DataObject::get_by_id($this->class, $this->ID);
2324
2325
		// Need to update pages linking to this one as no longer broken
2326
		foreach($result->DependentPages(false) as $page) {
2327
			// $page->write() calls syncLinkTracking, which does all the hard work for us.
2328
			$page->write();
2329
		}
2330
2331
		Versioned::set_reading_mode($oldReadingMode);
2332
2333
		$this->invokeWithExtensions('onAfterRestoreToStage', $this);
2334
2335
		return $result;
2336
	}
2337
2338
	/**
2339
	 * Check if this page is new - that is, if it has yet to have been written to the database.
2340
	 *
2341
	 * @return bool
2342
	 */
2343
	public function isNew() {
2344
		/**
2345
		 * This check was a problem for a self-hosted site, and may indicate a bug in the interpreter on their server,
2346
		 * or a bug here. Changing the condition from empty($this->ID) to !$this->ID && !$this->record['ID'] fixed this.
2347
		 */
2348
		if(empty($this->ID)) return true;
2349
2350
		if(is_numeric($this->ID)) return false;
2351
2352
		return stripos($this->ID, 'new') === 0;
2353
	}
2354
2355
	/**
2356
	 * Get the class dropdown used in the CMS to change the class of a page. This returns the list of options in the
2357
	 * dropdown as a Map from class name to singular name. Filters by {@link SiteTree->canCreate()}, as well as
2358
	 * {@link SiteTree::$needs_permission}.
2359
	 *
2360
	 * @return array
2361
	 */
2362
	protected function getClassDropdown() {
2363
		$classes = self::page_type_classes();
2364
		$currentClass = null;
2365
		$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...
2366
2367
		$result = array();
2368
		foreach($classes as $class) {
2369
			$instance = singleton($class);
2370
2371
			// if the current page type is this the same as the class type always show the page type in the list
2372
			if ($this->ClassName != $instance->ClassName) {
2373
				if($instance instanceof HiddenClass) continue;
0 ignored issues
show
Bug introduced by
The class SilverStripe\ORM\HiddenClass does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
2374
				if(!$instance->canCreate(null, array('Parent' => $this->ParentID ? $this->Parent() : null))) continue;
2375
			}
2376
2377
			if($perms = $instance->stat('need_permission')) {
2378
				if(!$this->can($perms)) continue;
2379
			}
2380
2381
			$pageTypeName = $instance->i18n_singular_name();
2382
2383
			$currentClass = $class;
2384
			$result[$class] = $pageTypeName;
2385
2386
			// If we're in translation mode, the link between the translated pagetype title and the actual classname
2387
			// might not be obvious, so we add it in parantheses. Example: class "RedirectorPage" has the title
2388
			// "Weiterleitung" in German, so it shows up as "Weiterleitung (RedirectorPage)"
2389
			if(i18n::get_lang_from_locale(i18n::get_locale()) != 'en') {
2390
				$result[$class] = $result[$class] .  " ({$class})";
2391
			}
2392
		}
2393
2394
		// sort alphabetically, and put current on top
2395
		asort($result);
2396
		if($currentClass) {
2397
			$currentPageTypeName = $result[$currentClass];
2398
			unset($result[$currentClass]);
2399
			$result = array_reverse($result);
2400
			$result[$currentClass] = $currentPageTypeName;
2401
			$result = array_reverse($result);
2402
		}
2403
2404
		return $result;
2405
	}
2406
2407
	/**
2408
	 * Returns an array of the class names of classes that are allowed to be children of this class.
2409
	 *
2410
	 * @return string[]
2411
	 */
2412
	public function allowedChildren() {
2413
		$allowedChildren = array();
2414
		$candidates = $this->stat('allowed_children');
2415
		if($candidates && $candidates != "none" && $candidates != "SiteTree_root") {
2416
			foreach($candidates as $candidate) {
2417
				// If a classname is prefixed by "*", such as "*Page", then only that class is allowed - no subclasses.
2418
				// Otherwise, the class and all its subclasses are allowed.
2419
				if(substr($candidate,0,1) == '*') {
2420
					$allowedChildren[] = substr($candidate,1);
2421
				} else {
2422
					$subclasses = ClassInfo::subclassesFor($candidate);
2423
					foreach($subclasses as $subclass) {
2424
						if($subclass != "SiteTree_root") $allowedChildren[] = $subclass;
2425
					}
2426
				}
2427
			}
2428
		}
2429
2430
		return $allowedChildren;
2431
	}
2432
2433
	/**
2434
	 * Returns the class name of the default class for children of this page.
2435
	 *
2436
	 * @return string
2437
	 */
2438
	public function defaultChild() {
2439
		$default = $this->stat('default_child');
2440
		$allowed = $this->allowedChildren();
2441
		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...
2442
			if(!$default || !in_array($default, $allowed))
2443
				$default = reset($allowed);
2444
			return $default;
2445
		}
2446
	}
2447
2448
	/**
2449
	 * Returns the class name of the default class for the parent of this page.
2450
	 *
2451
	 * @return string
2452
	 */
2453
	public function defaultParent() {
2454
		return $this->stat('default_parent');
2455
	}
2456
2457
	/**
2458
	 * Get the title for use in menus for this page. If the MenuTitle field is set it returns that, else it returns the
2459
	 * Title field.
2460
	 *
2461
	 * @return string
2462
	 */
2463
	public function getMenuTitle(){
2464
		if($value = $this->getField("MenuTitle")) {
2465
			return $value;
2466
		} else {
2467
			return $this->getField("Title");
2468
		}
2469
	}
2470
2471
2472
	/**
2473
	 * Set the menu title for this page.
2474
	 *
2475
	 * @param string $value
2476
	 */
2477
	public function setMenuTitle($value) {
2478
		if($value == $this->getField("Title")) {
2479
			$this->setField("MenuTitle", null);
2480
		} else {
2481
			$this->setField("MenuTitle", $value);
2482
		}
2483
	}
2484
2485
	/**
2486
	 * A flag provides the user with additional data about the current page status, for example a "removed from draft"
2487
	 * status. Each page can have more than one status flag. Returns a map of a unique key to a (localized) title for
2488
	 * the flag. The unique key can be reused as a CSS class. Use the 'updateStatusFlags' extension point to customize
2489
	 * the flags.
2490
	 *
2491
	 * Example (simple):
2492
	 *   "deletedonlive" => "Deleted"
2493
	 *
2494
	 * Example (with optional title attribute):
2495
	 *   "deletedonlive" => array('text' => "Deleted", 'title' => 'This page has been deleted')
2496
	 *
2497
	 * @param bool $cached Whether to serve the fields from cache; false regenerate them
2498
	 * @return array
2499
	 */
2500
	public function getStatusFlags($cached = true) {
2501
		if(!$this->_cache_statusFlags || !$cached) {
2502
			$flags = array();
2503
			if($this->getIsDeletedFromStage()) {
2504
				if($this->isPublished()) {
2505
					$flags['removedfromdraft'] = array(
2506
						'text' => _t('SiteTree.REMOVEDFROMDRAFTSHORT', 'Removed from draft'),
2507
						'title' => _t('SiteTree.REMOVEDFROMDRAFTHELP', 'Page is published, but has been deleted from draft'),
2508
					);
2509
				} else {
2510
					$flags['archived'] = array(
2511
						'text' => _t('SiteTree.ARCHIVEDPAGESHORT', 'Archived'),
2512
						'title' => _t('SiteTree.ARCHIVEDPAGEHELP', 'Page is removed from draft and live'),
2513
					);
2514
				}
2515
			} else if($this->getIsAddedToStage()) {
2516
				$flags['addedtodraft'] = array(
2517
					'text' => _t('SiteTree.ADDEDTODRAFTSHORT', 'Draft'),
2518
					'title' => _t('SiteTree.ADDEDTODRAFTHELP', "Page has not been published yet")
2519
				);
2520
			} else if($this->getIsModifiedOnStage()) {
2521
				$flags['modified'] = array(
2522
					'text' => _t('SiteTree.MODIFIEDONDRAFTSHORT', 'Modified'),
2523
					'title' => _t('SiteTree.MODIFIEDONDRAFTHELP', 'Page has unpublished changes'),
2524
				);
2525
			}
2526
2527
			$this->extend('updateStatusFlags', $flags);
2528
2529
			$this->_cache_statusFlags = $flags;
2530
		}
2531
2532
		return $this->_cache_statusFlags;
2533
	}
2534
2535
	/**
2536
	 * getTreeTitle will return three <span> html DOM elements, an empty <span> with the class 'jstree-pageicon' in
2537
	 * front, following by a <span> wrapping around its MenutTitle, then following by a <span> indicating its
2538
	 * publication status.
2539
	 *
2540
	 * @return string An HTML string ready to be directly used in a template
2541
	 */
2542
	public function getTreeTitle() {
2543
		// Build the list of candidate children
2544
		$children = array();
2545
		$candidates = static::page_type_classes();
2546
		foreach($this->allowedChildren() as $childClass) {
2547
			if(!in_array($childClass, $candidates)) continue;
2548
			$child = singleton($childClass);
2549
			if($child->canCreate(null, array('Parent' => $this))) {
2550
				$children[$childClass] = $child->i18n_singular_name();
2551
			}
2552
		}
2553
		$flags = $this->getStatusFlags();
2554
		$treeTitle = sprintf(
2555
			"<span class=\"jstree-pageicon\"></span><span class=\"item\" data-allowedchildren=\"%s\">%s</span>",
2556
			Convert::raw2att(Convert::raw2json($children)),
2557
			Convert::raw2xml(str_replace(array("\n","\r"),"",$this->MenuTitle))
2558
		);
2559
		foreach($flags as $class => $data) {
2560
			if(is_string($data)) $data = array('text' => $data);
2561
			$treeTitle .= sprintf(
2562
				"<span class=\"badge %s\"%s>%s</span>",
2563
				'status-' . Convert::raw2xml($class),
2564
				(isset($data['title'])) ? sprintf(' title="%s"', Convert::raw2xml($data['title'])) : '',
2565
				Convert::raw2xml($data['text'])
2566
			);
2567
		}
2568
2569
		return $treeTitle;
2570
	}
2571
2572
	/**
2573
	 * Returns the page in the current page stack of the given level. Level(1) will return the main menu item that
2574
	 * we're currently inside, etc.
2575
	 *
2576
	 * @param int $level
2577
	 * @return SiteTree
2578
	 */
2579
	public function Level($level) {
2580
		$parent = $this;
2581
		$stack = array($parent);
2582
		while($parent = $parent->Parent) {
2583
			array_unshift($stack, $parent);
2584
		}
2585
2586
		return isset($stack[$level-1]) ? $stack[$level-1] : null;
2587
	}
2588
2589
	/**
2590
	 * Gets the depth of this page in the sitetree, where 1 is the root level
2591
	 *
2592
	 * @return int
2593
	 */
2594
	public function getPageLevel() {
2595
		if($this->ParentID) {
2596
			return 1 + $this->Parent()->getPageLevel();
2597
		}
2598
		return 1;
2599
	}
2600
2601
	/**
2602
	 * Return the CSS classes to apply to this node in the CMS tree.
2603
	 *
2604
	 * @param string $numChildrenMethod
2605
	 * @return string
2606
	 */
2607
	public function CMSTreeClasses($numChildrenMethod="numChildren") {
2608
		$classes = sprintf('class-%s', $this->class);
2609
		if($this->HasBrokenFile || $this->HasBrokenLink) {
2610
			$classes .= " BrokenLink";
2611
		}
2612
2613
		if(!$this->canAddChildren()) {
2614
			$classes .= " nochildren";
2615
		}
2616
2617
		if(!$this->canEdit() && !$this->canAddChildren()) {
2618
			if (!$this->canView()) {
2619
				$classes .= " disabled";
2620
			} else {
2621
				$classes .= " edit-disabled";
2622
			}
2623
		}
2624
2625
		if(!$this->ShowInMenus) {
2626
			$classes .= " notinmenu";
2627
		}
2628
2629
		//TODO: Add integration
2630
		/*
2631
		if($this->hasExtension('Translatable') && $controller->Locale != Translatable::default_locale() && !$this->isTranslation())
2632
			$classes .= " untranslated ";
2633
		*/
2634
		$classes .= $this->markingClasses($numChildrenMethod);
2635
2636
		return $classes;
2637
	}
2638
2639
	/**
2640
	 * Compares current draft with live version, and returns true if no draft version of this page exists  but the page
2641
	 * is still published (eg, after triggering "Delete from draft site" in the CMS).
2642
	 *
2643
	 * @return bool
2644
	 */
2645
	public function getIsDeletedFromStage() {
2646
		if(!$this->ID) return true;
2647
		if($this->isNew()) return false;
2648
2649
		$stageVersion = Versioned::get_versionnumber_by_stage('SiteTree', Versioned::DRAFT, $this->ID);
2650
2651
		// Return true for both completely deleted pages and for pages just deleted from stage
2652
		return !($stageVersion);
2653
	}
2654
2655
	/**
2656
	 * Return true if this page exists on the live site
2657
	 *
2658
	 * @return bool
2659
	 */
2660
	public function getExistsOnLive() {
2661
		return $this->isPublished();
2662
	}
2663
2664
	/**
2665
	 * Compares current draft with live version, and returns true if these versions differ, meaning there have been
2666
	 * unpublished changes to the draft site.
2667
	 *
2668
	 * @return bool
2669
	 */
2670
	public function getIsModifiedOnStage() {
2671
		// New unsaved pages could be never be published
2672
		if($this->isNew()) return false;
2673
2674
		$stageVersion = Versioned::get_versionnumber_by_stage('SiteTree', 'Stage', $this->ID);
2675
		$liveVersion =	Versioned::get_versionnumber_by_stage('SiteTree', 'Live', $this->ID);
2676
2677
		$isModified = ($stageVersion && $stageVersion != $liveVersion);
2678
		$this->extend('getIsModifiedOnStage', $isModified);
2679
2680
		return $isModified;
2681
	}
2682
2683
	/**
2684
	 * Compares current draft with live version, and returns true if no live version exists, meaning the page was never
2685
	 * published.
2686
	 *
2687
	 * @return bool
2688
	 */
2689
	public function getIsAddedToStage() {
2690
		// New unsaved pages could be never be published
2691
		if($this->isNew()) return false;
2692
2693
		$stageVersion = Versioned::get_versionnumber_by_stage('SiteTree', 'Stage', $this->ID);
2694
		$liveVersion =	Versioned::get_versionnumber_by_stage('SiteTree', 'Live', $this->ID);
2695
2696
		return ($stageVersion && !$liveVersion);
2697
	}
2698
2699
	/**
2700
	 * Stops extendCMSFields() being called on getCMSFields(). This is useful when you need access to fields added by
2701
	 * subclasses of SiteTree in a extension. Call before calling parent::getCMSFields(), and reenable afterwards.
2702
	 */
2703
	static public function disableCMSFieldsExtensions() {
2704
		self::$runCMSFieldsExtensions = false;
2705
	}
2706
2707
	/**
2708
	 * Reenables extendCMSFields() being called on getCMSFields() after it has been disabled by
2709
	 * disableCMSFieldsExtensions().
2710
	 */
2711
	static public function enableCMSFieldsExtensions() {
2712
		self::$runCMSFieldsExtensions = true;
2713
	}
2714
2715
	public function providePermissions() {
2716
		return array(
2717
			'SITETREE_GRANT_ACCESS' => array(
2718
				'name' => _t('SiteTree.PERMISSION_GRANTACCESS_DESCRIPTION', 'Manage access rights for content'),
2719
				'help' => _t('SiteTree.PERMISSION_GRANTACCESS_HELP',  'Allow setting of page-specific access restrictions in the "Pages" section.'),
2720
				'category' => _t('Permissions.PERMISSIONS_CATEGORY', 'Roles and access permissions'),
2721
				'sort' => 100
2722
			),
2723
			'SITETREE_VIEW_ALL' => array(
2724
				'name' => _t('SiteTree.VIEW_ALL_DESCRIPTION', 'View any page'),
2725
				'category' => _t('Permissions.CONTENT_CATEGORY', 'Content permissions'),
2726
				'sort' => -100,
2727
				'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')
2728
			),
2729
			'SITETREE_EDIT_ALL' => array(
2730
				'name' => _t('SiteTree.EDIT_ALL_DESCRIPTION', 'Edit any page'),
2731
				'category' => _t('Permissions.CONTENT_CATEGORY', 'Content permissions'),
2732
				'sort' => -50,
2733
				'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')
2734
			),
2735
			'SITETREE_REORGANISE' => array(
2736
				'name' => _t('SiteTree.REORGANISE_DESCRIPTION', 'Change site structure'),
2737
				'category' => _t('Permissions.CONTENT_CATEGORY', 'Content permissions'),
2738
				'help' => _t('SiteTree.REORGANISE_HELP', 'Rearrange pages in the site tree through drag&drop.'),
2739
				'sort' => 100
2740
			),
2741
			'VIEW_DRAFT_CONTENT' => array(
2742
				'name' => _t('SiteTree.VIEW_DRAFT_CONTENT', 'View draft content'),
2743
				'category' => _t('Permissions.CONTENT_CATEGORY', 'Content permissions'),
2744
				'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.'),
2745
				'sort' => 100
2746
			)
2747
		);
2748
	}
2749
2750
	/**
2751
	 * Return the translated Singular name.
2752
	 *
2753
	 * @return string
2754
	 */
2755
	public function i18n_singular_name() {
2756
		// Convert 'Page' to 'SiteTree' for correct localization lookups
2757
		$class = ($this->class == 'Page') ? 'SiteTree' : $this->class;
2758
		return _t($class.'.SINGULARNAME', $this->singular_name());
2759
	}
2760
2761
	/**
2762
	 * Overloaded to also provide entities for 'Page' class which is usually located in custom code, hence textcollector
2763
	 * picks it up for the wrong folder.
2764
	 *
2765
	 * @return array
2766
	 */
2767
	public function provideI18nEntities() {
2768
		$entities = parent::provideI18nEntities();
2769
2770
		if(isset($entities['Page.SINGULARNAME'])) $entities['Page.SINGULARNAME'][3] = CMS_DIR;
2771
		if(isset($entities['Page.PLURALNAME'])) $entities['Page.PLURALNAME'][3] = CMS_DIR;
2772
2773
		$entities[$this->class . '.DESCRIPTION'] = array(
2774
			$this->stat('description'),
2775
			'Description of the page type (shown in the "add page" dialog)'
2776
		);
2777
2778
		$entities['SiteTree.SINGULARNAME'][0] = 'Page';
2779
		$entities['SiteTree.PLURALNAME'][0] = 'Pages';
2780
2781
		return $entities;
2782
	}
2783
2784
	/**
2785
	 * Returns 'root' if the current page has no parent, or 'subpage' otherwise
2786
	 *
2787
	 * @return string
2788
	 */
2789
	public function getParentType() {
2790
		return $this->ParentID == 0 ? 'root' : 'subpage';
2791
	}
2792
2793
	/**
2794
	 * Clear the permissions cache for SiteTree
2795
	 */
2796
	public static function reset() {
2797
		self::$cache_permissions = array();
2798
	}
2799
2800
	static public function on_db_reset() {
2801
		self::$cache_permissions = array();
2802
	}
2803
2804
}
2805