Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like SiteTree often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use SiteTree, and based on these observations, apply Extract Interface, too.
| 1 | <?php  | 
            ||
| 36 | class SiteTree extends DataObject implements PermissionProvider,i18nEntityProvider,CMSPreviewable { | 
            ||
| 37 | |||
| 38 | /**  | 
            ||
| 39 | * Indicates what kind of children this page type can have.  | 
            ||
| 40 | * This can be an array of allowed child classes, or the string "none" -  | 
            ||
| 41 | * indicating that this page type can't have children.  | 
            ||
| 42 | * If a classname is prefixed by "*", such as "*Page", then only that  | 
            ||
| 43 | * class is allowed - no subclasses. Otherwise, the class and all its  | 
            ||
| 44 | * subclasses are allowed.  | 
            ||
| 45 | 	 * To control allowed children on root level (no parent), use {@link $can_be_root}. | 
            ||
| 46 | *  | 
            ||
| 47 | * Note that this setting is cached when used in the CMS, use the "flush" query parameter to clear it.  | 
            ||
| 48 | *  | 
            ||
| 49 | * @config  | 
            ||
| 50 | * @var array  | 
            ||
| 51 | */  | 
            ||
| 52 | 	private static $allowed_children = array("SiteTree"); | 
            ||
| 53 | |||
| 54 | /**  | 
            ||
| 55 | * The default child class for this page.  | 
            ||
| 56 | 	 * Note: Value might be cached, see {@link $allowed_chilren}. | 
            ||
| 57 | *  | 
            ||
| 58 | * @config  | 
            ||
| 59 | * @var string  | 
            ||
| 60 | */  | 
            ||
| 61 | private static $default_child = "Page";  | 
            ||
| 62 | |||
| 63 | /**  | 
            ||
| 64 | * Default value for SiteTree.ClassName enum  | 
            ||
| 65 | 	 * {@see DBClassName::getDefault} | 
            ||
| 66 | *  | 
            ||
| 67 | * @config  | 
            ||
| 68 | * @var string  | 
            ||
| 69 | */  | 
            ||
| 70 | private static $default_classname = "Page";  | 
            ||
| 
                                                                                                    
                        
                         | 
                |||
| 71 | |||
| 72 | /**  | 
            ||
| 73 | * The default parent class for this page.  | 
            ||
| 74 | 	 * Note: Value might be cached, see {@link $allowed_chilren}. | 
            ||
| 75 | *  | 
            ||
| 76 | * @config  | 
            ||
| 77 | * @var string  | 
            ||
| 78 | */  | 
            ||
| 79 | private static $default_parent = null;  | 
            ||
| 80 | |||
| 81 | /**  | 
            ||
| 82 | * Controls whether a page can be in the root of the site tree.  | 
            ||
| 83 | 	 * Note: Value might be cached, see {@link $allowed_chilren}. | 
            ||
| 84 | *  | 
            ||
| 85 | * @config  | 
            ||
| 86 | * @var bool  | 
            ||
| 87 | */  | 
            ||
| 88 | private static $can_be_root = true;  | 
            ||
| 89 | |||
| 90 | /**  | 
            ||
| 91 | * List of permission codes a user can have to allow a user to create a page of this type.  | 
            ||
| 92 | 	 * Note: Value might be cached, see {@link $allowed_chilren}. | 
            ||
| 93 | *  | 
            ||
| 94 | * @config  | 
            ||
| 95 | * @var array  | 
            ||
| 96 | */  | 
            ||
| 97 | private static $need_permission = null;  | 
            ||
| 98 | |||
| 99 | /**  | 
            ||
| 100 | * If you extend a class, and don't want to be able to select the old class  | 
            ||
| 101 | * in the cms, set this to the old class name. Eg, if you extended Product  | 
            ||
| 102 | * to make ImprovedProduct, then you would set $hide_ancestor to Product.  | 
            ||
| 103 | *  | 
            ||
| 104 | * @config  | 
            ||
| 105 | * @var string  | 
            ||
| 106 | */  | 
            ||
| 107 | private static $hide_ancestor = null;  | 
            ||
| 108 | |||
| 109 | private static $db = array(  | 
            ||
| 110 | "URLSegment" => "Varchar(255)",  | 
            ||
| 111 | "Title" => "Varchar(255)",  | 
            ||
| 112 | "MenuTitle" => "Varchar(100)",  | 
            ||
| 113 | "Content" => "HTMLText",  | 
            ||
| 114 | "MetaDescription" => "Text",  | 
            ||
| 115 | 		"ExtraMeta" => "HTMLText('meta, link')", | 
            ||
| 116 | "ShowInMenus" => "Boolean",  | 
            ||
| 117 | "ShowInSearch" => "Boolean",  | 
            ||
| 118 | "Sort" => "Int",  | 
            ||
| 119 | "HasBrokenFile" => "Boolean",  | 
            ||
| 120 | "HasBrokenLink" => "Boolean",  | 
            ||
| 121 | "ReportClass" => "Varchar",  | 
            ||
| 122 | 		"CanViewType" => "Enum('Anyone, LoggedInUsers, OnlyTheseUsers, Inherit', 'Inherit')", | 
            ||
| 123 | 		"CanEditType" => "Enum('LoggedInUsers, OnlyTheseUsers, Inherit', 'Inherit')", | 
            ||
| 124 | );  | 
            ||
| 125 | |||
| 126 | private static $indexes = array(  | 
            ||
| 127 | "URLSegment" => true,  | 
            ||
| 128 | );  | 
            ||
| 129 | |||
| 130 | private static $many_many = array(  | 
            ||
| 131 | "ViewerGroups" => "Group",  | 
            ||
| 132 | "EditorGroups" => "Group",  | 
            ||
| 133 | );  | 
            ||
| 134 | |||
| 135 | private static $casting = array(  | 
            ||
| 136 | "Breadcrumbs" => "HTMLText",  | 
            ||
| 137 | "LastEdited" => "SS_Datetime",  | 
            ||
| 138 | "Created" => "SS_Datetime",  | 
            ||
| 139 | 'Link' => 'Text',  | 
            ||
| 140 | 'RelativeLink' => 'Text',  | 
            ||
| 141 | 'AbsoluteLink' => 'Text',  | 
            ||
| 142 | 'TreeTitle' => 'HTMLText',  | 
            ||
| 143 | );  | 
            ||
| 144 | |||
| 145 | private static $defaults = array(  | 
            ||
| 146 | "ShowInMenus" => 1,  | 
            ||
| 147 | "ShowInSearch" => 1,  | 
            ||
| 148 | "CanViewType" => "Inherit",  | 
            ||
| 149 | "CanEditType" => "Inherit"  | 
            ||
| 150 | );  | 
            ||
| 151 | |||
| 152 | private static $versioning = array(  | 
            ||
| 153 | "Stage", "Live"  | 
            ||
| 154 | );  | 
            ||
| 155 | |||
| 156 | private static $default_sort = "\"Sort\"";  | 
            ||
| 157 | |||
| 158 | /**  | 
            ||
| 159 | * If this is false, the class cannot be created in the CMS by regular content authors, only by ADMINs.  | 
            ||
| 160 | * @var boolean  | 
            ||
| 161 | * @config  | 
            ||
| 162 | */  | 
            ||
| 163 | private static $can_create = true;  | 
            ||
| 164 | |||
| 165 | /**  | 
            ||
| 166 | * Icon to use in the CMS page tree. This should be the full filename, relative to the webroot.  | 
            ||
| 167 | * Also supports custom CSS rule contents (applied to the correct selector for the tree UI implementation).  | 
            ||
| 168 | *  | 
            ||
| 169 | * @see CMSMain::generateTreeStylingCSS()  | 
            ||
| 170 | * @config  | 
            ||
| 171 | * @var string  | 
            ||
| 172 | */  | 
            ||
| 173 | private static $icon = null;  | 
            ||
| 174 | |||
| 175 | /**  | 
            ||
| 176 | * @config  | 
            ||
| 177 | * @var string Description of the class functionality, typically shown to a user  | 
            ||
| 178 | 	 * when selecting which page type to create. Translated through {@link provideI18nEntities()}. | 
            ||
| 179 | */  | 
            ||
| 180 | private static $description = 'Generic content page';  | 
            ||
| 181 | |||
| 182 | private static $extensions = array(  | 
            ||
| 183 | "Hierarchy",  | 
            ||
| 184 | 		"Versioned('Stage', 'Live')", | 
            ||
| 185 | "SiteTreeLinkTracking"  | 
            ||
| 186 | );  | 
            ||
| 187 | |||
| 188 | private static $searchable_fields = array(  | 
            ||
| 189 | 'Title',  | 
            ||
| 190 | 'Content',  | 
            ||
| 191 | );  | 
            ||
| 192 | |||
| 193 | private static $field_labels = array(  | 
            ||
| 194 | 'URLSegment' => 'URL'  | 
            ||
| 195 | );  | 
            ||
| 196 | |||
| 197 | /**  | 
            ||
| 198 | * @config  | 
            ||
| 199 | */  | 
            ||
| 200 | private static $nested_urls = true;  | 
            ||
| 201 | |||
| 202 | /**  | 
            ||
| 203 | * @config  | 
            ||
| 204 | */  | 
            ||
| 205 | private static $create_default_pages = true;  | 
            ||
| 206 | |||
| 207 | /**  | 
            ||
| 208 | * This controls whether of not extendCMSFields() is called by getCMSFields.  | 
            ||
| 209 | */  | 
            ||
| 210 | private static $runCMSFieldsExtensions = true;  | 
            ||
| 211 | |||
| 212 | /**  | 
            ||
| 213 | * Cache for canView/Edit/Publish/Delete permissions.  | 
            ||
| 214 | * Keyed by permission type (e.g. 'edit'), with an array  | 
            ||
| 215 | * of IDs mapped to their boolean permission ability (true=allow, false=deny).  | 
            ||
| 216 | 	 * See {@link batch_permission_check()} for details. | 
            ||
| 217 | */  | 
            ||
| 218 | private static $cache_permissions = array();  | 
            ||
| 219 | |||
| 220 | /**  | 
            ||
| 221 | * @config  | 
            ||
| 222 | * @var boolean  | 
            ||
| 223 | */  | 
            ||
| 224 | private static $enforce_strict_hierarchy = true;  | 
            ||
| 225 | |||
| 226 | /**  | 
            ||
| 227 | * The value used for the meta generator tag. Leave blank to omit the tag.  | 
            ||
| 228 | *  | 
            ||
| 229 | * @config  | 
            ||
| 230 | * @var string  | 
            ||
| 231 | */  | 
            ||
| 232 | private static $meta_generator = 'SilverStripe - http://silverstripe.org';  | 
            ||
| 233 | |||
| 234 | protected $_cache_statusFlags = null;  | 
            ||
| 235 | |||
| 236 | /**  | 
            ||
| 237 | * Determines if the system should avoid orphaned pages  | 
            ||
| 238 | * by deleting all children when the their parent is deleted (TRUE),  | 
            ||
| 239 | * or rather preserve this data even if its not reachable through any navigation path (FALSE).  | 
            ||
| 240 | *  | 
            ||
| 241 | * @deprecated 4.0 Use the "SiteTree.enforce_strict_hierarchy" config setting instead  | 
            ||
| 242 | * @param boolean  | 
            ||
| 243 | */  | 
            ||
| 244 | 	static public function set_enforce_strict_hierarchy($to) { | 
            ||
| 245 | 		Deprecation::notice('4.0', 'Use the "SiteTree.enforce_strict_hierarchy" config setting instead'); | 
            ||
| 246 | 		Config::inst()->update('SiteTree', 'enforce_strict_hierarchy', $to); | 
            ||
| 247 | }  | 
            ||
| 248 | |||
| 249 | /**  | 
            ||
| 250 | * @deprecated 4.0 Use the "SiteTree.enforce_strict_hierarchy" config setting instead  | 
            ||
| 251 | * @return boolean  | 
            ||
| 252 | */  | 
            ||
| 253 | 	static public function get_enforce_strict_hierarchy() { | 
            ||
| 254 | 		Deprecation::notice('4.0', 'Use the "SiteTree.enforce_strict_hierarchy" config setting instead'); | 
            ||
| 255 | 		return Config::inst()->get('SiteTree', 'enforce_strict_hierarchy'); | 
            ||
| 256 | }  | 
            ||
| 257 | |||
| 258 | /**  | 
            ||
| 259 | * Returns TRUE if nested URLs (e.g. page/sub-page/) are currently enabled on this site.  | 
            ||
| 260 | *  | 
            ||
| 261 | * @deprecated 4.0 Use the "SiteTree.nested_urls" config setting instead  | 
            ||
| 262 | * @return bool  | 
            ||
| 263 | */  | 
            ||
| 264 | 	static public function nested_urls() { | 
            ||
| 265 | 		Deprecation::notice('4.0', 'Use the "SiteTree.nested_urls" config setting instead'); | 
            ||
| 266 | 		return Config::inst()->get('SiteTree', 'nested_urls'); | 
            ||
| 267 | }  | 
            ||
| 268 | |||
| 269 | /**  | 
            ||
| 270 | * @deprecated 4.0 Use the "SiteTree.nested_urls" config setting instead  | 
            ||
| 271 | */  | 
            ||
| 272 | 	static public function enable_nested_urls() { | 
            ||
| 273 | 		Deprecation::notice('4.0', 'Use the "SiteTree.nested_urls" config setting instead'); | 
            ||
| 274 | 		Config::inst()->update('SiteTree', 'nested_urls', true); | 
            ||
| 275 | }  | 
            ||
| 276 | |||
| 277 | /**  | 
            ||
| 278 | * @deprecated 4.0 Use the "SiteTree.nested_urls" config setting instead  | 
            ||
| 279 | */  | 
            ||
| 280 | 	static public function disable_nested_urls() { | 
            ||
| 281 | 		Deprecation::notice('4.0', 'Use the "SiteTree.nested_urls" config setting instead'); | 
            ||
| 282 | 		Config::inst()->update('SiteTree', 'nested_urls', false); | 
            ||
| 283 | }  | 
            ||
| 284 | |||
| 285 | /**  | 
            ||
| 286 | * Set the (re)creation of default pages on /dev/build  | 
            ||
| 287 | *  | 
            ||
| 288 | * @deprecated 4.0 Use the "SiteTree.create_default_pages" config setting instead  | 
            ||
| 289 | * @param bool $option  | 
            ||
| 290 | */  | 
            ||
| 291 | 	static public function set_create_default_pages($option = true) { | 
            ||
| 292 | 		Deprecation::notice('4.0', 'Use the "SiteTree.create_default_pages" config setting instead'); | 
            ||
| 293 | 		Config::inst()->update('SiteTree', 'create_default_pages', $option); | 
            ||
| 294 | }  | 
            ||
| 295 | |||
| 296 | /**  | 
            ||
| 297 | * Return true if default pages should be created on /dev/build.  | 
            ||
| 298 | *  | 
            ||
| 299 | * @deprecated 4.0 Use the "SiteTree.create_default_pages" config setting instead  | 
            ||
| 300 | * @return bool  | 
            ||
| 301 | */  | 
            ||
| 302 | 	static public function get_create_default_pages() { | 
            ||
| 303 | 		Deprecation::notice('4.0', 'Use the "SiteTree.create_default_pages" config setting instead'); | 
            ||
| 304 | 		return Config::inst()->get('SiteTree', 'create_default_pages'); | 
            ||
| 305 | }  | 
            ||
| 306 | |||
| 307 | /**  | 
            ||
| 308 | 	 * Fetches the {@link SiteTree} object that maps to a link. | 
            ||
| 309 | *  | 
            ||
| 310 | 	 * If you have enabled {@link SiteTree::config()->nested_urls} on this site, then you can use a nested link such as | 
            ||
| 311 | * "about-us/staff/", and this function will traverse down the URL chain and grab the appropriate link.  | 
            ||
| 312 | *  | 
            ||
| 313 | * Note that if no model can be found, this method will fall over to a extended alternateGetByLink method provided  | 
            ||
| 314 | 	 * by a extension attached to {@link SiteTree} | 
            ||
| 315 | *  | 
            ||
| 316 | * @param string $link The link of the page to search for  | 
            ||
| 317 | * @param bool $cache True (default) to use caching, false to force a fresh search from the database  | 
            ||
| 318 | * @return SiteTree  | 
            ||
| 319 | */  | 
            ||
| 320 | 	static public function get_by_link($link, $cache = true) { | 
            ||
| 321 | 		if(trim($link, '/')) { | 
            ||
| 322 | $link = trim(Director::makeRelative($link), '/');  | 
            ||
| 323 | 		} else { | 
            ||
| 324 | $link = RootURLController::get_homepage_link();  | 
            ||
| 325 | }  | 
            ||
| 326 | |||
| 327 | 		$parts = preg_split('|/+|', $link); | 
            ||
| 328 | |||
| 329 | // Grab the initial root level page to traverse down from.  | 
            ||
| 330 | $URLSegment = array_shift($parts);  | 
            ||
| 331 | 		$conditions = array('"SiteTree"."URLSegment"' => rawurlencode($URLSegment)); | 
            ||
| 332 | 		if(self::config()->nested_urls) { | 
            ||
| 333 | 			$conditions[] = array('"SiteTree"."ParentID"' => 0); | 
            ||
| 334 | }  | 
            ||
| 335 | 		$sitetree = DataObject::get_one('SiteTree', $conditions, $cache); | 
            ||
| 336 | |||
| 337 | /// Fall back on a unique URLSegment for b/c.  | 
            ||
| 338 | if( !$sitetree  | 
            ||
| 339 | && self::config()->nested_urls  | 
            ||
| 340 | 			&& $page = DataObject::get_one('SiteTree', array( | 
            ||
| 341 | '"SiteTree"."URLSegment"' => $URLSegment  | 
            ||
| 342 | ), $cache)  | 
            ||
| 343 | 		) { | 
            ||
| 344 | return $page;  | 
            ||
| 345 | }  | 
            ||
| 346 | |||
| 347 | // Attempt to grab an alternative page from extensions.  | 
            ||
| 348 | 		if(!$sitetree) { | 
            ||
| 349 | $parentID = self::config()->nested_urls ? 0 : null;  | 
            ||
| 350 | |||
| 351 | View Code Duplication | 			if($alternatives = singleton('SiteTree')->extend('alternateGetByLink', $URLSegment, $parentID)) { | 
            |
| 352 | foreach($alternatives as $alternative) if($alternative) $sitetree = $alternative;  | 
            ||
| 353 | }  | 
            ||
| 354 | |||
| 355 | if(!$sitetree) return false;  | 
            ||
| 356 | }  | 
            ||
| 357 | |||
| 358 | // Check if we have any more URL parts to parse.  | 
            ||
| 359 | if(!self::config()->nested_urls || !count($parts)) return $sitetree;  | 
            ||
| 360 | |||
| 361 | // Traverse down the remaining URL segments and grab the relevant SiteTree objects.  | 
            ||
| 362 | 		foreach($parts as $segment) { | 
            ||
| 363 | 			$next = DataObject::get_one('SiteTree', array( | 
            ||
| 364 | '"SiteTree"."URLSegment"' => $segment,  | 
            ||
| 365 | '"SiteTree"."ParentID"' => $sitetree->ID  | 
            ||
| 366 | ),  | 
            ||
| 367 | $cache  | 
            ||
| 368 | );  | 
            ||
| 369 | |||
| 370 | 			if(!$next) { | 
            ||
| 371 | $parentID = (int) $sitetree->ID;  | 
            ||
| 372 | |||
| 373 | View Code Duplication | 				if($alternatives = singleton('SiteTree')->extend('alternateGetByLink', $segment, $parentID)) { | 
            |
| 374 | foreach($alternatives as $alternative) if($alternative) $next = $alternative;  | 
            ||
| 375 | }  | 
            ||
| 376 | |||
| 377 | if(!$next) return false;  | 
            ||
| 378 | }  | 
            ||
| 379 | |||
| 380 | $sitetree->destroy();  | 
            ||
| 381 | $sitetree = $next;  | 
            ||
| 382 | }  | 
            ||
| 383 | |||
| 384 | return $sitetree;  | 
            ||
| 385 | }  | 
            ||
| 386 | |||
| 387 | /**  | 
            ||
| 388 | 	 * Return a subclass map of SiteTree that shouldn't be hidden through {@link SiteTree::$hide_ancestor} | 
            ||
| 389 | *  | 
            ||
| 390 | * @return array  | 
            ||
| 391 | */  | 
            ||
| 392 | 	static public function page_type_classes() { | 
            ||
| 393 | $classes = ClassInfo::getValidSubClasses();  | 
            ||
| 394 | |||
| 395 | 		$baseClassIndex = array_search('SiteTree', $classes); | 
            ||
| 396 | if($baseClassIndex !== FALSE) unset($classes[$baseClassIndex]);  | 
            ||
| 397 | |||
| 398 | $kill_ancestors = array();  | 
            ||
| 399 | |||
| 400 | // figure out if there are any classes we don't want to appear  | 
            ||
| 401 | 		foreach($classes as $class) { | 
            ||
| 402 | $instance = singleton($class);  | 
            ||
| 403 | |||
| 404 | // do any of the progeny want to hide an ancestor?  | 
            ||
| 405 | 			if($ancestor_to_hide = $instance->stat('hide_ancestor')) { | 
            ||
| 406 | // note for killing later  | 
            ||
| 407 | $kill_ancestors[] = $ancestor_to_hide;  | 
            ||
| 408 | }  | 
            ||
| 409 | }  | 
            ||
| 410 | |||
| 411 | // If any of the descendents don't want any of the elders to show up, cruelly render the elders surplus to  | 
            ||
| 412 | // requirements  | 
            ||
| 413 | 		if($kill_ancestors) { | 
            ||
| 414 | $kill_ancestors = array_unique($kill_ancestors);  | 
            ||
| 415 | 			foreach($kill_ancestors as $mark) { | 
            ||
| 416 | // unset from $classes  | 
            ||
| 417 | $idx = array_search($mark, $classes);  | 
            ||
| 418 | unset($classes[$idx]);  | 
            ||
| 419 | }  | 
            ||
| 420 | }  | 
            ||
| 421 | |||
| 422 | return $classes;  | 
            ||
| 423 | }  | 
            ||
| 424 | |||
| 425 | /**  | 
            ||
| 426 | * Replace a "[sitetree_link id=n]" shortcode with a link to the page with the corresponding ID.  | 
            ||
| 427 | *  | 
            ||
| 428 | * @param array $arguments  | 
            ||
| 429 | * @param string $content  | 
            ||
| 430 | * @param TextParser $parser  | 
            ||
| 431 | * @return string  | 
            ||
| 432 | */  | 
            ||
| 433 | 	static public function link_shortcode_handler($arguments, $content = null, $parser = null) { | 
            ||
| 434 | if(!isset($arguments['id']) || !is_numeric($arguments['id'])) return;  | 
            ||
| 435 | |||
| 436 | if (  | 
            ||
| 437 | 			   !($page = DataObject::get_by_id('SiteTree', $arguments['id']))         // Get the current page by ID. | 
            ||
| 438 | 			&& !($page = Versioned::get_latest_version('SiteTree', $arguments['id'])) // Attempt link to old version. | 
            ||
| 439 | 		) { | 
            ||
| 440 | return; // There were no suitable matches at all.  | 
            ||
| 441 | }  | 
            ||
| 442 | |||
| 443 | $link = Convert::raw2att($page->Link());  | 
            ||
| 444 | |||
| 445 | 		if($content) { | 
            ||
| 446 | 			return sprintf('<a href="%s">%s</a>', $link, $parser->parse($content)); | 
            ||
| 447 | 		} else { | 
            ||
| 448 | return $link;  | 
            ||
| 449 | }  | 
            ||
| 450 | }  | 
            ||
| 451 | |||
| 452 | /**  | 
            ||
| 453 | 	 * Return the link for this {@link SiteTree} object, with the {@link Director::baseURL()} included. | 
            ||
| 454 | *  | 
            ||
| 455 | * @param string $action Optional controller action (method).  | 
            ||
| 456 | * Note: URI encoding of this parameter is applied automatically through template casting,  | 
            ||
| 457 | 	 *                       don't encode the passed parameter. Please use {@link Controller::join_links()} instead to | 
            ||
| 458 | * append GET parameters.  | 
            ||
| 459 | * @return string  | 
            ||
| 460 | */  | 
            ||
| 461 | 	public function Link($action = null) { | 
            ||
| 462 | return Controller::join_links(Director::baseURL(), $this->RelativeLink($action));  | 
            ||
| 463 | }  | 
            ||
| 464 | |||
| 465 | /**  | 
            ||
| 466 | * Get the absolute URL for this page, including protocol and host.  | 
            ||
| 467 | *  | 
            ||
| 468 | 	 * @param string $action See {@link Link()} | 
            ||
| 469 | * @return string  | 
            ||
| 470 | */  | 
            ||
| 471 | 	public function AbsoluteLink($action = null) { | 
            ||
| 472 | 		if($this->hasMethod('alternateAbsoluteLink')) { | 
            ||
| 473 | return $this->alternateAbsoluteLink($action);  | 
            ||
| 474 | 		} else { | 
            ||
| 475 | return Director::absoluteURL($this->Link($action));  | 
            ||
| 476 | }  | 
            ||
| 477 | }  | 
            ||
| 478 | |||
| 479 | /**  | 
            ||
| 480 | * Base link used for previewing. Defaults to absolute URL, in order to account for domain changes, e.g. on multi  | 
            ||
| 481 | 	 * site setups. Does not contain hints about the stage, see {@link SilverStripeNavigator} for details. | 
            ||
| 482 | *  | 
            ||
| 483 | 	 * @param string $action See {@link Link()} | 
            ||
| 484 | * @return string  | 
            ||
| 485 | */  | 
            ||
| 486 | 	public function PreviewLink($action = null) { | 
            ||
| 487 | 		if($this->hasMethod('alternatePreviewLink')) { | 
            ||
| 488 | return $this->alternatePreviewLink($action);  | 
            ||
| 489 | 		} else { | 
            ||
| 490 | return $this->AbsoluteLink($action);  | 
            ||
| 491 | }  | 
            ||
| 492 | }  | 
            ||
| 493 | |||
| 494 | /**  | 
            ||
| 495 | 	 * Return the link for this {@link SiteTree} object relative to the SilverStripe root. | 
            ||
| 496 | *  | 
            ||
| 497 | * By default, if this page is the current home page, and there is no action specified then this will return a link  | 
            ||
| 498 | * to the root of the site. However, if you set the $action parameter to TRUE then the link will not be rewritten  | 
            ||
| 499 | * and returned in its full form.  | 
            ||
| 500 | *  | 
            ||
| 501 | * @uses RootURLController::get_homepage_link()  | 
            ||
| 502 | *  | 
            ||
| 503 | 	 * @param string $action See {@link Link()} | 
            ||
| 504 | * @return string  | 
            ||
| 505 | */  | 
            ||
| 506 | 	public function RelativeLink($action = null) { | 
            ||
| 507 | 		if($this->ParentID && self::config()->nested_urls) { | 
            ||
| 508 | $parent = $this->Parent();  | 
            ||
| 509 | // If page is removed select parent from version history (for archive page view)  | 
            ||
| 510 | 			if((!$parent || !$parent->exists()) && $this->IsDeletedFromStage) { | 
            ||
| 511 | 				$parent = Versioned::get_latest_version('SiteTree', $this->ParentID); | 
            ||
| 512 | }  | 
            ||
| 513 | $base = $parent->RelativeLink($this->URLSegment);  | 
            ||
| 514 | 		} elseif(!$action && $this->URLSegment == RootURLController::get_homepage_link()) { | 
            ||
| 515 | // Unset base for root-level homepages.  | 
            ||
| 516 | // Note: Homepages with action parameters (or $action === true)  | 
            ||
| 517 | // need to retain their URLSegment.  | 
            ||
| 518 | $base = null;  | 
            ||
| 519 | 		} else { | 
            ||
| 520 | $base = $this->URLSegment;  | 
            ||
| 521 | }  | 
            ||
| 522 | |||
| 523 | 		$this->extend('updateRelativeLink', $base, $action); | 
            ||
| 524 | |||
| 525 | // Legacy support: If $action === true, retain URLSegment for homepages,  | 
            ||
| 526 | // but don't append any action  | 
            ||
| 527 | if($action === true) $action = null;  | 
            ||
| 528 | |||
| 529 | return Controller::join_links($base, '/', $action);  | 
            ||
| 530 | }  | 
            ||
| 531 | |||
| 532 | /**  | 
            ||
| 533 | * Get the absolute URL for this page on the Live site.  | 
            ||
| 534 | *  | 
            ||
| 535 | * @param bool $includeStageEqualsLive Whether to append the URL with ?stage=Live to force Live mode  | 
            ||
| 536 | * @return string  | 
            ||
| 537 | */  | 
            ||
| 538 | 	public function getAbsoluteLiveLink($includeStageEqualsLive = true) { | 
            ||
| 539 | $oldStage = Versioned::current_stage();  | 
            ||
| 540 | 		Versioned::reading_stage('Live'); | 
            ||
| 541 | 		$live = Versioned::get_one_by_stage('SiteTree', 'Live', array( | 
            ||
| 542 | '"SiteTree"."ID"' => $this->ID  | 
            ||
| 543 | ));  | 
            ||
| 544 | 		if($live) { | 
            ||
| 545 | $link = $live->AbsoluteLink();  | 
            ||
| 546 | if($includeStageEqualsLive) $link .= '?stage=Live';  | 
            ||
| 547 | 		} else { | 
            ||
| 548 | $link = null;  | 
            ||
| 549 | }  | 
            ||
| 550 | |||
| 551 | Versioned::reading_stage($oldStage);  | 
            ||
| 552 | return $link;  | 
            ||
| 553 | }  | 
            ||
| 554 | |||
| 555 | /**  | 
            ||
| 556 | * Generates a link to edit this page in the CMS.  | 
            ||
| 557 | *  | 
            ||
| 558 | * @return string  | 
            ||
| 559 | */  | 
            ||
| 560 | 	public function CMSEditLink() { | 
            ||
| 561 | 		return Controller::join_links(singleton('CMSPageEditController')->Link('show'), $this->ID); | 
            ||
| 562 | }  | 
            ||
| 563 | |||
| 564 | |||
| 565 | /**  | 
            ||
| 566 | * Return a CSS identifier generated from this page's link.  | 
            ||
| 567 | *  | 
            ||
| 568 | * @return string The URL segment  | 
            ||
| 569 | */  | 
            ||
| 570 | 	public function ElementName() { | 
            ||
| 571 | 		return str_replace('/', '-', trim($this->RelativeLink(true), '/')); | 
            ||
| 572 | }  | 
            ||
| 573 | |||
| 574 | /**  | 
            ||
| 575 | * Returns true if this is the currently active page being used to handle this request.  | 
            ||
| 576 | *  | 
            ||
| 577 | * @return bool  | 
            ||
| 578 | */  | 
            ||
| 579 | 	public function isCurrent() { | 
            ||
| 580 | return $this->ID ? $this->ID == Director::get_current_page()->ID : $this === Director::get_current_page();  | 
            ||
| 581 | }  | 
            ||
| 582 | |||
| 583 | /**  | 
            ||
| 584 | * Check if this page is in the currently active section (e.g. it is either current or one of its children is  | 
            ||
| 585 | * currently being viewed).  | 
            ||
| 586 | *  | 
            ||
| 587 | * @return bool  | 
            ||
| 588 | */  | 
            ||
| 589 | 	public function isSection() { | 
            ||
| 590 | return $this->isCurrent() || (  | 
            ||
| 591 | Director::get_current_page() instanceof SiteTree && in_array($this->ID, Director::get_current_page()->getAncestors()->column())  | 
            ||
| 592 | );  | 
            ||
| 593 | }  | 
            ||
| 594 | |||
| 595 | /**  | 
            ||
| 596 | * Check if the parent of this page has been removed (or made otherwise unavailable), and is still referenced by  | 
            ||
| 597 | * this child. Any such orphaned page may still require access via the CMS, but should not be shown as accessible  | 
            ||
| 598 | * to external users.  | 
            ||
| 599 | *  | 
            ||
| 600 | * @return bool  | 
            ||
| 601 | */  | 
            ||
| 602 | 	public function isOrphaned() { | 
            ||
| 603 | // Always false for root pages  | 
            ||
| 604 | if(empty($this->ParentID)) return false;  | 
            ||
| 605 | |||
| 606 | // Parent must exist and not be an orphan itself  | 
            ||
| 607 | $parent = $this->Parent();  | 
            ||
| 608 | return !$parent || !$parent->exists() || $parent->isOrphaned();  | 
            ||
| 609 | }  | 
            ||
| 610 | |||
| 611 | /**  | 
            ||
| 612 | 	 * Return "link" or "current" depending on if this is the {@link SiteTree::isCurrent()} current page. | 
            ||
| 613 | *  | 
            ||
| 614 | * @return string  | 
            ||
| 615 | */  | 
            ||
| 616 | 	public function LinkOrCurrent() { | 
            ||
| 617 | return $this->isCurrent() ? 'current' : 'link';  | 
            ||
| 618 | }  | 
            ||
| 619 | |||
| 620 | /**  | 
            ||
| 621 | 	 * Return "link" or "section" depending on if this is the {@link SiteTree::isSeciton()} current section. | 
            ||
| 622 | *  | 
            ||
| 623 | * @return string  | 
            ||
| 624 | */  | 
            ||
| 625 | 	public function LinkOrSection() { | 
            ||
| 626 | return $this->isSection() ? 'section' : 'link';  | 
            ||
| 627 | }  | 
            ||
| 628 | |||
| 629 | /**  | 
            ||
| 630 | * Return "link", "current" or "section" depending on if this page is the current page, or not on the current page  | 
            ||
| 631 | * but in the current section.  | 
            ||
| 632 | *  | 
            ||
| 633 | * @return string  | 
            ||
| 634 | */  | 
            ||
| 635 | 	public function LinkingMode() { | 
            ||
| 636 | 		if($this->isCurrent()) { | 
            ||
| 637 | return 'current';  | 
            ||
| 638 | 		} elseif($this->isSection()) { | 
            ||
| 639 | return 'section';  | 
            ||
| 640 | 		} else { | 
            ||
| 641 | return 'link';  | 
            ||
| 642 | }  | 
            ||
| 643 | }  | 
            ||
| 644 | |||
| 645 | /**  | 
            ||
| 646 | * Check if this page is in the given current section.  | 
            ||
| 647 | *  | 
            ||
| 648 | * @param string $sectionName Name of the section to check  | 
            ||
| 649 | * @return bool True if we are in the given section  | 
            ||
| 650 | */  | 
            ||
| 651 | 	public function InSection($sectionName) { | 
            ||
| 652 | $page = Director::get_current_page();  | 
            ||
| 653 | 		while($page) { | 
            ||
| 654 | if($sectionName == $page->URLSegment)  | 
            ||
| 655 | return true;  | 
            ||
| 656 | $page = $page->Parent;  | 
            ||
| 657 | }  | 
            ||
| 658 | return false;  | 
            ||
| 659 | }  | 
            ||
| 660 | |||
| 661 | /**  | 
            ||
| 662 | * Create a duplicate of this node. Doesn't affect joined data - create a custom overloading of this if you need  | 
            ||
| 663 | * such behaviour.  | 
            ||
| 664 | *  | 
            ||
| 665 | * @param bool $doWrite Whether to write the new object before returning it  | 
            ||
| 666 | * @return self The duplicated object  | 
            ||
| 667 | */  | 
            ||
| 668 | 	 public function duplicate($doWrite = true) { | 
            ||
| 669 | |||
| 670 | $page = parent::duplicate(false);  | 
            ||
| 671 | $page->Sort = 0;  | 
            ||
| 672 | 		$this->invokeWithExtensions('onBeforeDuplicate', $page); | 
            ||
| 673 | |||
| 674 | 		if($doWrite) { | 
            ||
| 675 | $page->write();  | 
            ||
| 676 | |||
| 677 | $page = $this->duplicateManyManyRelations($this, $page);  | 
            ||
| 678 | }  | 
            ||
| 679 | 		$this->invokeWithExtensions('onAfterDuplicate', $page); | 
            ||
| 680 | |||
| 681 | return $page;  | 
            ||
| 682 | }  | 
            ||
| 683 | |||
| 684 | /**  | 
            ||
| 685 | * Duplicates each child of this node recursively and returns the top-level duplicate node.  | 
            ||
| 686 | *  | 
            ||
| 687 | * @return self The duplicated object  | 
            ||
| 688 | */  | 
            ||
| 689 | 	public function duplicateWithChildren() { | 
            ||
| 690 | $clone = $this->duplicate();  | 
            ||
| 691 | $children = $this->AllChildren();  | 
            ||
| 692 | |||
| 693 | 		if($children) { | 
            ||
| 694 | 			foreach($children as $child) { | 
            ||
| 695 | $childClone = method_exists($child, 'duplicateWithChildren')  | 
            ||
| 696 | ? $child->duplicateWithChildren()  | 
            ||
| 697 | : $child->duplicate();  | 
            ||
| 698 | $childClone->ParentID = $clone->ID;  | 
            ||
| 699 | $childClone->write();  | 
            ||
| 700 | }  | 
            ||
| 701 | }  | 
            ||
| 702 | |||
| 703 | return $clone;  | 
            ||
| 704 | }  | 
            ||
| 705 | |||
| 706 | /**  | 
            ||
| 707 | * Duplicate this node and its children as a child of the node with the given ID  | 
            ||
| 708 | *  | 
            ||
| 709 | * @param int $id ID of the new node's new parent  | 
            ||
| 710 | */  | 
            ||
| 711 | 	public function duplicateAsChild($id) { | 
            ||
| 712 | $newSiteTree = $this->duplicate();  | 
            ||
| 713 | $newSiteTree->ParentID = $id;  | 
            ||
| 714 | $newSiteTree->Sort = 0;  | 
            ||
| 715 | $newSiteTree->write();  | 
            ||
| 716 | }  | 
            ||
| 717 | |||
| 718 | /**  | 
            ||
| 719 | * Return a breadcrumb trail to this page. Excludes "hidden" pages (with ShowInMenus=0) by default.  | 
            ||
| 720 | *  | 
            ||
| 721 | * @param int $maxDepth The maximum depth to traverse.  | 
            ||
| 722 | * @param boolean $unlinked Whether to link page titles.  | 
            ||
| 723 | * @param boolean|string $stopAtPageType ClassName of a page to stop the upwards traversal.  | 
            ||
| 724 | * @param boolean $showHidden Include pages marked with the attribute ShowInMenus = 0  | 
            ||
| 725 | * @return HTMLText The breadcrumb trail.  | 
            ||
| 726 | */  | 
            ||
| 727 | 	public function Breadcrumbs($maxDepth = 20, $unlinked = false, $stopAtPageType = false, $showHidden = false) { | 
            ||
| 728 | $pages = $this->getBreadcrumbItems($maxDepth, $stopAtPageType, $showHidden);  | 
            ||
| 729 | 		$template = new SSViewer('BreadcrumbsTemplate'); | 
            ||
| 730 | return $template->process($this->customise(new ArrayData(array(  | 
            ||
| 731 | "Pages" => $pages,  | 
            ||
| 732 | "Unlinked" => $unlinked  | 
            ||
| 733 | ))));  | 
            ||
| 734 | }  | 
            ||
| 735 | |||
| 736 | |||
| 737 | /**  | 
            ||
| 738 | * Returns a list of breadcrumbs for the current page.  | 
            ||
| 739 | *  | 
            ||
| 740 | * @param int $maxDepth The maximum depth to traverse.  | 
            ||
| 741 | * @param boolean|string $stopAtPageType ClassName of a page to stop the upwards traversal.  | 
            ||
| 742 | * @param boolean $showHidden Include pages marked with the attribute ShowInMenus = 0  | 
            ||
| 743 | *  | 
            ||
| 744 | * @return ArrayList  | 
            ||
| 745 | */  | 
            ||
| 746 | 	public function getBreadcrumbItems($maxDepth = 20, $stopAtPageType = false, $showHidden = false) { | 
            ||
| 747 | $page = $this;  | 
            ||
| 748 | $pages = array();  | 
            ||
| 749 | |||
| 750 | while(  | 
            ||
| 751 | $page  | 
            ||
| 752 | && (!$maxDepth || count($pages) < $maxDepth)  | 
            ||
| 753 | && (!$stopAtPageType || $page->ClassName != $stopAtPageType)  | 
            ||
| 754 |  		) { | 
            ||
| 755 | 			if($showHidden || $page->ShowInMenus || ($page->ID == $this->ID)) { | 
            ||
| 756 | $pages[] = $page;  | 
            ||
| 757 | }  | 
            ||
| 758 | |||
| 759 | $page = $page->Parent;  | 
            ||
| 760 | }  | 
            ||
| 761 | |||
| 762 | return new ArrayList(array_reverse($pages));  | 
            ||
| 763 | }  | 
            ||
| 764 | |||
| 765 | |||
| 766 | /**  | 
            ||
| 767 | * Make this page a child of another page.  | 
            ||
| 768 | *  | 
            ||
| 769 | * If the parent page does not exist, resolve it to a valid ID before updating this page's reference.  | 
            ||
| 770 | *  | 
            ||
| 771 | * @param SiteTree|int $item Either the parent object, or the parent ID  | 
            ||
| 772 | */  | 
            ||
| 773 | 	public function setParent($item) { | 
            ||
| 774 | 		if(is_object($item)) { | 
            ||
| 775 | if (!$item->exists()) $item->write();  | 
            ||
| 776 | 			$this->setField("ParentID", $item->ID); | 
            ||
| 777 | 		} else { | 
            ||
| 778 | 			$this->setField("ParentID", $item); | 
            ||
| 779 | }  | 
            ||
| 780 | }  | 
            ||
| 781 | |||
| 782 | /**  | 
            ||
| 783 | * Get the parent of this page.  | 
            ||
| 784 | *  | 
            ||
| 785 | * @return SiteTree Parent of this page  | 
            ||
| 786 | */  | 
            ||
| 787 | 	public function getParent() { | 
            ||
| 788 | 		if ($parentID = $this->getField("ParentID")) { | 
            ||
| 789 | 			return DataObject::get_by_id("SiteTree", $parentID); | 
            ||
| 790 | }  | 
            ||
| 791 | }  | 
            ||
| 792 | |||
| 793 | /**  | 
            ||
| 794 | * Return a string of the form "parent - page" or "grandparent - parent - page" using page titles  | 
            ||
| 795 | *  | 
            ||
| 796 | * @param int $level The maximum amount of levels to traverse.  | 
            ||
| 797 | * @param string $separator Seperating string  | 
            ||
| 798 | * @return string The resulting string  | 
            ||
| 799 | */  | 
            ||
| 800 | 	public function NestedTitle($level = 2, $separator = " - ") { | 
            ||
| 801 | $item = $this;  | 
            ||
| 802 | 		while($item && $level > 0) { | 
            ||
| 803 | $parts[] = $item->Title;  | 
            ||
| 804 | $item = $item->Parent;  | 
            ||
| 805 | $level--;  | 
            ||
| 806 | }  | 
            ||
| 807 | return implode($separator, array_reverse($parts));  | 
            ||
| 808 | }  | 
            ||
| 809 | |||
| 810 | /**  | 
            ||
| 811 | * This function should return true if the current user can execute this action. It can be overloaded to customise  | 
            ||
| 812 | * the security model for an application.  | 
            ||
| 813 | *  | 
            ||
| 814 | 	 * Slightly altered from parent behaviour in {@link DataObject->can()}: | 
            ||
| 815 | * - Checks for existence of a method named "can<$perm>()" on the object  | 
            ||
| 816 | * - Calls decorators and only returns for FALSE "vetoes"  | 
            ||
| 817 | 	 * - Falls back to {@link Permission::check()} | 
            ||
| 818 | * - Does NOT check for many-many relations named "Can<$perm>"  | 
            ||
| 819 | *  | 
            ||
| 820 | * @uses DataObjectDecorator->can()  | 
            ||
| 821 | *  | 
            ||
| 822 | * @param string $perm The permission to be checked, such as 'View'  | 
            ||
| 823 | * @param Member $member The member whose permissions need checking. Defaults to the currently logged in user.  | 
            ||
| 824 | * @return bool True if the the member is allowed to do the given action  | 
            ||
| 825 | */  | 
            ||
| 826 | 	public function can($perm, $member = null) { | 
            ||
| 827 | View Code Duplication | 		if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) { | 
            |
| 828 | $member = Member::currentUserID();  | 
            ||
| 829 | }  | 
            ||
| 830 | |||
| 831 | if($member && Permission::checkMember($member, "ADMIN")) return true;  | 
            ||
| 832 | |||
| 833 | 		if(is_string($perm) && method_exists($this, 'can' . ucfirst($perm))) { | 
            ||
| 834 | $method = 'can' . ucfirst($perm);  | 
            ||
| 835 | return $this->$method($member);  | 
            ||
| 836 | }  | 
            ||
| 837 | |||
| 838 | 		$results = $this->extend('can', $member); | 
            ||
| 839 | if($results && is_array($results)) if(!min($results)) return false;  | 
            ||
| 840 | |||
| 841 | return ($member && Permission::checkMember($member, $perm));  | 
            ||
| 842 | }  | 
            ||
