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