-
Notifications
You must be signed in to change notification settings - Fork 334
/
Copy pathSiteTree.php
executable file
·3460 lines (3095 loc) · 124 KB
/
SiteTree.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace SilverStripe\CMS\Model;
use Page;
use Psr\SimpleCache\CacheInterface;
use SilverStripe\Admin\CMSEditLinkExtension;
use SilverStripe\Assets\Shortcodes\FileLinkTracking;
use SilverStripe\CMS\Controllers\CMSMain;
use SilverStripe\CMS\Controllers\CMSPageEditController;
use SilverStripe\CMS\Controllers\ContentController;
use SilverStripe\CMS\Controllers\ModelAsController;
use SilverStripe\CMS\Controllers\RootURLController;
use SilverStripe\CMS\Forms\SiteTreeURLSegmentField;
use SilverStripe\Control\ContentNegotiator;
use SilverStripe\Control\Controller;
use SilverStripe\Control\Director;
use SilverStripe\Core\Cache\MemberCacheFlusher;
use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Convert;
use SilverStripe\Core\Flushable;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Manifest\ModuleResource;
use SilverStripe\Core\Manifest\ModuleResourceLoader;
use SilverStripe\Core\Manifest\VersionProvider;
use SilverStripe\Core\Resettable;
use SilverStripe\Dev\Deprecation;
use SilverStripe\Forms\CheckboxField;
use SilverStripe\Forms\CompositeField;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\FieldGroup;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\FormAction;
use SilverStripe\Forms\GridField\GridField;
use SilverStripe\Forms\GridField\GridFieldDataColumns;
use SilverStripe\Forms\GridField\GridFieldLazyLoader;
use SilverStripe\Forms\HTMLEditor\HTMLEditorField;
use SilverStripe\Forms\ListboxField;
use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\OptionsetField;
use SilverStripe\Forms\SearchableMultiDropdownField;
use SilverStripe\Forms\Tab;
use SilverStripe\Forms\TabSet;
use SilverStripe\Forms\TextareaField;
use SilverStripe\Forms\TextField;
use SilverStripe\Forms\ToggleCompositeField;
use SilverStripe\Forms\TreeDropdownField;
use SilverStripe\Forms\TreeMultiselectField;
use SilverStripe\i18n\i18n;
use SilverStripe\i18n\i18nEntityProvider;
use SilverStripe\ORM\ArrayList;
use SilverStripe\ORM\CMSPreviewable;
use SilverStripe\ORM\DataList;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\DB;
use SilverStripe\ORM\HasManyList;
use SilverStripe\ORM\HiddenClass;
use SilverStripe\ORM\Hierarchy\Hierarchy;
use SilverStripe\ORM\ManyManyList;
use SilverStripe\ORM\ValidationResult;
use SilverStripe\Security\Group;
use SilverStripe\Security\InheritedPermissions;
use SilverStripe\Security\InheritedPermissionsExtension;
use SilverStripe\Security\Member;
use SilverStripe\Security\Permission;
use SilverStripe\Security\PermissionChecker;
use SilverStripe\Security\PermissionProvider;
use SilverStripe\Security\Security;
use SilverStripe\SiteConfig\SiteConfig;
use SilverStripe\Subsites\Model\Subsite;
use SilverStripe\Versioned\RecursivePublishable;
use SilverStripe\Versioned\Versioned;
use SilverStripe\View\ArrayData;
use SilverStripe\View\HTML;
use SilverStripe\View\Parsers\HTMLValue;
use SilverStripe\View\Parsers\ShortcodeParser;
use SilverStripe\View\Parsers\URLSegmentFilter;
use SilverStripe\View\Shortcodes\EmbedShortcodeProvider;
use SilverStripe\View\SSViewer;
/**
* Basic data-object representing all pages within the site tree. All page types that live within the hierarchy should
* inherit from this. In addition, it contains a number of static methods for querying the site tree and working with
* draft and published states.
*
* <h2>URLs</h2>
* A page is identified during request handling via its "URLSegment" database column. As pages can be nested, the full
* path of a URL might contain multiple segments. Each segment is stored in its filtered representation (through
* {@link URLSegmentFilter}). The full path is constructed via {@link Link()}, {@link RelativeLink()} and
* {@link AbsoluteLink()}. You can allow these segments to contain multibyte characters through
* {@link URLSegmentFilter::$default_allow_multibyte}.
*
* @property string $URLSegment
* @property string $Title
* @property string $MenuTitle
* @property string $Content HTML content of the page.
* @property string $MetaDescription
* @property string $ExtraMeta
* @property string $ReportClass
* @property int $Sort Integer value denoting the sort order.
* @property bool $ShowInMenus
* @property bool $ShowInSearch
* @property bool $HasBrokenFile True if this page has a broken file shortcode
* @property bool $HasBrokenLink True if this page has a broken page shortcode
*
* @mixin Hierarchy
* @mixin Versioned
* @mixin RecursivePublishable
* @mixin SiteTreeLinkTracking Added via linktracking.yml to DataObject directly
* @mixin FileLinkTracking Added via filetracking.yml in silverstripe/assets
* @mixin InheritedPermissionsExtension
* @method HasManyList<SiteTreeLink> BackLinks()
*/
class SiteTree extends DataObject implements PermissionProvider, i18nEntityProvider, CMSPreviewable, Resettable, Flushable, MemberCacheFlusher
{
/**
* Indicates what kind of children this page type can have.
* This can be an array of allowed child classes, or the string "none" -
* indicating that this page type can't have children.
* If a classname is prefixed by "*", such as "*Page", then only that
* class is allowed - no subclasses. Otherwise, the class and all its
* subclasses are allowed.
* To control allowed children on root level (no parent), use {@link $can_be_root}.
*
* Note that this setting is cached when used in the CMS, use the "flush" query parameter to clear it.
*
* @config
* @var array
*/
private static $allowed_children = [
SiteTree::class
];
/**
* Used as a cache for `SiteTree::allowedChildren()`
* Drastically reduces admin page load when there are a lot of page types
* @var array
* @deprecated 5.4.0 will be moved to SilverStripe\ORM\Hierarchy\Hierarchy->cache_allowedChildren
*/
protected static $_allowedChildren = [];
/**
* Determines if the Draft Preview panel will appear when in the CMS admin
* @var bool
*/
private static $show_stage_link = true;
/**
* Determines if the Live Preview panel will appear when in the CMS admin
* @var bool
*/
private static $show_live_link = true;
/**
* The default child class for this page.
* Note: Value might be cached, see {@link $allowed_chilren}.
*
* @config
* @var string
*/
private static $default_child = "Page";
/**
* Default value for SiteTree.ClassName enum
* {@see DBClassName::getDefault}
*
* @config
* @var string
*/
private static $default_classname = "Page";
/**
* The default parent class for this page.
* Note: Value might be cached, see {@link $allowed_chilren}.
*
* @config
* @var string
*/
private static $default_parent = null;
/**
* Controls whether a page can be in the root of the site tree.
* Note: Value might be cached, see {@link $allowed_chilren}.
*
* @config
* @var bool
*/
private static $can_be_root = true;
/**
* List of permission codes a user can have to allow a user to create a page of this type.
* Note: Value might be cached, see {@link $allowed_chilren}.
*
* @config
* @var array
* @deprecated 5.4.0 Use canCreate() instead.
*/
private static $need_permission = null;
/**
* If you extend a class, and don't want to be able to select the old class
* in the cms, set this to the old class name. Eg, if you extended Product
* to make ImprovedProduct, then you would set $hide_ancestor to Product.
*
* @deprecated 5.2.0 Use hide_pagetypes instead
*
* @config
* @var string
*/
private static $hide_ancestor = null;
/**
* Any fully qualified class names added to this array will be hidden in the CMS
* when selecting page types, e.g. for creating a new page or changing the type
* of an existing page.
*/
private static array $hide_pagetypes = [];
/**
* You can define the class of the controller that maps to your SiteTree object here if
* you don't want to rely on the magic of appending Controller to the Classname
*
* @config
* @var string
*/
private static $controller_name = null;
/**
* The class of the LeftAndMain controller where this class is managed.
* @see CMSEditLinkExtension::getCMSEditOwner()
*/
private static string $cms_edit_owner = CMSMain::class;
/**
* You can define the a map of Page namespaces to Controller namespaces here
* This will apply after the magic of appending Controller, and in order
* Must be applied to SiteTree config e.g.
*
* SilverStripe\CMS\Model\SiteTree:
* namespace_map:
* "App\Pages": "App\Control"
*
* Will map App\Pages\MyPage to App\Control\MyPageController
*
* @config
* @var string
*/
private static $namespace_map = null;
private static $db = [
"URLSegment" => "Varchar(255)",
"Title" => "Varchar(255)",
"MenuTitle" => "Varchar(100)",
"Content" => "HTMLText",
"MetaDescription" => "Text",
"ExtraMeta" => "HTMLFragment(['whitelist' => ['meta', 'link']])",
"ShowInMenus" => "Boolean",
"ShowInSearch" => "Boolean",
"Sort" => "Int",
"HasBrokenFile" => "Boolean",
"HasBrokenLink" => "Boolean",
"ReportClass" => "Varchar",
];
private static $indexes = [
"URLSegment" => true,
];
private static $has_many = [
"VirtualPages" => VirtualPage::class . '.CopyContentFrom',
'BackLinks' => SiteTreeLink::class . '.Linked',
];
private static $owned_by = [
"VirtualPages"
];
private static $cascade_deletes = [
'VirtualPages',
];
private static $casting = [
"Breadcrumbs" => "HTMLFragment",
"LastEdited" => "Datetime",
"Created" => "Datetime",
'Link' => 'Text',
'RelativeLink' => 'Text',
'AbsoluteLink' => 'Text',
'CMSEditLink' => 'Text',
'TreeTitle' => 'HTMLFragment',
'MetaTags' => 'HTMLFragment',
];
private static $defaults = [
"ShowInMenus" => 1,
"ShowInSearch" => 1,
];
private static $table_name = 'SiteTree';
private static $versioning = [
"Stage", "Live"
];
/**
* Fields which, if changed on their own, won't cause a new version/live record to be created
* @var string[]
*/
private static array $fields_ignored_by_versioning = [
'HasBrokenFile',
'HasBrokenLink',
];
private static $default_sort = "\"Sort\"";
/**
* If this is false, the class cannot be created in the CMS by regular content authors, only by ADMINs.
* @var boolean
* @config
*/
private static $can_create = true;
/**
* Icon to use in the CMS page tree. This should be the full filename, relative to the webroot.
* Also supports custom CSS rule contents (applied to the correct selector for the tree UI implementation).
*
* @see LeftAndMainPageIconsExtension::generatePageIconsCss()
* @config
* @var string
* @deprecated 5.4.0 Will be renamed to cms_icon
*/
private static $icon = null;
/**
* Class attached to page icons in the CMS page tree. Also supports font-icon set.
* @config
* @var string
* @deprecated 5.4.0 Will be renamed to cms_icon_class
*/
private static $icon_class = 'font-icon-page';
private static $extensions = [
Hierarchy::class,
Versioned::class,
InheritedPermissionsExtension::class,
CMSEditLinkExtension::class,
];
private static $searchable_fields = [
'Title',
'Content',
];
private static $field_labels = [
'URLSegment' => 'URL'
];
/**
* @config
*/
private static $nested_urls = true;
/**
* @config
*/
private static $create_default_pages = true;
/**
* This controls whether of not extendCMSFields() is called by getCMSFields.
*/
private static $runCMSFieldsExtensions = true;
/**
* Deleting this page also deletes all its children when set to true.
*
* @config
* @var boolean
*/
private static $enforce_strict_hierarchy = true;
/**
* The value used for the meta generator tag. Leave blank to omit the tag.
*
* @config
* @var string
*/
private static $meta_generator = 'Silverstripe CMS';
/**
* Whether to display the version portion of the meta generator tag
* Set to false if it's viewed as a concern.
*
* @config
* @var bool
*/
private static $show_meta_generator_version = true;
protected $_cache_statusFlags = null;
/**
* Plural form for SiteTree / Page classes. Not inherited by subclasses.
*
* @config
* @var string
*/
private static $base_plural_name = 'Pages';
/**
* Plural form for SiteTree / Page classes. Not inherited by subclasses.
*
* @config
* @var string
*/
private static $base_singular_name = 'Page';
/**
* Description of the class functionality, typically shown to a user
* when selecting which page type to create. Translated through {@link provideI18nEntities()}.
*
* @see SiteTree::classDescription()
* @see SiteTree::i18n_classDescription()
*
* @config
* @var string
* @deprecated 5.4.0 use class_description instead.
*/
private static $description = null;
/**
* Description for Page and SiteTree classes, but not inherited by subclasses.
* override SiteTree::$description in subclasses instead.
*
* @see SiteTree::classDescription()
* @see SiteTree::i18n_classDescription()
*
* @config
* @var string
* @deprecated 5.4.0 use base_class_description instead.
*/
private static $base_description = 'Generic content page';
/**
* Description for Page and SiteTree classes, but not inherited by subclasses.
*/
private static string $base_class_description = 'Generic content page';
/**
* @var array
*/
private static $dependencies = [
'creatableChildrenCache' => '%$' . CacheInterface::class . '.SiteTree_CreatableChildren'
];
/**
* @var CacheInterface
*/
protected $creatableChildrenCache;
/**
* @var VersionProvider
*/
private $versionProvider;
/**
* Fetches the {@link SiteTree} object that maps to a link.
*
* If you have enabled {@link SiteTree::config()->nested_urls} on this site, then you can use a nested link such as
* "about-us/staff/", and this function will traverse down the URL chain and grab the appropriate link.
*
* Note that if no model can be found, this method will fall over to a extended alternateGetByLink method provided
* by a extension attached to {@link SiteTree}
*
* @param string $link The link of the page to search for
* @param bool $cache True (default) to use caching, false to force a fresh search from the database
* @return SiteTree|null
*/
public static function get_by_link($link, $cache = true)
{
// Compute the column names with dynamic a dynamic table name
$tableName = DataObject::singleton(SiteTree::class)->baseTable();
$urlSegmentExpr = sprintf('"%s"."URLSegment"', $tableName);
$parentIDExpr = sprintf('"%s"."ParentID"', $tableName);
$link = trim(Director::makeRelative($link) ?? '', '/');
if ($link === false || $link === null || $link === '') {
$link = RootURLController::get_homepage_link();
}
$parts = preg_split('|/+|', $link ?? '');
// Grab the initial root level page to traverse down from.
$URLSegment = array_shift($parts);
$conditions = [$urlSegmentExpr => rawurlencode($URLSegment ?? '')];
if (static::config()->get('nested_urls')) {
$conditions[] = [$parentIDExpr => 0];
}
/** @var SiteTree $sitetree */
$sitetree = DataObject::get_one(SiteTree::class, $conditions, $cache);
/// Fall back on a unique URLSegment for b/c.
if (!$sitetree
&& static::config()->get('nested_urls')
&& $sitetree = DataObject::get_one(SiteTree::class, [
$urlSegmentExpr => $URLSegment
], $cache)
) {
return $sitetree;
}
// Attempt to grab an alternative page from extensions.
if (!$sitetree) {
$parentID = static::config()->get('nested_urls') ? 0 : null;
if ($alternatives = static::singleton()->extend('alternateGetByLink', $URLSegment, $parentID)) {
foreach ($alternatives as $alternative) {
if ($alternative) {
$sitetree = $alternative;
}
}
}
if (!$sitetree) {
return null;
}
}
// Check if we have any more URL parts to parse.
if (!static::config()->get('nested_urls') || !count($parts ?? [])) {
return $sitetree;
}
// Traverse down the remaining URL segments and grab the relevant SiteTree objects.
foreach ($parts as $segment) {
$next = DataObject::get_one(
SiteTree::class,
[
$urlSegmentExpr => $segment,
$parentIDExpr => $sitetree->ID
],
$cache
);
if (!$next) {
$parentID = (int) $sitetree->ID;
if ($alternatives = static::singleton()->extend('alternateGetByLink', $segment, $parentID)) {
foreach ($alternatives as $alternative) {
if ($alternative) {
$next = $alternative;
}
}
}
if (!$next) {
return null;
}
}
$sitetree->destroy();
$sitetree = $next;
}
return $sitetree;
}
/**
* Return a subclass map of SiteTree that shouldn't be hidden through {@link SiteTree::$hide_pagetypes}
*
* @return array
* @deprecated 5.4.0 Will be replaced with updateAllowedSubClasses()
*/
public static function page_type_classes()
{
$classes = ClassInfo::getValidSubClasses();
$baseClassIndex = array_search(SiteTree::class, $classes ?? []);
if ($baseClassIndex !== false) {
unset($classes[$baseClassIndex]);
}
$kill_ancestors = SiteTree::config()->get('hide_pagetypes', Config::UNINHERITED) ?? [];
// figure out if there are any classes we don't want to appear
foreach ($classes as $class) {
$instance = singleton($class);
// do any of the progeny want to hide an ancestor?
if ($ancestor_to_hide = $instance->config()->get('hide_ancestor')) {
// note for killing later
$kill_ancestors[] = $ancestor_to_hide;
}
}
// If any of the descendents don't want any of the elders to show up, cruelly render the elders surplus to
// requirements
if ($kill_ancestors) {
$kill_ancestors = array_unique($kill_ancestors ?? []);
foreach ($kill_ancestors as $mark) {
// unset from $classes
$idx = array_search($mark, $classes ?? [], true);
if ($idx !== false) {
unset($classes[$idx]);
}
}
}
return $classes;
}
/**
* Replace a "[sitetree_link id=n]" shortcode with a link to the page with the corresponding ID.
*
* @param array $arguments
* @param string $content
* @param ShortcodeParser $parser
* @return string
*/
public static function link_shortcode_handler($arguments, $content = null, $parser = null)
{
if (!isset($arguments['id']) || !is_numeric($arguments['id'])) {
return null;
}
/** @var SiteTree $page */
if (!($page = DataObject::get_by_id(SiteTree::class, $arguments['id'])) // Get the current page by ID.
&& !($page = Versioned::get_latest_version(SiteTree::class, $arguments['id'])) // Attempt link to old version.
) {
return null; // There were no suitable matches at all.
}
$link = Convert::raw2att($page->Link());
if ($content) {
return sprintf('<a href="%s">%s</a>', $link, $parser->parse($content));
} else {
return $link;
}
}
/**
* Return the link for this {@link SiteTree} object, with the {@link Director::baseURL()} included.
*
* @param string $action Optional controller action (method).
* Note: URI encoding of this parameter is applied automatically through template casting,
* don't encode the passed parameter. Please use {@link Controller::join_links()} instead to
* append GET parameters.
* @return string
*/
public function Link($action = null)
{
$relativeLink = $this->RelativeLink($action);
$link = Controller::join_links(Director::baseURL(), $relativeLink);
$this->extend('updateLink', $link, $action, $relativeLink);
return $link;
}
/**
* Get the absolute URL for this page, including protocol and host.
*
* @param string $action See {@link Link()}
* @return string
*/
public function AbsoluteLink($action = null)
{
if ($this->hasMethod('alternateAbsoluteLink')) {
return $this->alternateAbsoluteLink($action);
} else {
return Director::absoluteURL((string) $this->Link($action));
}
}
/**
* Base link used for previewing. Defaults to absolute URL, in order to account for domain changes, e.g. on multi
* site setups. Does not contain hints about the stage, see {@link SilverStripeNavigator} for details.
*
* @param string $action See {@link Link()}
* @return string
*/
public function PreviewLink($action = null)
{
$link = $this->AbsoluteLink($action);
$this->extend('updatePreviewLink', $link, $action);
return $link;
}
public function getMimeType()
{
return 'text/html';
}
/**
* Return the link for this {@link SiteTree} object relative to the SilverStripe root.
*
* By default, if this page is the current home page, and there is no action specified then this will return a link
* to the root of the site. However, if you set the $action parameter to TRUE then the link will not be rewritten
* and returned in its full form.
*
* @uses RootURLController::get_homepage_link()
*
* @param string $action See {@link Link()}
* @return string
*/
public function RelativeLink($action = null)
{
if ($this->ParentID && static::config()->get('nested_urls')) {
$parent = $this->Parent();
// If page is removed select parent from version history (for archive page view)
if ((!$parent || !$parent->exists()) && !$this->isOnDraft()) {
$parent = Versioned::get_latest_version(SiteTree::class, $this->ParentID);
}
$base = $parent ? $parent->RelativeLink($this->URLSegment) : null;
} elseif (!$action && $this->URLSegment == RootURLController::get_homepage_link()) {
// Unset base for root-level homepages.
// Note: Homepages with action parameters (or $action === true)
// need to retain their URLSegment.
$base = null;
} else {
$base = $this->URLSegment;
}
// Legacy support: If $action === true, retain URLSegment for homepages,
// but don't append any action
if ($action === true) {
$action = null;
}
$link = Controller::join_links($base, $action);
$this->extend('updateRelativeLink', $link, $base, $action);
return $link;
}
/**
* Get the absolute URL for this page on the Live site.
*
* @param bool $includeStageEqualsLive Whether to append the URL with ?stage=Live to force Live mode
* @return string
*/
public function getAbsoluteLiveLink($includeStageEqualsLive = true)
{
$oldReadingMode = Versioned::get_reading_mode();
Versioned::set_stage(Versioned::LIVE);
$tablename = $this->baseTable();
/** @var SiteTree $live */
$live = Versioned::get_one_by_stage(SiteTree::class, Versioned::LIVE, [
"\"$tablename\".\"ID\"" => $this->ID
]);
if ($live) {
$link = $live->AbsoluteLink();
if ($includeStageEqualsLive) {
$link = Controller::join_links($link, '?stage=Live');
}
} else {
$link = null;
}
Versioned::set_reading_mode($oldReadingMode);
return $link;
}
/**
* Generates a link to edit this page in the CMS.
*
* Implemented here to satisfy the CMSPreviewable interface, but data is intended to be loaded via Extension
*
* @see SilverStripe\Admin\CMSEditLinkExtension
*
* @return string
*/
public function CMSEditLink()
{
return $this->extend('CMSEditLink')[0] ?? '';
}
/**
* Return a CSS identifier generated from this page's link.
*
* @return string The URL segment
*/
public function ElementName()
{
return str_replace('/', '-', trim($this->RelativeLink(true) ?? '', '/'));
}
/**
* Returns true if this is the currently active page being used to handle this request.
*
* @return bool
*/
public function isCurrent()
{
$currentPage = Director::get_current_page();
if ($currentPage instanceof ContentController) {
$currentPage = $currentPage->data();
}
if ($currentPage instanceof SiteTree) {
return $currentPage === $this || $currentPage->ID === $this->ID;
}
return false;
}
/**
* Check if this page is in the currently active section (e.g. it is either current or one of its children is
* currently being viewed).
*
* @return bool
*/
public function isSection()
{
return $this->isCurrent() || (
Director::get_current_page() instanceof SiteTree && in_array($this->ID, Director::get_current_page()->getAncestors()->column() ?? [])
);
}
/**
* Check if the parent of this page has been removed (or made otherwise unavailable), and is still referenced by
* this child. Any such orphaned page may still require access via the CMS, but should not be shown as accessible
* to external users.
*
* @return bool
*/
public function isOrphaned()
{
// Always false for root pages
if (empty($this->ParentID)) {
return false;
}
// Parent must exist and not be an orphan itself
$parent = $this->Parent();
return !$parent || !$parent->exists() || $parent->isOrphaned();
}
/**
* Return "link" or "current" depending on if this is the {@link SiteTree::isCurrent()} current page.
*
* @return string
*/
public function LinkOrCurrent()
{
return $this->isCurrent() ? 'current' : 'link';
}
/**
* Return "link" or "section" depending on if this is the {@link SiteTree::isSeciton()} current section.
*
* @return string
*/
public function LinkOrSection()
{
return $this->isSection() ? 'section' : 'link';
}
/**
* Return "link", "current" or "section" depending on if this page is the current page, or not on the current page
* but in the current section.
*
* @return string
*/
public function LinkingMode()
{
if ($this->isCurrent()) {
return 'current';
} elseif ($this->isSection()) {
return 'section';
} else {
return 'link';
}
}
/**
* Check if this page is in the given current section.
*
* @param string $sectionName Name of the section to check
* @return bool True if we are in the given section
*/
public function InSection($sectionName)
{
$page = Director::get_current_page();
while ($page instanceof SiteTree && $page->exists()) {
if ($sectionName === $page->URLSegment) {
return true;
}
$page = $page->Parent();
}
return false;
}
/**
* Reset Sort on duped page
*
* @param SiteTree $original
* @param bool $doWrite
*/
public function onBeforeDuplicate($original, $doWrite)
{
$this->Sort = 0;
}
/**
* Duplicates each child of this node recursively and returns the top-level duplicate node.
*
* @return static The duplicated object
*/
public function duplicateWithChildren()
{
$clone = $this->duplicate();
$children = $this->AllChildren();
if ($children) {
$sort = 0;
foreach ($children as $child) {
$childClone = method_exists($child, 'duplicateWithChildren')
? $child->duplicateWithChildren()
: $child->duplicate();
$childClone->ParentID = $clone->ID;
//retain sort order by manually setting sort values
$childClone->Sort = ++$sort;
$childClone->write();
}
}
return $clone;
}
/**
* Duplicate this node and its children as a child of the node with the given ID
*
* @param int $id ID of the new node's new parent
*/
public function duplicateAsChild($id)
{
$newSiteTree = $this->duplicate();
$newSiteTree->ParentID = $id;
$newSiteTree->Sort = 0;
$newSiteTree->write();
}
/**
* Return a breadcrumb trail to this page. Excludes "hidden" pages (with ShowInMenus=0) by default.
*
* @param int $maxDepth The maximum depth to traverse.
* @param boolean $unlinked Whether to link page titles.
* @param boolean|string $stopAtPageType ClassName of a page to stop the upwards traversal.
* @param boolean $showHidden Include pages marked with the attribute ShowInMenus = 0
* @param string $delimiter Delimiter character (raw html)
* @return string The breadcrumb trail.
*/
public function Breadcrumbs($maxDepth = 20, $unlinked = false, $stopAtPageType = false, $showHidden = false, $delimiter = '»')
{
$pages = $this->getBreadcrumbItems($maxDepth, $stopAtPageType, $showHidden);
$template = SSViewer::create('BreadcrumbsTemplate');
return $template->process($this->customise(new ArrayData([
"Pages" => $pages,
"Unlinked" => $unlinked,
"Delimiter" => $delimiter,
])));
}
/**
* Returns a list of breadcrumbs for the current page.
*
* @param int $maxDepth The maximum depth to traverse.
* @param boolean|string $stopAtPageType ClassName of a page to stop the upwards traversal.
* @param boolean $showHidden Include pages marked with the attribute ShowInMenus = 0
*
* @return ArrayList<SiteTree>
*/
public function getBreadcrumbItems($maxDepth = 20, $stopAtPageType = false, $showHidden = false)
{
$page = $this;
$pages = [];
while ($page
&& $page->exists()
&& (!$maxDepth || count($pages ?? []) < $maxDepth)
&& (!$stopAtPageType || $page->ClassName != $stopAtPageType)
) {
if ($showHidden || $page->ShowInMenus || ($page->ID == $this->ID)) {
$pages[] = $page;
}
$page = $page->Parent();
}
return new ArrayList(array_reverse($pages ?? []));
}
/**
* Make this page a child of another page.
*
* If the parent page does not exist, resolve it to a valid ID before updating this page's reference.
*
* @param SiteTree|int $item Either the parent object, or the parent ID
*/
public function setParent($item)