| 843 | |||
| 844 | /**  | 
            ||
| 845 | * This function should return true if the current user can add children to this page. It can be overloaded to  | 
            ||
| 846 | * customise the security model for an application.  | 
            ||
| 847 | *  | 
            ||
| 848 | * Denies permission if any of the following conditions is true:  | 
            ||
| 849 | * - alternateCanAddChildren() on a extension returns false  | 
            ||
| 850 | * - canEdit() is not granted  | 
            ||
| 851 | 	 * - There are no classes defined in {@link $allowed_children} | 
            ||
| 852 | *  | 
            ||
| 853 | * @uses SiteTreeExtension->canAddChildren()  | 
            ||
| 854 | * @uses canEdit()  | 
            ||
| 855 | * @uses $allowed_children  | 
            ||
| 856 | *  | 
            ||
| 857 | * @param Member|int $member  | 
            ||
| 858 | * @return bool True if the current user can add children  | 
            ||
| 859 | */  | 
            ||
| 860 | 	public function canAddChildren($member = null) { | 
            ||
| 861 | // Disable adding children to archived pages  | 
            ||
| 862 | 		if($this->getIsDeletedFromStage()) { | 
            ||
| 863 | return false;  | 
            ||
| 864 | }  | 
            ||
| 865 | |||
| 866 | View Code Duplication | 		if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) { | 
            |
| 867 | $member = Member::currentUserID();  | 
            ||
| 868 | }  | 
            ||
| 869 | |||
| 870 | if($member && Permission::checkMember($member, "ADMIN")) return true;  | 
            ||
| 871 | |||
| 872 | // Standard mechanism for accepting permission changes from extensions  | 
            ||
| 873 | 		$extended = $this->extendedCan('canAddChildren', $member); | 
            ||
| 874 | if($extended !== null) return $extended;  | 
            ||
| 875 | |||
| 876 | 		return $this->canEdit($member) && $this->stat('allowed_children') != 'none'; | 
            ||
| 877 | }  | 
            ||
| 878 | |||
| 879 | /**  | 
            ||
| 880 | * This function should return true if the current user can view this page. It can be overloaded to customise the  | 
            ||
| 881 | * security model for an application.  | 
            ||
| 882 | *  | 
            ||
| 883 | * Denies permission if any of the following conditions is true:  | 
            ||
| 884 | * - canView() on any extension returns false  | 
            ||
| 885 | * - "CanViewType" directive is set to "Inherit" and any parent page return false for canView()  | 
            ||
| 886 | * - "CanViewType" directive is set to "LoggedInUsers" and no user is logged in  | 
            ||
| 887 | * - "CanViewType" directive is set to "OnlyTheseUsers" and user is not in the given groups  | 
            ||
| 888 | *  | 
            ||
| 889 | * @uses DataExtension->canView()  | 
            ||
| 890 | * @uses ViewerGroups()  | 
            ||
| 891 | *  | 
            ||
| 892 | * @param Member|int $member  | 
            ||
| 893 | * @return bool True if the current user can view this page  | 
            ||
| 894 | */  | 
            ||
| 895 | 	public function canView($member = null) { | 
            ||
| 896 | View Code Duplication | 		if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) { | 
            |
| 897 | $member = Member::currentUserID();  | 
            ||
| 898 | }  | 
            ||
| 899 | |||
| 900 | // admin override  | 
            ||
| 901 | 		if($member && Permission::checkMember($member, array("ADMIN", "SITETREE_VIEW_ALL"))) return true; | 
            ||
| 902 | |||
| 903 | // Orphaned pages (in the current stage) are unavailable, except for admins via the CMS  | 
            ||
| 904 | if($this->isOrphaned()) return false;  | 
            ||
| 905 | |||
| 906 | // Standard mechanism for accepting permission changes from extensions  | 
            ||
| 907 | 		$extended = $this->extendedCan('canView', $member); | 
            ||
| 908 | if($extended !== null) return $extended;  | 
            ||
| 909 | |||
| 910 | // check for empty spec  | 
            ||
| 911 | if(!$this->CanViewType || $this->CanViewType == 'Anyone') return true;  | 
            ||
| 912 | |||
| 913 | // check for inherit  | 
            ||
| 914 | 		if($this->CanViewType == 'Inherit') { | 
            ||
| 915 | if($this->ParentID) return $this->Parent()->canView($member);  | 
            ||
| 916 | else return $this->getSiteConfig()->canViewPages($member);  | 
            ||
| 917 | }  | 
            ||
| 918 | |||
| 919 | // check for any logged-in users  | 
            ||
| 920 | 		if($this->CanViewType == 'LoggedInUsers' && $member) { | 
            ||
| 921 | return true;  | 
            ||
| 922 | }  | 
            ||
| 923 | |||
| 924 | // check for specific groups  | 
            ||
| 925 | 		if($member && is_numeric($member)) $member = DataObject::get_by_id('Member', $member); | 
            ||
| 926 | if(  | 
            ||
| 927 | $this->CanViewType == 'OnlyTheseUsers'  | 
            ||
| 928 | && $member  | 
            ||
| 929 | && $member->inGroups($this->ViewerGroups())  | 
            ||
| 930 | ) return true;  | 
            ||
| 931 | |||
| 932 | return false;  | 
            ||
| 933 | }  | 
            ||
| 934 | |||
| 935 | /**  | 
            ||
| 936 | * This function should return true if the current user can delete this page. It can be overloaded to customise the  | 
            ||
| 937 | * security model for an application.  | 
            ||
| 938 | *  | 
            ||
| 939 | * Denies permission if any of the following conditions is true:  | 
            ||
| 940 | * - canDelete() returns false on any extension  | 
            ||
| 941 | * - canEdit() returns false  | 
            ||
| 942 | * - any descendant page returns false for canDelete()  | 
            ||
| 943 | *  | 
            ||
| 944 | * @uses canDelete()  | 
            ||
| 945 | * @uses SiteTreeExtension->canDelete()  | 
            ||
| 946 | * @uses canEdit()  | 
            ||
| 947 | *  | 
            ||
| 948 | * @param Member $member  | 
            ||
| 949 | * @return bool True if the current user can delete this page  | 
            ||
| 950 | */  | 
            ||
| 951 | 	public function canDelete($member = null) { | 
            ||
| 952 | View Code Duplication | if($member instanceof Member) $memberID = $member->ID;  | 
            |
| 953 | else if(is_numeric($member)) $memberID = $member;  | 
            ||
| 954 | else $memberID = Member::currentUserID();  | 
            ||
| 955 | |||
| 956 | 		if($memberID && Permission::checkMember($memberID, array("ADMIN", "SITETREE_EDIT_ALL"))) { | 
            ||
| 957 | return true;  | 
            ||
| 958 | }  | 
            ||
| 959 | |||
| 960 | // Standard mechanism for accepting permission changes from extensions  | 
            ||
| 961 | 		$extended = $this->extendedCan('canDelete', $memberID); | 
            ||
| 962 | if($extended !== null) return $extended;  | 
            ||
| 963 | |||
| 964 | // Regular canEdit logic is handled by can_edit_multiple  | 
            ||
| 965 | $results = self::can_delete_multiple(array($this->ID), $memberID);  | 
            ||
| 966 | |||
| 967 | // If this page no longer exists in stage/live results won't contain the page.  | 
            ||
| 968 | // Fail-over to false  | 
            ||
| 969 | return isset($results[$this->ID]) ? $results[$this->ID] : false;  | 
            ||
| 970 | }  | 
            ||
| 971 | |||
| 972 | /**  | 
            ||
| 973 | * This function should return true if the current user can create new pages of this class, regardless of class. It  | 
            ||
| 974 | * can be overloaded to customise the security model for an application.  | 
            ||
| 975 | *  | 
            ||
| 976 | * By default, permission to create at the root level is based on the SiteConfig configuration, and permission to  | 
            ||
| 977 | * create beneath a parent is based on the ability to edit that parent page.  | 
            ||
| 978 | *  | 
            ||
| 979 | 	 * Use {@link canAddChildren()} to control behaviour of creating children under this page. | 
            ||
| 980 | *  | 
            ||
| 981 | * @uses $can_create  | 
            ||
| 982 | * @uses DataExtension->canCreate()  | 
            ||
| 983 | *  | 
            ||
| 984 | * @param Member $member  | 
            ||
| 985 | 	 * @param array $context Optional array which may contain array('Parent' => $parentObj) | 
            ||
| 986 | * If a parent page is known, it will be checked for validity.  | 
            ||
| 987 | * If omitted, it will be assumed this is to be created as a top level page.  | 
            ||
| 988 | * @return bool True if the current user can create pages on this class.  | 
            ||
| 989 | */  | 
            ||
| 990 | 	public function canCreate($member = null, $context = array()) { | 
            ||
| 991 | View Code Duplication | 		if(!$member || !(is_a($member, 'Member')) || is_numeric($member)) { | 
            |
| 992 | $member = Member::currentUserID();  | 
            ||
| 993 | }  | 
            ||
| 994 | |||
| 995 | // Check parent (custom canCreate option for SiteTree)  | 
            ||
| 996 | // Block children not allowed for this parent type  | 
            ||
| 997 | $parent = isset($context['Parent']) ? $context['Parent'] : null;  | 
            ||
| 998 | 		if($parent && !in_array(get_class($this), $parent->allowedChildren())) { | 
            ||
| 999 | return false;  | 
            ||
| 1000 | }  | 
            ||
| 1001 | |||
| 1002 | // Check permission  | 
            ||
| 1003 | 		if($member && Permission::checkMember($member, "ADMIN")) { | 
            ||
| 1004 | return true;  | 
            ||
| 1005 | }  | 
            ||
| 1006 | |||
| 1007 | // Standard mechanism for accepting permission changes from extensions  | 
            ||
| 1008 | $extended = $this->extendedCan(__FUNCTION__, $member, $context);  | 
            ||
| 1009 | 		if($extended !== null) { | 
            ||
| 1010 | return $extended;  | 
            ||
| 1011 | }  | 
            ||
| 1012 | |||
| 1013 | // Fall over to inherited permissions  | 
            ||
| 1014 | 		if($parent) { | 
            ||
| 1015 | return $parent->canAddChildren($member);  | 
            ||
| 1016 | 		} else { | 
            ||
| 1017 | // This doesn't necessarily mean we are creating a root page, but that  | 
            ||
| 1018 | // we don't know if there is a parent, so default to this permission  | 
            ||
| 1019 | return SiteConfig::current_site_config()->canCreateTopLevel($member);  | 
            ||
| 1020 | }  | 
            ||
| 1021 | }  | 
            ||
| 1022 | |||
| 1023 | /**  | 
            ||
| 1024 | * This function should return true if the current user can edit this page. It can be overloaded to customise the  | 
            ||
| 1025 | * security model for an application.  | 
            ||
| 1026 | *  | 
            ||
| 1027 | * Denies permission if any of the following conditions is true:  | 
            ||
| 1028 | * - canEdit() on any extension returns false  | 
            ||
| 1029 | * - canView() return false  | 
            ||
| 1030 | * - "CanEditType" directive is set to "Inherit" and any parent page return false for canEdit()  | 
            ||
| 1031 | * - "CanEditType" directive is set to "LoggedInUsers" and no user is logged in or doesn't have the  | 
            ||
| 1032 | * CMS_Access_CMSMAIN permission code  | 
            ||
| 1033 | * - "CanEditType" directive is set to "OnlyTheseUsers" and user is not in the given groups  | 
            ||
| 1034 | *  | 
            ||
| 1035 | * @uses canView()  | 
            ||
| 1036 | * @uses EditorGroups()  | 
            ||
| 1037 | * @uses DataExtension->canEdit()  | 
            ||
| 1038 | *  | 
            ||
| 1039 | * @param Member $member Set to false if you want to explicitly test permissions without a valid user (useful for  | 
            ||
| 1040 | * unit tests)  | 
            ||
| 1041 | * @return bool True if the current user can edit this page  | 
            ||
| 1042 | */  | 
            ||
| 1043 | 	public function canEdit($member = null) { | 
            ||
| 1044 | View Code Duplication | if($member instanceof Member) $memberID = $member->ID;  | 
            |
| 1045 | else if(is_numeric($member)) $memberID = $member;  | 
            ||
| 1046 | else $memberID = Member::currentUserID();  | 
            ||
| 1047 | |||
| 1048 | 		if($memberID && Permission::checkMember($memberID, array("ADMIN", "SITETREE_EDIT_ALL"))) return true; | 
            ||
| 1049 | |||
| 1050 | // Standard mechanism for accepting permission changes from extensions  | 
            ||
| 1051 | 		$extended = $this->extendedCan('canEdit', $memberID); | 
            ||
| 1052 | if($extended !== null) return $extended;  | 
            ||
| 1053 | |||
| 1054 | 		if($this->ID) { | 
            ||
| 1055 | // Regular canEdit logic is handled by can_edit_multiple  | 
            ||
| 1056 | $results = self::can_edit_multiple(array($this->ID), $memberID);  | 
            ||
| 1057 | |||
| 1058 | // If this page no longer exists in stage/live results won't contain the page.  | 
            ||
| 1059 | // Fail-over to false  | 
            ||
| 1060 | return isset($results[$this->ID]) ? $results[$this->ID] : false;  | 
            ||
| 1061 | |||
| 1062 | // Default for unsaved pages  | 
            ||
| 1063 | 		} else { | 
            ||
| 1064 | return $this->getSiteConfig()->canEditPages($member);  | 
            ||
| 1065 | }  | 
            ||
| 1066 | }  | 
            ||
| 1067 | |||
| 1068 | /**  | 
            ||
| 1069 | * @deprecated  | 
            ||
| 1070 | */  | 
            ||
| 1071 | 	public function canDeleteFromLive($member = null) { | 
            ||
| 1072 | 		Deprecation::notice('4.0', 'Use canUnpublish'); | 
            ||
| 1073 | |||
| 1074 | // Deprecated extension  | 
            ||
| 1075 | 		$extended = $this->extendedCan('canDeleteFromLive', $member); | 
            ||
| 1076 | 		if($extended !== null) { | 
            ||
| 1077 | 			Deprecation::notice('4.0', 'Use canUnpublish in your extension instead'); | 
            ||
| 1078 | return $extended;  | 
            ||
| 1079 | }  | 
            ||
| 1080 | |||
| 1081 | return $this->canUnpublish($member);  | 
            ||
| 1082 | }  | 
            ||
| 1083 | |||
| 1084 | /**  | 
            ||
| 1085 | * Stub method to get the site config, unless the current class can provide an alternate.  | 
            ||
| 1086 | *  | 
            ||
| 1087 | * @return SiteConfig  | 
            ||
| 1088 | */  | 
            ||
| 1089 | 	public function getSiteConfig() { | 
            ||
| 1090 | |||
| 1091 | 		if($this->hasMethod('alternateSiteConfig')) { | 
            ||
| 1092 | $altConfig = $this->alternateSiteConfig();  | 
            ||
| 1093 | if($altConfig) return $altConfig;  | 
            ||
| 1094 | }  | 
            ||
| 1095 | |||
| 1096 | return SiteConfig::current_site_config();  | 
            ||
| 1097 | }  | 
            ||
| 1098 | |||
| 1099 | /**  | 
            ||
| 1100 | * Pre-populate the cache of canEdit, canView, canDelete, canPublish permissions. This method will use the static  | 
            ||
| 1101 | * can_(perm)_multiple method for efficiency.  | 
            ||
| 1102 | *  | 
            ||
| 1103 | * @param string $permission The permission: edit, view, publish, approve, etc.  | 
            ||
| 1104 | * @param array $ids An array of page IDs  | 
            ||
| 1105 | * @param callable|string $batchCallback The function/static method to call to calculate permissions. Defaults  | 
            ||
| 1106 | * to 'SiteTree::can_(permission)_multiple'  | 
            ||
| 1107 | */  | 
            ||
| 1108 | 	static public function prepopulate_permission_cache($permission = 'CanEditType', $ids, $batchCallback = null) { | 
            ||
| 1109 | 		if(!$batchCallback) $batchCallback = "SiteTree::can_{$permission}_multiple"; | 
            ||
| 1110 | |||
| 1111 | 		if(is_callable($batchCallback)) { | 
            ||
| 1112 | call_user_func($batchCallback, $ids, Member::currentUserID(), false);  | 
            ||
| 1113 | 		} else { | 
            ||
| 1114 | 			user_error("SiteTree::prepopulate_permission_cache can't calculate '$permission' " | 
            ||
| 1115 | . "with callback '$batchCallback'", E_USER_WARNING);  | 
            ||
| 1116 | }  | 
            ||
| 1117 | }  | 
            ||
| 1118 | |||
| 1119 | /**  | 
            ||
| 1120 | 	 * This method is NOT a full replacement for the individual can*() methods, e.g. {@link canEdit()}. Rather than | 
            ||
| 1121 | * checking (potentially slow) PHP logic, it relies on the database group associations, e.g. the "CanEditType" field  | 
            ||
| 1122 | * plus the "SiteTree_EditorGroups" many-many table. By batch checking multiple records, we can combine the queries  | 
            ||
| 1123 | * efficiently.  | 
            ||
| 1124 | *  | 
            ||
| 1125 | 	 * Caches based on $typeField data. To invalidate the cache, use {@link SiteTree::reset()} or set the $useCached | 
            ||
| 1126 | * property to FALSE.  | 
            ||
| 1127 | *  | 
            ||
| 1128 | 	 * @param array  $ids              Of {@link SiteTree} IDs | 
            ||
| 1129 | * @param int $memberID Member ID  | 
            ||
| 1130 | * @param string $typeField A property on the data record, e.g. "CanEditType".  | 
            ||
| 1131 | * @param string $groupJoinTable A many-many table name on this record, e.g. "SiteTree_EditorGroups"  | 
            ||
| 1132 | 	 * @param string $siteConfigMethod Method to call on {@link SiteConfig} for toplevel items, e.g. "canEdit" | 
            ||
| 1133 | * @param string $globalPermission If the member doesn't have this permission code, don't bother iterating deeper  | 
            ||
| 1134 | * @param bool $useCached  | 
            ||
| 1135 | 	 * @return array An map of {@link SiteTree} ID keys to boolean values | 
            ||
| 1136 | */  | 
            ||
| 1137 | public static function batch_permission_check($ids, $memberID, $typeField, $groupJoinTable, $siteConfigMethod,  | 
            ||
| 1138 | 												  $globalPermission = null, $useCached = true) { | 
            ||
| 1139 | 		if($globalPermission === NULL) $globalPermission = array('CMS_ACCESS_LeftAndMain', 'CMS_ACCESS_CMSMain'); | 
            ||
| 1140 | |||
| 1141 | // Sanitise the IDs  | 
            ||
| 1142 | $ids = array_filter($ids, 'is_numeric');  | 
            ||
| 1143 | |||
| 1144 | // This is the name used on the permission cache  | 
            ||
| 1145 | // converts something like 'CanEditType' to 'edit'.  | 
            ||
| 1146 | $cacheKey = strtolower(substr($typeField, 3, -4)) . "-$memberID";  | 
            ||
| 1147 | |||
| 1148 | // Default result: nothing editable  | 
            ||
| 1149 | $result = array_fill_keys($ids, false);  | 
            ||
| 1150 | 		if($ids) { | 
            ||
| 1151 | |||
| 1152 | // Look in the cache for values  | 
            ||
| 1153 | 			if($useCached && isset(self::$cache_permissions[$cacheKey])) { | 
            ||
| 1154 | $cachedValues = array_intersect_key(self::$cache_permissions[$cacheKey], $result);  | 
            ||
| 1155 | |||
| 1156 | // If we can't find everything in the cache, then look up the remainder separately  | 
            ||
| 1157 | $uncachedValues = array_diff_key($result, self::$cache_permissions[$cacheKey]);  | 
            ||
| 1158 | 				if($uncachedValues) { | 
            ||
| 1159 | $cachedValues = self::batch_permission_check(array_keys($uncachedValues), $memberID, $typeField, $groupJoinTable, $siteConfigMethod, $globalPermission, false) + $cachedValues;  | 
            ||
| 1160 | }  | 
            ||
| 1161 | return $cachedValues;  | 
            ||
| 1162 | }  | 
            ||
| 1163 | |||
| 1164 | // If a member doesn't have a certain permission then they can't edit anything  | 
            ||
| 1165 | 			if(!$memberID || ($globalPermission && !Permission::checkMember($memberID, $globalPermission))) { | 
            ||
| 1166 | return $result;  | 
            ||
| 1167 | }  | 
            ||
| 1168 | |||
| 1169 | // Placeholder for parameterised ID list  | 
            ||
| 1170 | $idPlaceholders = DB::placeholders($ids);  | 
            ||
| 1171 | |||
| 1172 | // If page can't be viewed, don't grant edit permissions to do - implement can_view_multiple(), so this can  | 
            ||
| 1173 | // be enabled  | 
            ||
| 1174 | //$ids = array_keys(array_filter(self::can_view_multiple($ids, $memberID)));  | 
            ||
| 1175 | |||
| 1176 | // Get the groups that the given member belongs to  | 
            ||
| 1177 | 			$groupIDs = DataObject::get_by_id('Member', $memberID)->Groups()->column("ID"); | 
            ||
| 1178 | 			$SQL_groupList = implode(", ", $groupIDs); | 
            ||
| 1179 | if (!$SQL_groupList) $SQL_groupList = '0';  | 
            ||
| 1180 | |||
| 1181 | $combinedStageResult = array();  | 
            ||
| 1182 | |||
| 1183 | 			foreach(array('Stage', 'Live') as $stage) { | 
            ||
| 1184 | // Start by filling the array with the pages that actually exist  | 
            ||
| 1185 | $table = ($stage=='Stage') ? "SiteTree" : "SiteTree_$stage";  | 
            ||
| 1186 | |||
| 1187 | 				if($ids) { | 
            ||
| 1188 | $idQuery = "SELECT \"ID\" FROM \"$table\" WHERE \"ID\" IN ($idPlaceholders)";  | 
            ||
| 1189 | $stageIds = DB::prepared_query($idQuery, $ids)->column();  | 
            ||
| 1190 | 				} else { | 
            ||
| 1191 | $stageIds = array();  | 
            ||
| 1192 | }  | 
            ||
| 1193 | $result = array_fill_keys($stageIds, false);  | 
            ||
| 1194 | |||
| 1195 | // Get the uninherited permissions  | 
            ||
| 1196 | 				$uninheritedPermissions = Versioned::get_by_stage("SiteTree", $stage) | 
            ||
| 1197 | ->where(array(  | 
            ||
| 1198 | "(\"$typeField\" = 'LoggedInUsers' OR  | 
            ||
| 1199 | (\"$typeField\" = 'OnlyTheseUsers' AND \"$groupJoinTable\".\"SiteTreeID\" IS NOT NULL))  | 
            ||
| 1200 | AND \"SiteTree\".\"ID\" IN ($idPlaceholders)"  | 
            ||
| 1201 | => $ids  | 
            ||
| 1202 | ))  | 
            ||
| 1203 | ->leftJoin($groupJoinTable, "\"$groupJoinTable\".\"SiteTreeID\" = \"SiteTree\".\"ID\" AND \"$groupJoinTable\".\"GroupID\" IN ($SQL_groupList)");  | 
            ||
| 1204 | |||
| 1205 | 				if($uninheritedPermissions) { | 
            ||
| 1206 | // Set all the relevant items in $result to true  | 
            ||
| 1207 | 					$result = array_fill_keys($uninheritedPermissions->column('ID'), true) + $result; | 
            ||
| 1208 | }  | 
            ||
| 1209 | |||
| 1210 | // Get permissions that are inherited  | 
            ||
| 1211 | $potentiallyInherited = Versioned::get_by_stage(  | 
            ||
| 1212 | "SiteTree",  | 
            ||
| 1213 | $stage,  | 
            ||
| 1214 | 					array("\"$typeField\" = 'Inherit' AND \"SiteTree\".\"ID\" IN ($idPlaceholders)" => $ids) | 
            ||
| 1215 | );  | 
            ||
| 1216 | |||
| 1217 | 				if($potentiallyInherited) { | 
            ||
| 1218 | // Group $potentiallyInherited by ParentID; we'll look at the permission of all those parents and  | 
            ||
| 1219 | // then see which ones the user has permission on  | 
            ||
| 1220 | $groupedByParent = array();  | 
            ||
| 1221 | 					foreach($potentiallyInherited as $item) { | 
            ||
| 1222 | 						if($item->ParentID) { | 
            ||
| 1223 | if(!isset($groupedByParent[$item->ParentID])) $groupedByParent[$item->ParentID] = array();  | 
            ||
| 1224 | $groupedByParent[$item->ParentID][] = $item->ID;  | 
            ||
| 1225 | 						} else { | 
            ||
| 1226 | // Might return different site config based on record context, e.g. when subsites module  | 
            ||
| 1227 | // is used  | 
            ||
| 1228 | $siteConfig = $item->getSiteConfig();  | 
            ||
| 1229 | 							$result[$item->ID] = $siteConfig->{$siteConfigMethod}($memberID); | 
            ||
| 1230 | }  | 
            ||
| 1231 | }  | 
            ||
| 1232 | |||
| 1233 | 					if($groupedByParent) { | 
            ||
| 1234 | $actuallyInherited = self::batch_permission_check(array_keys($groupedByParent), $memberID, $typeField, $groupJoinTable, $siteConfigMethod);  | 
            ||
| 1235 | 						if($actuallyInherited) { | 
            ||
| 1236 | $parentIDs = array_keys(array_filter($actuallyInherited));  | 
            ||
| 1237 | 							foreach($parentIDs as $parentID) { | 
            ||
| 1238 | // Set all the relevant items in $result to true  | 
            ||
| 1239 | $result = array_fill_keys($groupedByParent[$parentID], true) + $result;  | 
            ||
| 1240 | }  | 
            ||
| 1241 | }  | 
            ||
| 1242 | }  | 
            ||
| 1243 | }  | 
            ||
| 1244 | |||
| 1245 | $combinedStageResult = $combinedStageResult + $result;  | 
            ||
| 1246 | |||
| 1247 | }  | 
            ||
| 1248 | }  | 
            ||
| 1249 | |||
| 1250 | 		if(isset($combinedStageResult)) { | 
            ||
| 1251 | // Cache the results  | 
            ||
| 1252 | if(empty(self::$cache_permissions[$cacheKey])) self::$cache_permissions[$cacheKey] = array();  | 
            ||
| 1253 | self::$cache_permissions[$cacheKey] = $combinedStageResult + self::$cache_permissions[$cacheKey];  | 
            ||
| 1254 | |||
| 1255 | return $combinedStageResult;  | 
            ||
| 1256 | 		} else { | 
            ||
| 1257 | return array();  | 
            ||
| 1258 | }  | 
            ||
| 1259 | }  | 
            ||
| 1260 | |||
| 1261 | /**  | 
            ||
| 1262 | * Get the 'can edit' information for a number of SiteTree pages.  | 
            ||
| 1263 | *  | 
            ||
| 1264 | * @param array $ids An array of IDs of the SiteTree pages to look up  | 
            ||
| 1265 | * @param int $memberID ID of member  | 
            ||
| 1266 | * @param bool $useCached Return values from the permission cache if they exist  | 
            ||
| 1267 | * @return array A map where the IDs are keys and the values are booleans stating whether the given page can be  | 
            ||
| 1268 | * edited  | 
            ||
| 1269 | */  | 
            ||
| 1270 | 	static public function can_edit_multiple($ids, $memberID, $useCached = true) { | 
            ||
| 1271 | return self::batch_permission_check($ids, $memberID, 'CanEditType', 'SiteTree_EditorGroups', 'canEditPages', null, $useCached);  | 
            ||
| 1272 | }  | 
            ||
| 1273 | |||
| 1274 | /**  | 
            ||
| 1275 | * Get the 'can edit' information for a number of SiteTree pages.  | 
            ||
| 1276 | *  | 
            ||
| 1277 | * @param array $ids An array of IDs of the SiteTree pages to look up  | 
            ||
| 1278 | * @param int $memberID ID of member  | 
            ||
| 1279 | * @param bool $useCached Return values from the permission cache if they exist  | 
            ||
| 1280 | * @return array  | 
            ||
| 1281 | */  | 
            ||
| 1282 | 	static public function can_delete_multiple($ids, $memberID, $useCached = true) { | 
            ||
| 1283 | $deletable = array();  | 
            ||
| 1284 | $result = array_fill_keys($ids, false);  | 
            ||
| 1285 | $cacheKey = "delete-$memberID";  | 
            ||
| 1286 | |||
| 1287 | // Look in the cache for values  | 
            ||
| 1288 | 		if($useCached && isset(self::$cache_permissions[$cacheKey])) { | 
            ||
| 1289 | $cachedValues = array_intersect_key(self::$cache_permissions[$cacheKey], $result);  | 
            ||
| 1290 | |||
| 1291 | // If we can't find everything in the cache, then look up the remainder separately  | 
            ||
| 1292 | $uncachedValues = array_diff_key($result, self::$cache_permissions[$cacheKey]);  | 
            ||
| 1293 | 			if($uncachedValues) { | 
            ||
| 1294 | $cachedValues = self::can_delete_multiple(array_keys($uncachedValues), $memberID, false)  | 
            ||
| 1295 | + $cachedValues;  | 
            ||
| 1296 | }  | 
            ||
| 1297 | return $cachedValues;  | 
            ||
| 1298 | }  | 
            ||
| 1299 | |||
| 1300 | // You can only delete pages that you can edit  | 
            ||
| 1301 | $editableIDs = array_keys(array_filter(self::can_edit_multiple($ids, $memberID)));  | 
            ||
| 1302 | 		if($editableIDs) { | 
            ||
| 1303 | |||
| 1304 | // You can only delete pages whose children you can delete  | 
            ||
| 1305 | $editablePlaceholders = DB::placeholders($editableIDs);  | 
            ||
| 1306 | $childRecords = SiteTree::get()->where(array(  | 
            ||
| 1307 | "\"SiteTree\".\"ParentID\" IN ($editablePlaceholders)" => $editableIDs  | 
            ||
| 1308 | ));  | 
            ||
| 1309 | 			if($childRecords) { | 
            ||
| 1310 | 				$children = $childRecords->map("ID", "ParentID"); | 
            ||
| 1311 | |||
| 1312 | // Find out the children that can be deleted  | 
            ||
| 1313 | $deletableChildren = self::can_delete_multiple($children->keys(), $memberID);  | 
            ||
| 1314 | |||
| 1315 | // Get a list of all the parents that have no undeletable children  | 
            ||
| 1316 | $deletableParents = array_fill_keys($editableIDs, true);  | 
            ||
| 1317 | 				foreach($deletableChildren as $id => $canDelete) { | 
            ||
| 1318 | if(!$canDelete) unset($deletableParents[$children[$id]]);  | 
            ||
| 1319 | }  | 
            ||
| 1320 | |||
| 1321 | // Use that to filter the list of deletable parents that have children  | 
            ||
| 1322 | $deletableParents = array_keys($deletableParents);  | 
            ||
| 1323 | |||
| 1324 | // Also get the $ids that don't have children  | 
            ||
| 1325 | $parents = array_unique($children->values());  | 
            ||
| 1326 | $deletableLeafNodes = array_diff($editableIDs, $parents);  | 
            ||
| 1327 | |||
| 1328 | // Combine the two  | 
            ||
| 1329 | $deletable = array_merge($deletableParents, $deletableLeafNodes);  | 
            ||
| 1330 | |||
| 1331 | 			} else { | 
            ||
| 1332 | $deletable = $editableIDs;  | 
            ||
| 1333 | }  | 
            ||
| 1334 | 		} else { | 
            ||
| 1335 | $deletable = array();  | 
            ||
| 1336 | }  | 
            ||
| 1337 | |||
| 1338 | // Convert the array of deletable IDs into a map of the original IDs with true/false as the value  | 
            ||
| 1339 | return array_fill_keys($deletable, true) + array_fill_keys($ids, false);  | 
            ||
| 1340 | }  | 
            ||
| 1341 | |||
| 1342 | /**  | 
            ||
| 1343 | * Collate selected descendants of this page.  | 
            ||
| 1344 | *  | 
            ||
| 1345 | 	 * {@link $condition} will be evaluated on each descendant, and if it is succeeds, that item will be added to the | 
            ||
| 1346 | * $collator array.  | 
            ||
| 1347 | *  | 
            ||
| 1348 | * @param string $condition The PHP condition to be evaluated. The page will be called $item  | 
            ||
| 1349 | * @param array $collator An array, passed by reference, to collect all of the matching descendants.  | 
            ||
| 1350 | * @return bool  | 
            ||
| 1351 | */  | 
            ||
| 1352 | 	public function collateDescendants($condition, &$collator) { | 
            ||
| 1353 | 		if($children = $this->Children()) { | 
            ||
| 1354 | 			foreach($children as $item) { | 
            ||
| 1355 | 				if(eval("return $condition;")) $collator[] = $item; | 
            ||
| 1356 | $item->collateDescendants($condition, $collator);  | 
            ||
| 1357 | }  | 
            ||
| 1358 | return true;  | 
            ||
| 1359 | }  | 
            ||
| 1360 | }  | 
            ||
| 1361 | |||
| 1362 | /**  | 
            ||
| 1363 | * Return the title, description, keywords and language metatags.  | 
            ||
| 1364 | *  | 
            ||
| 1365 | * @todo Move <title> tag in separate getter for easier customization and more obvious usage  | 
            ||
| 1366 | *  | 
            ||
| 1367 | * @param bool $includeTitle Show default <title>-tag, set to false for custom templating  | 
            ||
| 1368 | * @return string The XHTML metatags  | 
            ||
| 1369 | */  | 
            ||
| 1370 | 	public function MetaTags($includeTitle = true) { | 
            ||
| 1371 | $tags = "";  | 
            ||
| 1372 | 		if($includeTitle === true || $includeTitle == 'true') { | 
            ||
| 1373 | $tags .= "<title>" . Convert::raw2xml($this->Title) . "</title>\n";  | 
            ||
| 1374 | }  | 
            ||
| 1375 | |||
| 1376 | 		$generator = trim(Config::inst()->get('SiteTree', 'meta_generator')); | 
            ||
| 1377 | 		if (!empty($generator)) { | 
            ||
| 1378 | $tags .= "<meta name=\"generator\" content=\"" . Convert::raw2att($generator) . "\" />\n";  | 
            ||
| 1379 | }  | 
            ||
| 1380 | |||
| 1381 | 		$charset = Config::inst()->get('ContentNegotiator', 'encoding'); | 
            ||
| 1382 | $tags .= "<meta http-equiv=\"Content-type\" content=\"text/html; charset=$charset\" />\n";  | 
            ||
| 1383 | 		if($this->MetaDescription) { | 
            ||
| 1384 | $tags .= "<meta name=\"description\" content=\"" . Convert::raw2att($this->MetaDescription) . "\" />\n";  | 
            ||
| 1385 | }  | 
            ||
| 1386 | 		if($this->ExtraMeta) { | 
            ||
| 1387 | $tags .= $this->ExtraMeta . "\n";  | 
            ||
| 1388 | }  | 
            ||
| 1389 | |||
| 1390 | 		if(Permission::check('CMS_ACCESS_CMSMain') | 
            ||
| 1391 | 			&& in_array('CMSPreviewable', class_implements($this)) | 
            ||
| 1392 | && !$this instanceof ErrorPage  | 
            ||
| 1393 | && $this->ID > 0  | 
            ||
| 1394 | 		) { | 
            ||
| 1395 | 			$tags .= "<meta name=\"x-page-id\" content=\"{$this->ID}\" />\n"; | 
            ||
| 1396 | $tags .= "<meta name=\"x-cms-edit-link\" content=\"" . $this->CMSEditLink() . "\" />\n";  | 
            ||
| 1397 | }  | 
            ||
| 1398 | |||
| 1399 | 		$this->extend('MetaTags', $tags); | 
            ||
| 1400 | |||
| 1401 | return $tags;  | 
            ||
| 1402 | }  | 
            ||
| 1403 | |||
| 1404 | /**  | 
            ||
| 1405 | * Returns the object that contains the content that a user would associate with this page.  | 
            ||
| 1406 | *  | 
            ||
| 1407 | * Ordinarily, this is just the page itself, but for example on RedirectorPages or VirtualPages ContentSource() will  | 
            ||
| 1408 | * return the page that is linked to.  | 
            ||
| 1409 | *  | 
            ||
| 1410 | * @return $this  | 
            ||
| 1411 | */  | 
            ||
| 1412 | 	public function ContentSource() { | 
            ||
| 1413 | return $this;  | 
            ||
| 1414 | }  | 
            ||
| 1415 | |||
| 1416 | /**  | 
            ||
| 1417 | * Add default records to database.  | 
            ||
| 1418 | *  | 
            ||
| 1419 | * This function is called whenever the database is built, after the database tables have all been created. Overload  | 
            ||
| 1420 | * this to add default records when the database is built, but make sure you call parent::requireDefaultRecords().  | 
            ||
| 1421 | */  | 
            ||
| 1422 | 	public function requireDefaultRecords() { | 
            ||
| 1423 | parent::requireDefaultRecords();  | 
            ||
| 1424 | |||
| 1425 | // default pages  | 
            ||
| 1426 | 		if($this->class == 'SiteTree' && $this->config()->create_default_pages) { | 
            ||
| 1427 | 			if(!SiteTree::get_by_link(Config::inst()->get('RootURLController', 'default_homepage_link'))) { | 
            ||
| 1428 | $homepage = new Page();  | 
            ||
| 1429 | 				$homepage->Title = _t('SiteTree.DEFAULTHOMETITLE', 'Home'); | 
            ||
| 1430 | 				$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>'); | 
            ||
| 1431 | 				$homepage->URLSegment = Config::inst()->get('RootURLController', 'default_homepage_link'); | 
            ||
| 1432 | $homepage->Sort = 1;  | 
            ||
| 1433 | $homepage->write();  | 
            ||
| 1434 | 				$homepage->publish('Stage', 'Live'); | 
            ||
| 1435 | $homepage->flushCache();  | 
            ||
| 1436 | 				DB::alteration_message('Home page created', 'created'); | 
            ||
| 1437 | }  | 
            ||
| 1438 | |||
| 1439 | 			if(DB::query("SELECT COUNT(*) FROM \"SiteTree\"")->value() == 1) { | 
            ||
| 1440 | $aboutus = new Page();  | 
            ||
| 1441 | 				$aboutus->Title = _t('SiteTree.DEFAULTABOUTTITLE', 'About Us'); | 
            ||
| 1442 | 				$aboutus->Content = _t('SiteTree.DEFAULTABOUTCONTENT', '<p>You can fill this page out with your own content, or delete it and create your own pages.<br /></p>'); | 
            ||
| 1443 | $aboutus->Sort = 2;  | 
            ||
| 1444 | $aboutus->write();  | 
            ||
| 1445 | 				$aboutus->publish('Stage', 'Live'); | 
            ||
| 1446 | $aboutus->flushCache();  | 
            ||
| 1447 | 				DB::alteration_message('About Us page created', 'created'); | 
            ||
| 1448 | |||
| 1449 | $contactus = new Page();  | 
            ||
| 1450 | 				$contactus->Title = _t('SiteTree.DEFAULTCONTACTTITLE', 'Contact Us'); | 
            ||
| 1451 | 				$contactus->Content = _t('SiteTree.DEFAULTCONTACTCONTENT', '<p>You can fill this page out with your own content, or delete it and create your own pages.<br /></p>'); | 
            ||
| 1452 | $contactus->Sort = 3;  | 
            ||
| 1453 | $contactus->write();  | 
            ||
| 1454 | 				$contactus->publish('Stage', 'Live'); | 
            ||
| 1455 | $contactus->flushCache();  | 
            ||
| 1456 | 				DB::alteration_message('Contact Us page created', 'created'); | 
            ||
| 1457 | }  | 
            ||
| 1458 | }  | 
            ||
| 1459 | |||
| 1460 | // schema migration  | 
            ||
| 1461 | // @todo Move to migration task once infrastructure is implemented  | 
            ||
| 1462 | 		if($this->class == 'SiteTree') { | 
            ||
| 1463 | $conn = DB::get_schema();  | 
            ||
| 1464 | // only execute command if fields haven't been renamed to _obsolete_<fieldname> already by the task  | 
            ||
| 1465 | 			if($conn->hasField('SiteTree' ,'Viewers')) { | 
            ||
| 1466 | $task = new UpgradeSiteTreePermissionSchemaTask();  | 
            ||
| 1467 | 				$task->run(new SS_HTTPRequest('GET','/')); | 
            ||
| 1468 | }  | 
            ||
| 1469 | }  | 
            ||
| 1470 | }  | 
            ||
| 1471 | |||
| 1472 | 	protected function onBeforeWrite() { | 
            ||
| 1473 | parent::onBeforeWrite();  | 
            ||
| 1474 | |||
| 1475 | // If Sort hasn't been set, make this page come after it's siblings  | 
            ||
| 1476 | 		if(!$this->Sort) { | 
            ||
| 1477 | $parentID = ($this->ParentID) ? $this->ParentID : 0;  | 
            ||
| 1478 | $this->Sort = DB::prepared_query(  | 
            ||
| 1479 | "SELECT MAX(\"Sort\") + 1 FROM \"SiteTree\" WHERE \"ParentID\" = ?",  | 
            ||
| 1480 | array($parentID)  | 
            ||
| 1481 | )->value();  | 
            ||
| 1482 | }  | 
            ||
| 1483 | |||
| 1484 | // If there is no URLSegment set, generate one from Title  | 
            ||
| 1485 | $defaultSegment = $this->generateURLSegment(_t(  | 
            ||
| 1486 | 'CMSMain.NEWPAGE',  | 
            ||
| 1487 | 			array('pagetype' => $this->i18n_singular_name()) | 
            ||
| 1488 | ));  | 
            ||
| 1489 | 		if((!$this->URLSegment || $this->URLSegment == $defaultSegment) && $this->Title) { | 
            ||
| 1490 | $this->URLSegment = $this->generateURLSegment($this->Title);  | 
            ||
| 1491 | 		} else if($this->isChanged('URLSegment', 2)) { | 
            ||
| 1492 | // Do a strict check on change level, to avoid double encoding caused by  | 
            ||
| 1493 | // bogus changes through forceChange()  | 
            ||
| 1494 | $filter = URLSegmentFilter::create();  | 
            ||
| 1495 | $this->URLSegment = $filter->filter($this->URLSegment);  | 
            ||
| 1496 | // If after sanitising there is no URLSegment, give it a reasonable default  | 
            ||
| 1497 | if(!$this->URLSegment) $this->URLSegment = "page-$this->ID";  | 
            ||
| 1498 | }  | 
            ||
| 1499 | |||
| 1500 | // Ensure that this object has a non-conflicting URLSegment value.  | 
            ||
| 1501 | $count = 2;  | 
            ||
| 1502 | 		while(!$this->validURLSegment()) { | 
            ||
| 1503 | 			$this->URLSegment = preg_replace('/-[0-9]+$/', null, $this->URLSegment) . '-' . $count; | 
            ||
| 1504 | $count++;  | 
            ||
| 1505 | }  | 
            ||
| 1506 | |||
| 1507 | $this->syncLinkTracking();  | 
            ||
| 1508 | |||
| 1509 | // Check to see if we've only altered fields that shouldn't affect versioning  | 
            ||
| 1510 | 		$fieldsIgnoredByVersioning = array('HasBrokenLink', 'Status', 'HasBrokenFile', 'ToDo', 'VersionID', 'SaveCount'); | 
            ||
| 1511 | $changedFields = array_keys($this->getChangedFields(true, 2));  | 
            ||
| 1512 | |||
| 1513 | // This more rigorous check is inline with the test that write() does to dedcide whether or not to write to the  | 
            ||
| 1514 | // DB. We use that to avoid cluttering the system with a migrateVersion() call that doesn't get used  | 
            ||
| 1515 | $oneChangedFields = array_keys($this->getChangedFields(true, 1));  | 
            ||
| 1516 | |||
| 1517 | 		if($oneChangedFields && !array_diff($changedFields, $fieldsIgnoredByVersioning)) { | 
            ||
| 1518 | // This will have the affect of preserving the versioning  | 
            ||
| 1519 | $this->migrateVersion($this->Version);  | 
            ||
| 1520 | }  | 
            ||
| 1521 | }  | 
            ||
| 1522 | |||
| 1523 | /**  | 
            ||
| 1524 | * Trigger synchronisation of link tracking  | 
            ||
| 1525 | *  | 
            ||
| 1526 | 	 * {@see SiteTreeLinkTracking::augmentSyncLinkTracking} | 
            ||
| 1527 | */  | 
            ||
| 1528 | 	public function syncLinkTracking() { | 
            ||
| 1529 | 		$this->extend('augmentSyncLinkTracking'); | 
            ||
| 1530 | }  | 
            ||
| 1531 | |||
| 1532 | 	public function onAfterWrite() { | 
            ||
| 1533 | // Need to flush cache to avoid outdated versionnumber references  | 
            ||
| 1534 | $this->flushCache();  | 
            ||
| 1535 | |||
| 1536 | $linkedPages = $this->VirtualPages();  | 
            ||
| 1537 | 		if($linkedPages) { | 
            ||
| 1538 | // The only way after a write() call to determine if it was triggered by a writeWithoutVersion(),  | 
            ||
| 1539 | // which we have to pass on to the virtual page writes as well.  | 
            ||
| 1540 | $previous = ($this->Version > 1) ? Versioned::get_version($this->class, $this->ID, $this->Version-1) : null;  | 
            ||
| 1541 | 			$withoutVersion = $this->getExtensionInstance('Versioned')->_nextWriteWithoutVersion; | 
            ||
| 1542 | 			foreach($linkedPages as $page) { | 
            ||
| 1543 | $page->copyFrom($page->CopyContentFrom());  | 
            ||
| 1544 | if($withoutVersion) $page->writeWithoutVersion();  | 
            ||
| 1545 | else $page->write();  | 
            ||
| 1546 | }  | 
            ||
| 1547 | }  | 
            ||
| 1548 | |||
| 1549 | parent::onAfterWrite();  | 
            ||
| 1550 | }  | 
            ||
| 1551 | |||
| 1552 | 	public function onBeforeDelete() { | 
            ||
| 1553 | parent::onBeforeDelete();  | 
            ||
| 1554 | |||
| 1555 | // If deleting this page, delete all its children.  | 
            ||
| 1556 | 		if(SiteTree::config()->enforce_strict_hierarchy && $children = $this->AllChildren()) { | 
            ||
| 1557 | 			foreach($children as $child) { | 
            ||
| 1558 | $child->delete();  | 
            ||
| 1559 | }  | 
            ||
| 1560 | }  | 
            ||
| 1561 | }  | 
            ||
| 1562 | |||
| 1563 | 	public function onAfterDelete() { | 
            ||
| 1564 | // Need to flush cache to avoid outdated versionnumber references  | 
            ||
| 1565 | $this->flushCache();  | 
            ||
| 1566 | |||
| 1567 | // Need to mark pages depending to this one as broken  | 
            ||
| 1568 | $dependentPages = $this->DependentPages();  | 
            ||
| 1569 | 		if($dependentPages) foreach($dependentPages as $page) { | 
            ||
| 1570 | // $page->write() calls syncLinkTracking, which does all the hard work for us.  | 
            ||
| 1571 | $page->write();  | 
            ||
| 1572 | }  | 
            ||
| 1573 | |||
| 1574 | parent::onAfterDelete();  | 
            ||
| 1575 | }  | 
            ||
| 1576 | |||
| 1577 | 	public function flushCache($persistent = true) { | 
            ||
| 1578 | parent::flushCache($persistent);  | 
            ||
| 1579 | $this->_cache_statusFlags = null;  | 
            ||
| 1580 | }  | 
            ||
| 1581 | |||
| 1582 | 	public function validate() { | 
            ||
| 1583 | $result = parent::validate();  | 
            ||
| 1584 | |||
| 1585 | // Allowed children validation  | 
            ||
| 1586 | $parent = $this->getParent();  | 
            ||
| 1587 | 		if($parent && $parent->exists()) { | 
            ||
| 1588 | // No need to check for subclasses or instanceof, as allowedChildren() already  | 
            ||
| 1589 | // deconstructs any inheritance trees already.  | 
            ||
| 1590 | $allowed = $parent->allowedChildren();  | 
            ||
| 1591 | $subject = ($this instanceof VirtualPage && $this->CopyContentFromID) ? $this->CopyContentFrom() : $this;  | 
            ||
| 1592 | 			if(!in_array($subject->ClassName, $allowed)) { | 
            ||
| 1593 | |||
| 1594 | $result->error(  | 
            ||
| 1595 | _t(  | 
            ||
| 1596 | 'SiteTree.PageTypeNotAllowed',  | 
            ||
| 1597 | 						'Page type "{type}" not allowed as child of this parent page', | 
            ||
| 1598 | 						array('type' => $subject->i18n_singular_name()) | 
            ||
| 1599 | ),  | 
            ||
| 1600 | 'ALLOWED_CHILDREN'  | 
            ||
| 1601 | );  | 
            ||
| 1602 | }  | 
            ||
| 1603 | }  | 
            ||
| 1604 | |||
| 1605 | // "Can be root" validation  | 
            ||
| 1606 | View Code Duplication | 		if(!$this->stat('can_be_root') && !$this->ParentID) { | 
            |
| 1607 | $result->error(  | 
            ||
| 1608 | _t(  | 
            ||
| 1609 | 'SiteTree.PageTypNotAllowedOnRoot',  | 
            ||
| 1610 | 					'Page type "{type}" is not allowed on the root level', | 
            ||
| 1611 | 					array('type' => $this->i18n_singular_name()) | 
            ||
| 1612 | ),  | 
            ||
| 1613 | 'CAN_BE_ROOT'  | 
            ||
| 1614 | );  | 
            ||
| 1615 | }  | 
            ||
| 1616 | |||
| 1617 | return $result;  | 
            ||
| 1618 | }  | 
            ||
| 1619 | |||
| 1620 | /**  | 
            ||
| 1621 | * Returns true if this object has a URLSegment value that does not conflict with any other objects. This method  | 
            ||
| 1622 | * checks for:  | 
            ||
| 1623 | * - A page with the same URLSegment that has a conflict  | 
            ||
| 1624 | * - Conflicts with actions on the parent page  | 
            ||
| 1625 | * - A conflict caused by a root page having the same URLSegment as a class name  | 
            ||
| 1626 | *  | 
            ||
| 1627 | * @return bool  | 
            ||
| 1628 | */  | 
            ||
| 1629 | 	public function validURLSegment() { | 
            ||
| 1630 | 		if(self::config()->nested_urls && $parent = $this->Parent()) { | 
            ||
| 1631 | 			if($controller = ModelAsController::controller_for($parent)) { | 
            ||
| 1632 | if($controller instanceof Controller && $controller->hasAction($this->URLSegment)) return false;  | 
            ||
| 1633 | }  | 
            ||
| 1634 | }  | 
            ||
| 1635 | |||
| 1636 | 		if(!self::config()->nested_urls || !$this->ParentID) { | 
            ||
| 1637 | if(class_exists($this->URLSegment) && is_subclass_of($this->URLSegment, 'RequestHandler')) return false;  | 
            ||
| 1638 | }  | 
            ||
| 1639 | |||
| 1640 | // Filters by url, id, and parent  | 
            ||
| 1641 | 		$filter = array('"SiteTree"."URLSegment"' => $this->URLSegment); | 
            ||
| 1642 | 		if($this->ID) { | 
            ||
| 1643 | $filter['"SiteTree"."ID" <> ?'] = $this->ID;  | 
            ||
| 1644 | }  | 
            ||
| 1645 | 		if(self::config()->nested_urls) { | 
            ||
| 1646 | $filter['"SiteTree"."ParentID"'] = $this->ParentID ? $this->ParentID : 0;  | 
            ||
| 1647 | }  | 
            ||
| 1648 | |||
| 1649 | $votes = array_filter(  | 
            ||
| 1650 | 			(array)$this->extend('augmentValidURLSegment'), | 
            ||
| 1651 | 			function($v) {return !is_null($v);} | 
            ||
| 1652 | );  | 
            ||
| 1653 | 		if($votes) { | 
            ||
| 1654 | return min($votes);  | 
            ||
| 1655 | }  | 
            ||
| 1656 | |||
| 1657 | // Check existence  | 
            ||
| 1658 | 		$existingPage = DataObject::get_one('SiteTree', $filter); | 
            ||
| 1659 | if ($existingPage) return false;  | 
            ||
| 1660 | |||
| 1661 | return !($existingPage);  | 
            ||
| 1662 | }  | 
            ||
| 1663 | |||
| 1664 | /**  | 
            ||
| 1665 | * Generate a URL segment based on the title provided.  | 
            ||
| 1666 | *  | 
            ||
| 1667 | 	 * If {@link Extension}s wish to alter URL segment generation, they can do so by defining | 
            ||
| 1668 | * updateURLSegment(&$url, $title). $url will be passed by reference and should be modified. $title will contain  | 
            ||
| 1669 | * the title that was originally used as the source of this generated URL. This lets extensions either start from  | 
            ||
| 1670 | * scratch, or incrementally modify the generated URL.  | 
            ||
| 1671 | *  | 
            ||
| 1672 | * @param string $title Page title  | 
            ||
| 1673 | * @return string Generated url segment  | 
            ||
| 1674 | */  | 
            ||
| 1675 | 	public function generateURLSegment($title){ | 
            ||
| 1676 | $filter = URLSegmentFilter::create();  | 
            ||
| 1677 | $t = $filter->filter($title);  | 
            ||
| 1678 | |||
| 1679 | // Fallback to generic page name if path is empty (= no valid, convertable characters)  | 
            ||
| 1680 | if(!$t || $t == '-' || $t == '-1') $t = "page-$this->ID";  | 
            ||
| 1681 | |||
| 1682 | // Hook for extensions  | 
            ||
| 1683 | 		$this->extend('updateURLSegment', $t, $title); | 
            ||
| 1684 | |||
| 1685 | return $t;  | 
            ||
| 1686 | }  | 
            ||
| 1687 | |||
| 1688 | /**  | 
            ||
| 1689 | * Gets the URL segment for the latest draft version of this page.  | 
            ||
| 1690 | *  | 
            ||
| 1691 | * @return string  | 
            ||
| 1692 | */  | 
            ||
| 1693 | 	public function getStageURLSegment() { | 
            ||
| 1694 | 		$stageRecord = Versioned::get_one_by_stage('SiteTree', 'Stage', array( | 
            ||
| 1695 | '"SiteTree"."ID"' => $this->ID  | 
            ||
| 1696 | ));  | 
            ||
| 1697 | return ($stageRecord) ? $stageRecord->URLSegment : null;  | 
            ||
| 1698 | }  | 
            ||
| 1699 | |||
| 1700 | /**  | 
            ||
| 1701 | * Gets the URL segment for the currently published version of this page.  | 
            ||
| 1702 | *  | 
            ||
| 1703 | * @return string  | 
            ||
| 1704 | */  | 
            ||
| 1705 | 	public function getLiveURLSegment() { | 
            ||
| 1706 | 		$liveRecord = Versioned::get_one_by_stage('SiteTree', 'Live', array( | 
            ||
| 1707 | '"SiteTree"."ID"' => $this->ID  | 
            ||
| 1708 | ));  | 
            ||
| 1709 | return ($liveRecord) ? $liveRecord->URLSegment : null;  | 
            ||
| 1710 | }  | 
            ||
| 1711 | |||
| 1712 | /**  | 
            ||
| 1713 | * Rewrites any linked images on this page without creating a new version record.  | 
            ||
| 1714 | * Non-image files should be linked via shortcodes  | 
            ||
| 1715 | * Triggers the onRenameLinkedAsset action on extensions.  | 
            ||
| 1716 | *  | 
            ||
| 1717 | * @todo Implement image shortcodes and remove this feature  | 
            ||
| 1718 | */  | 
            ||
| 1719 | 	public function rewriteFileLinks() { | 
            ||
| 1720 | // Skip live stage  | 
            ||
| 1721 | 		if(\Versioned::current_stage() === \Versioned::get_live_stage()) { | 
            ||
| 1722 | return;  | 
            ||
| 1723 | }  | 
            ||
| 1724 | |||
| 1725 | // Update the content without actually creating a new version  | 
            ||
| 1726 | 		foreach($this->db() as $fieldName => $fieldType) { | 
            ||
| 1727 | // Skip if non HTML or if empty  | 
            ||
| 1728 | 			if ($fieldType !== 'HTMLText') { | 
            ||
| 1729 | continue;  | 
            ||
| 1730 | }  | 
            ||
| 1731 | 			$fieldValue = $this->{$fieldName}; | 
            ||
| 1732 | 			if(empty($fieldValue)) { | 
            ||
| 1733 | continue;  | 
            ||
| 1734 | }  | 
            ||
| 1735 | |||
| 1736 | // Regenerate content  | 
            ||
| 1737 | $content = Image::regenerate_html_links($fieldValue);  | 
            ||
| 1738 | 			if($content === $fieldValue) { | 
            ||
| 1739 | continue;  | 
            ||
| 1740 | }  | 
            ||
| 1741 | |||
| 1742 | // Write content directly without updating linked assets  | 
            ||
| 1743 | $table = ClassInfo::table_for_object_field($this, $fieldName);  | 
            ||
| 1744 | 			$query = sprintf('UPDATE "%s" SET "%s" = ? WHERE "ID" = ?', $table, $fieldName); | 
            ||
| 1745 | DB::prepared_query($query, array($content, $this->ID));  | 
            ||
| 1746 | |||
| 1747 | // Update linked assets  | 
            ||
| 1748 | 			$this->invokeWithExtensions('onRenameLinkedAsset'); | 
            ||
| 1749 | }  | 
            ||
| 1750 | }  | 
            ||
| 1751 | |||
| 1752 | /**  | 
            ||
| 1753 | * Returns the pages that depend on this page. This includes virtual pages, pages that link to it, etc.  | 
            ||
| 1754 | *  | 
            ||
| 1755 | * @param bool $includeVirtuals Set to false to exlcude virtual pages.  | 
            ||
| 1756 | * @return ArrayList  | 
            ||
| 1757 | */  | 
            ||
| 1758 | 	public function DependentPages($includeVirtuals = true) { | 
            ||
| 1808 | |||
| 1809 | /**  | 
            ||
| 1810 | * Return all virtual pages that link to this page.  | 
            ||
| 1811 | *  | 
            ||
| 1812 | * @return DataList  | 
            ||
| 1813 | */  | 
            ||
| 1814 | 	public function VirtualPages() { | 
            ||
| 1836 | |||
| 1837 | /**  | 
            ||
| 1838 | * Returns a FieldList with which to create the main editing form.  | 
            ||
| 1839 | *  | 
            ||
| 1840 | * You can override this in your child classes to add extra fields - first get the parent fields using  | 
            ||
| 1841 | * parent::getCMSFields(), then use addFieldToTab() on the FieldList.  | 
            ||
| 1842 | *  | 
            ||
| 1843 | 	 * See {@link getSettingsFields()} for a different set of fields concerned with configuration aspects on the record, | 
            ||
| 1844 | * e.g. access control.  | 
            ||
| 1845 | *  | 
            ||
| 1846 | * @return FieldList The fields to be displayed in the CMS  | 
            ||
| 1847 | */  | 
            ||
| 1848 | 	public function getCMSFields() { | 
            ||
| 2028 | |||
| 2029 | |||
| 2030 | /**  | 
            ||
| 2031 | 	 * Returns fields related to configuration aspects on this record, e.g. access control. See {@link getCMSFields()} | 
            ||
| 2032 | * for content-related fields.  | 
            ||
| 2033 | *  | 
            ||
| 2034 | * @return FieldList  | 
            ||
| 2035 | */  | 
            ||
| 2036 | 	public function getSettingsFields() { | 
            ||
| 2142 | |||
| 2143 | /**  | 
            ||
| 2144 | * @param bool $includerelations A boolean value to indicate if the labels returned should include relation fields  | 
            ||
| 2145 | * @return array  | 
            ||
| 2146 | */  | 
            ||
| 2147 | 	public function fieldLabels($includerelations = true) { | 
            ||
| 2185 | |||
| 2186 | /**  | 
            ||
| 2187 | * Get the actions available in the CMS for this page - eg Save, Publish.  | 
            ||
| 2188 | *  | 
            ||
| 2189 | * Frontend scripts and styles know how to handle the following FormFields:  | 
            ||
| 2190 | * - top-level FormActions appear as standalone buttons  | 
            ||
| 2191 | * - top-level CompositeField with FormActions within appear as grouped buttons  | 
            ||
| 2192 | * - TabSet & Tabs appear as a drop ups  | 
            ||
| 2193 | * - FormActions within the Tab are restyled as links  | 
            ||
| 2194 | * - major actions can provide alternate states for richer presentation (see ssui.button widget extension)  | 
            ||
| 2195 | *  | 
            ||
| 2196 | * @return FieldList The available actions for this page.  | 
            ||
| 2197 | */  | 
            ||
| 2198 | 	public function getCMSActions() { | 
            ||
| 2349 | |||
| 2350 | /**  | 
            ||
| 2351 | * Publish this page.  | 
            ||
| 2352 | *  | 
            ||
| 2353 | * @uses SiteTreeExtension->onBeforePublish()  | 
            ||
| 2354 | * @uses SiteTreeExtension->onAfterPublish()  | 
            ||
| 2355 | * @return bool True if published  | 
            ||
| 2356 | */  | 
            ||
| 2357 | 	public function doPublish() { | 
            ||
| 2399 | |||
| 2400 | /**  | 
            ||
| 2401 | * Unpublish this page - remove it from the live site  | 
            ||
| 2402 | *  | 
            ||
| 2403 | 	 * Overrides {@see Versioned::doUnpublish()} | 
            ||
| 2404 | *  | 
            ||
| 2405 | * @uses SiteTreeExtension->onBeforeUnpublish()  | 
            ||
| 2406 | * @uses SiteTreeExtension->onAfterUnpublish()  | 
            ||
| 2407 | */  | 
            ||
| 2408 | 	public function doUnpublish() { | 
            ||
| 2446 | |||
| 2447 | /**  | 
            ||
| 2448 | * Revert the draft changes: replace the draft content with the content on live  | 
            ||
| 2449 | */  | 
            ||
| 2450 | 	public function doRevertToLive() { | 
            ||
| 2468 | |||
| 2469 | /**  | 
            ||
| 2470 | * Determine if this page references a parent which is archived, and not available in stage  | 
            ||
| 2471 | *  | 
            ||
| 2472 | * @return bool True if there is an archived parent  | 
            ||
| 2473 | */  | 
            ||
| 2474 | 	protected function isParentArchived() { | 
            ||
| 2483 | |||
| 2484 | /**  | 
            ||
| 2485 | * Restore the content in the active copy of this SiteTree page to the stage site.  | 
            ||
| 2486 | *  | 
            ||
| 2487 | * @return self  | 
            ||
| 2488 | */  | 
            ||
| 2489 | 	public function doRestoreToStage() { | 
            ||
| 2525 | |||
| 2526 | /**  | 
            ||
| 2527 | * @deprecated  | 
            ||
| 2528 | */  | 
            ||
| 2529 | 	public function doDeleteFromLive() { | 
            ||
| 2533 | |||
| 2534 | /**  | 
            ||
| 2535 | * Check if this page is new - that is, if it has yet to have been written to the database.  | 
            ||
| 2536 | *  | 
            ||
| 2537 | * @return bool  | 
            ||
| 2538 | */  | 
            ||
| 2539 | 	public function isNew() { | 
            ||
| 2550 | |||
| 2551 | /**  | 
            ||
| 2552 | * Get the class dropdown used in the CMS to change the class of a page. This returns the list of options in the  | 
            ||
| 2553 | 	 * dropdown as a Map from class name to singular name. Filters by {@link SiteTree->canCreate()}, as well as | 
            ||
| 2554 | 	 * {@link SiteTree::$needs_permission}. | 
            ||
| 2555 | *  | 
            ||
| 2556 | * @return array  | 
            ||
| 2557 | */  | 
            ||
| 2558 | 	protected function getClassDropdown() { | 
            ||
| 2602 | |||
| 2603 | /**  | 
            ||
| 2604 | * Returns an array of the class names of classes that are allowed to be children of this class.  | 
            ||
| 2605 | *  | 
            ||
| 2606 | * @return string[]  | 
            ||
| 2607 | */  | 
            ||
| 2608 | 	public function allowedChildren() { | 
            ||
| 2628 | |||
| 2629 | /**  | 
            ||
| 2630 | * Returns the class name of the default class for children of this page.  | 
            ||
| 2631 | *  | 
            ||
| 2632 | * @return string  | 
            ||
| 2633 | */  | 
            ||
| 2634 | 	public function defaultChild() { | 
            ||
| 2643 | |||
| 2644 | /**  | 
            ||
| 2645 | * Returns the class name of the default class for the parent of this page.  | 
            ||
| 2646 | *  | 
            ||
| 2647 | * @return string  | 
            ||
| 2648 | */  | 
            ||
| 2649 | 	public function defaultParent() { | 
            ||
| 2652 | |||
| 2653 | /**  | 
            ||
| 2654 | * Get the title for use in menus for this page. If the MenuTitle field is set it returns that, else it returns the  | 
            ||
| 2655 | * Title field.  | 
            ||
| 2656 | *  | 
            ||
| 2657 | * @return string  | 
            ||
| 2658 | */  | 
            ||
| 2659 | 	public function getMenuTitle(){ | 
            ||
| 2666 | |||
| 2667 | |||
| 2668 | /**  | 
            ||
| 2669 | * Set the menu title for this page.  | 
            ||
| 2670 | *  | 
            ||
| 2671 | * @param string $value  | 
            ||
| 2672 | */  | 
            ||
| 2673 | 	public function setMenuTitle($value) { | 
            ||
| 2680 | |||
| 2681 | /**  | 
            ||
| 2682 | * A flag provides the user with additional data about the current page status, for example a "removed from draft"  | 
            ||
| 2683 | * status. Each page can have more than one status flag. Returns a map of a unique key to a (localized) title for  | 
            ||
| 2684 | * the flag. The unique key can be reused as a CSS class. Use the 'updateStatusFlags' extension point to customize  | 
            ||
| 2685 | * the flags.  | 
            ||
| 2686 | *  | 
            ||
| 2687 | * Example (simple):  | 
            ||
| 2688 | * "deletedonlive" => "Deleted"  | 
            ||
| 2689 | *  | 
            ||
| 2690 | * Example (with optional title attribute):  | 
            ||
| 2691 | 	 *   "deletedonlive" => array('text' => "Deleted", 'title' => 'This page has been deleted') | 
            ||
| 2692 | *  | 
            ||
| 2693 | * @param bool $cached Whether to serve the fields from cache; false regenerate them  | 
            ||
| 2694 | * @return array  | 
            ||
| 2695 | */  | 
            ||
| 2696 | 	public function getStatusFlags($cached = true) { | 
            ||
| 2730 | |||
| 2731 | /**  | 
            ||
| 2732 | * getTreeTitle will return three <span> html DOM elements, an empty <span> with the class 'jstree-pageicon' in  | 
            ||
| 2733 | * front, following by a <span> wrapping around its MenutTitle, then following by a <span> indicating its  | 
            ||
| 2734 | * publication status.  | 
            ||
| 2735 | *  | 
            ||
| 2736 | * @return string An HTML string ready to be directly used in a template  | 
            ||
| 2737 | */  | 
            ||
| 2738 | 	public function getTreeTitle() { | 
            ||
| 2767 | |||
| 2768 | /**  | 
            ||
| 2769 | * Returns the page in the current page stack of the given level. Level(1) will return the main menu item that  | 
            ||
| 2770 | * we're currently inside, etc.  | 
            ||
| 2771 | *  | 
            ||
| 2772 | * @param int $level  | 
            ||
| 2773 | * @return SiteTree  | 
            ||
| 2774 | */  | 
            ||
| 2775 | 	public function Level($level) { | 
            ||
| 2784 | |||
| 2785 | /**  | 
            ||
| 2786 | * Gets the depth of this page in the sitetree, where 1 is the root level  | 
            ||
| 2787 | *  | 
            ||
| 2788 | * @return int  | 
            ||
| 2789 | */  | 
            ||
| 2790 | 	public function getPageLevel() { | 
            ||
| 2796 | |||
| 2797 | /**  | 
            ||
| 2798 | * Return the CSS classes to apply to this node in the CMS tree.  | 
            ||
| 2799 | *  | 
            ||
| 2800 | * @param string $numChildrenMethod  | 
            ||
| 2801 | * @return string  | 
            ||
| 2802 | */  | 
            ||
| 2803 | 	public function CMSTreeClasses($numChildrenMethod="numChildren") { | 
            ||
| 2834 | |||
| 2835 | /**  | 
            ||
| 2836 | * Compares current draft with live version, and returns true if no draft version of this page exists but the page  | 
            ||
| 2837 | * is still published (eg, after triggering "Delete from draft site" in the CMS).  | 
            ||
| 2838 | *  | 
            ||
| 2839 | * @return bool  | 
            ||
| 2840 | */  | 
            ||
| 2841 | 	public function getIsDeletedFromStage() { | 
            ||
| 2850 | |||
| 2851 | /**  | 
            ||
| 2852 | * Return true if this page exists on the live site  | 
            ||
| 2853 | *  | 
            ||
| 2854 | * @return bool  | 
            ||
| 2855 | */  | 
            ||
| 2856 | 	public function getExistsOnLive() { | 
            ||
| 2859 | |||
| 2860 | /**  | 
            ||
| 2861 | * Compares current draft with live version, and returns true if these versions differ, meaning there have been  | 
            ||
| 2862 | * unpublished changes to the draft site.  | 
            ||
| 2863 | *  | 
            ||
| 2864 | * @return bool  | 
            ||
| 2865 | */  | 
            ||
| 2866 | 	public function getIsModifiedOnStage() { | 
            ||
| 2878 | |||
| 2879 | /**  | 
            ||
| 2880 | * Compares current draft with live version, and returns true if no live version exists, meaning the page was never  | 
            ||
| 2881 | * published.  | 
            ||
| 2882 | *  | 
            ||
| 2883 | * @return bool  | 
            ||
| 2884 | */  | 
            ||
| 2885 | 	public function getIsAddedToStage() { | 
            ||
| 2894 | |||
| 2895 | /**  | 
            ||
| 2896 | * Stops extendCMSFields() being called on getCMSFields(). This is useful when you need access to fields added by  | 
            ||
| 2897 | * subclasses of SiteTree in a extension. Call before calling parent::getCMSFields(), and reenable afterwards.  | 
            ||
| 2898 | */  | 
            ||
| 2899 | 	static public function disableCMSFieldsExtensions() { | 
            ||
| 2902 | |||
| 2903 | /**  | 
            ||
| 2904 | * Reenables extendCMSFields() being called on getCMSFields() after it has been disabled by  | 
            ||
| 2905 | * disableCMSFieldsExtensions().  | 
            ||
| 2906 | */  | 
            ||
| 2907 | 	static public function enableCMSFieldsExtensions() { | 
            ||
| 2910 | |||
| 2911 | 	public function providePermissions() { | 
            ||
| 2945 | |||
| 2946 | /**  | 
            ||
| 2947 | * Return the translated Singular name.  | 
            ||
| 2948 | *  | 
            ||
| 2949 | * @return string  | 
            ||
| 2950 | */  | 
            ||
| 2951 | 	public function i18n_singular_name() { | 
            ||
| 2956 | |||
| 2957 | /**  | 
            ||
| 2958 | * Overloaded to also provide entities for 'Page' class which is usually located in custom code, hence textcollector  | 
            ||
| 2959 | * picks it up for the wrong folder.  | 
            ||
| 2960 | *  | 
            ||
| 2961 | * @return array  | 
            ||
| 2962 | */  | 
            ||
| 2963 | 	public function provideI18nEntities() { | 
            ||
| 2979 | |||
| 2980 | /**  | 
            ||
| 2981 | * Returns 'root' if the current page has no parent, or 'subpage' otherwise  | 
            ||
| 2982 | *  | 
            ||
| 2983 | * @return string  | 
            ||
| 2984 | */  | 
            ||
| 2985 | 	public function getParentType() { | 
            ||
| 2988 | |||
| 2989 | /**  | 
            ||
| 2990 | * Clear the permissions cache for SiteTree  | 
            ||
| 2991 | */  | 
            ||
| 2992 | 	public static function reset() { | 
            ||
| 2995 | |||
| 2996 | 	static public function on_db_reset() { | 
            ||
| 2999 | |||
| 3000 | }  | 
            ||
| 3001 |