/
BaseElement.php
1288 lines (1105 loc) · 37 KB
/
BaseElement.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 DNADesign\Elemental\Models;
use DNADesign\Elemental\Controllers\ElementController;
use DNADesign\Elemental\Forms\TextCheckboxGroupField;
use DNADesign\Elemental\ORM\FieldType\DBObjectType;
use DNADesign\Elemental\TopPage\DataExtension;
use Exception;
use SilverStripe\CMS\Controllers\CMSPageEditController;
use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\Control\Controller;
use SilverStripe\Control\Director;
use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\HiddenField;
use SilverStripe\Forms\NumericField;
use SilverStripe\Forms\TextField;
use SilverStripe\GraphQL\Scaffolding\StaticSchema;
use SilverStripe\GraphQL\Schema\Exception\SchemaBuilderException;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\FieldType\DBBoolean;
use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\ORM\FieldType\DBHTMLText;
use SilverStripe\ORM\ValidationException;
use SilverStripe\Security\Member;
use SilverStripe\Security\Permission;
use SilverStripe\Versioned\Versioned;
use SilverStripe\VersionedAdmin\Forms\HistoryViewerField;
use SilverStripe\View\ArrayData;
use SilverStripe\View\Parsers\URLSegmentFilter;
use SilverStripe\View\Requirements;
use SilverStripe\ORM\CMSPreviewable;
use SilverStripe\Core\Config\Config;
use SilverStripe\ORM\DataObjectSchema;
/**
* Class BaseElement
* @package DNADesign\Elemental\Models
*
* @property string $Title
* @property bool $ShowTitle
* @property int $Sort
* @property string $ExtraClass
* @property string $Style
* @property int $ParentID
*
* @mixin Versioned
* @method ElementalArea Parent()
*/
class BaseElement extends DataObject implements CMSPreviewable
{
/**
* Override this on your custom elements to specify a CSS icon class
*
* @var string
*/
private static $icon = 'font-icon-block-layout';
/**
* Describe the purpose of this element
*
* @config
* @var string
*/
private static $description = 'Base element class';
/**
* List of fields to exclude from CMS SiteTree seatch
* @see ElementSiteTreeFilterSearch::applyDefaultFilters()
*/
private static array $fields_excluded_from_cms_search = [
'ExtraClass',
];
private static $db = [
'Title' => 'Varchar(255)',
'ShowTitle' => 'Boolean',
'Sort' => 'Int',
'ExtraClass' => 'Varchar(255)',
'Style' => 'Varchar(255)'
];
private static $has_one = [
'Parent' => ElementalArea::class
];
private static $extensions = [
Versioned::class,
DataExtension::class,
];
private static $casting = [
'BlockSchema' => DBObjectType::class,
'IsLiveVersion' => DBBoolean::class,
'IsPublished' => DBBoolean::class,
'canCreate' => DBBoolean::class,
'canPublish' => DBBoolean::class,
'canUnpublish' => DBBoolean::class,
'canDelete' => DBBoolean::class,
];
private static $indexes = [
'Sort' => true,
];
private static $versioned_gridfield_extensions = true;
private static $table_name = 'Element';
/**
* @var string
*/
private static $controller_class = ElementController::class;
/**
* @var string
*/
private static $controller_template = 'ElementHolder';
/**
* @var ElementController
*/
protected $controller;
private static $show_stage_link = true;
private static $show_live_link = true;
/**
* Cache various data to improve CMS load time
*
* @internal
* @var array
*/
protected $cacheData;
private static $default_sort = 'Sort';
private static $singular_name = 'block';
private static $plural_name = 'blocks';
private static $summary_fields = [
'EditorPreview' => 'Summary'
];
/**
* @config
* @var array
*/
private static $styles = [];
private static $searchable_fields = [
'ID' => [
'field' => NumericField::class,
],
'Title',
'LastEdited'
];
/**
* Enable for backwards compatibility
*
* @var boolean
*/
private static $disable_pretty_anchor_name = false;
/**
* Set to false to prevent an in-line edit form from showing in an elemental area. Instead the element will be
* clickable and a GridFieldDetailForm will be used.
*
* @config
* @var bool
*/
private static $inline_editable = true;
/**
* Display a show title button
*
* @config
* @var boolean
*/
private static $displays_title_in_template = true;
/**
* Determines whether a block should be indexable in search.
*
* @config
* @var boolean
* @see ElementalPageExtension::getElementsForSearch()
*/
private static $search_indexable = true;
/**
* Store used anchor names, this is to avoid title clashes
* when calling 'getAnchor'
*
* @var array
*/
protected static $used_anchors = [];
/**
* For caching 'getAnchor'
*
* @var string
*/
protected $anchor = null;
/**
* Basic permissions, defaults to page perms where possible.
*
* @param Member $member
* @return boolean
*/
public function canView($member = null)
{
$extended = $this->extendedCan(__FUNCTION__, $member);
if ($extended !== null) {
return $extended;
}
if ($this->hasMethod('getPage')) {
if ($page = $this->getPage()) {
return $page->canView($member);
}
}
return Permission::check('CMS_ACCESS', 'any', $member);
}
/**
* Basic permissions, defaults to page perms where possible.
*
* @param Member $member
*
* @return boolean
*/
public function canEdit($member = null)
{
$extended = $this->extendedCan(__FUNCTION__, $member);
if ($extended !== null) {
return $extended;
}
if ($this->hasMethod('getPage')) {
if ($page = $this->getPage()) {
return $page->canEdit($member);
}
}
return Permission::check('CMS_ACCESS', 'any', $member);
}
/**
* Basic permissions, defaults to page perms where possible.
*
* Uses archive not delete so that current stage is respected i.e if a
* element is not published, then it can be deleted by someone who doesn't
* have publishing permissions.
*
* @param Member $member
*
* @return boolean
*/
public function canDelete($member = null)
{
$extended = $this->extendedCan(__FUNCTION__, $member);
if ($extended !== null) {
return $extended;
}
if ($this->hasMethod('getPage')) {
if ($page = $this->getPage()) {
if ($page->hasExtension(Versioned::class)) {
return $page->canArchive($member);
} else {
return $page->canDelete($member);
}
}
}
return Permission::check('CMS_ACCESS', 'any', $member);
}
/**
* Basic permissions, defaults to page perms where possible.
*
* @param Member $member
* @param array $context
*
* @return boolean
*/
public function canCreate($member = null, $context = array())
{
$extended = $this->extendedCan(__FUNCTION__, $member);
if ($extended !== null) {
return $extended;
}
return Permission::check('CMS_ACCESS', 'any', $member);
}
public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false)
{
// Skips writes for broken blocks, so that we can still publish the page to allow all other blocks to publish.
if ($this->ObsoleteClassName) {
return $this->ID;
}
return parent::write($showDebug, $forceInsert, $forceWrite, $writeComponents);
}
/**
* Increment the sort order if one hasn't been already defined. This
* ensures that new elements are created at the end of the list by default.
*
* {@inheritDoc}
*/
public function onBeforeWrite()
{
parent::onBeforeWrite();
// If a Sort has already been set, then we can exit early
if ($this->Sort) {
return;
}
// If no ParentID is currently set for the Element, then we don't want to define an initial Sort yet
if (!$this->ParentID) {
return;
}
if ($this->hasExtension(Versioned::class)) {
$records = Versioned::get_by_stage(BaseElement::class, Versioned::DRAFT);
} else {
$records = BaseElement::get();
}
$records = $records->filter('ParentID', $this->ParentID);
$this->Sort = $records->max('Sort') + 1;
}
public function getCMSFields()
{
$this->beforeUpdateCMSFields(function (FieldList $fields) {
// Remove relationship fields
$fields->removeByName('ParentID');
$fields->removeByName('Sort');
// Remove link and file tracking tabs
$fields->removeByName(['LinkTracking', 'FileTracking']);
$fields->addFieldToTab(
'Root.Settings',
TextField::create('ExtraClass', _t(__CLASS__ . '.ExtraCssClassesLabel', 'Custom CSS classes'))
->setAttribute(
'placeholder',
_t(__CLASS__ . '.ExtraCssClassesPlaceholder', 'my_class another_class')
)
);
// Rename the "Settings" tab
$fields->fieldByName('Root.Settings')
->setTitle(_t(__CLASS__ . '.SettingsTabLabel', 'Settings'));
// Add a combined field for "Title" and "Displayed" checkbox in a Bootstrap input group
$fields->removeByName('ShowTitle');
if ($this->config()->get('displays_title_in_template')) {
$fields->replaceField(
'Title',
TextCheckboxGroupField::create()
->setName('Title')
);
}
// Rename the "Main" tab
$fields->fieldByName('Root.Main')
->setTitle(_t(__CLASS__ . '.MainTabLabel', 'Content'));
$fields->addFieldsToTab('Root.Main', [
HiddenField::create('AbsoluteLink', false, Director::absoluteURL((string) $this->PreviewLink())),
HiddenField::create('LiveLink', false, Director::absoluteURL((string) $this->Link())),
HiddenField::create('StageLink', false, Director::absoluteURL((string) $this->PreviewLink())),
]);
$styles = $this->config()->get('styles');
if ($styles && count($styles ?? []) > 0) {
$styleDropdown = DropdownField::create('Style', _t(__CLASS__.'.STYLE', 'Style variation'), $styles);
$fields->insertBefore('ExtraClass', $styleDropdown);
$styleDropdown->setEmptyString(_t(__CLASS__.'.CUSTOM_STYLES', 'Select a style..'));
} else {
$fields->removeByName('Style');
}
// Hide the navigation section of the tabs in the React component {@see silverstripe/admin Tabs}
$rootTabset = $fields->fieldByName('Root');
$rootTabset->setSchemaState(['hideNav' => true]);
if ($this->isInDB()) {
$fields->addFieldsToTab('Root.History', [
HistoryViewerField::create('ElementHistory')
->addExtraClass('history-viewer--standalone'),
]);
// Add class to containing tab
$fields->fieldByName('Root.History')
->addExtraClass('elemental-block__history-tab tab--history-viewer');
// Hack: automatically navigate to the History tab with `#Root_History` is in the URL
// To unhack, fix this: https://github.com/silverstripe/silverstripe-admin/issues/911
Requirements::customScript(<<<JS
document.addEventListener('DOMContentLoaded', () => {
var hash = window.location.hash.substr(1);
if (hash !== 'Root_History') {
return null;
}
jQuery('.cms-tabset-nav-primary li[aria-controls="Root_History"] a').trigger('click')
});
JS
);
}
});
return parent::getCMSFields();
}
/**
* Get the type of the current block, for use in GridField summaries, block
* type dropdowns etc. Examples are "Content", "File", "Media", etc.
*
* @return string
*/
public function getType()
{
$default = $this->i18n_singular_name() ?: 'Block';
return _t(static::class . '.BlockType', $default);
}
/**
* Proxy through to configuration setting 'inline_editable'
*
* @return bool
*/
public function inlineEditable()
{
return static::config()->get('inline_editable');
}
/**
* @param ElementController $controller
*
* @return $this
*/
public function setController($controller)
{
$this->controller = $controller;
return $this;
}
/**
* @throws Exception If the specified controller class doesn't exist
*
* @return ElementController
*/
public function getController()
{
if ($this->controller) {
return $this->controller;
}
$controllerClass = self::config()->controller_class;
if (!class_exists($controllerClass ?? '')) {
throw new Exception(
'Could not find controller class ' . $controllerClass . ' as defined in ' . static::class
);
}
$this->controller = Injector::inst()->create($controllerClass, $this);
$this->controller->doInit();
return $this->controller;
}
/**
* @param string $name
* @return $this
*/
public function setAreaRelationNameCache($name)
{
$this->cacheData['area_relation_name'] = $name;
return $this;
}
/**
* @return Controller
*/
public function Top()
{
return (Controller::has_curr()) ? Controller::curr() : null;
}
/**
* Determines whether this elemental block is indexable in search.
*
* By default, this uses the configurable variable search_indexable, but
* this method can be overridden to provide more complex logic if required.
*
* @return boolean
*/
public function getSearchIndexable(): bool
{
return (bool) $this->config()->get('search_indexable');
}
/**
* Provides content to be indexed in search.
*
* @return string
*/
public function getContentForSearchIndex(): string
{
// Strips tags but be sure there's a space between words.
$content = trim(strip_tags(str_replace('<', ' <', $this->forTemplate() ?? '') ?? ''));
// Allow projects to update indexable content of third-party elements.
$this->extend('updateContentForSearchIndex', $content);
return $content;
}
/**
* Provides content for CMS search if ElementSiteTreeFilterSearch.render_elements is false
*/
public function getContentForCmsSearch(): string
{
$fieldNames = $this->getTextualDatabaseFieldNames();
$excludedFieldNames = $this->getFieldNamesExcludedFromCmsSearch();
$contents = [];
foreach ($fieldNames as $fieldName) {
if (in_array($fieldName, $excludedFieldNames)) {
continue;
}
$contents[] = $this->$fieldName;
}
// Allow projects to update contents of third-party elements.
$this->extend('updateContentForCmsSearch', $contents);
// Use |#| to delimit different fields rather than space so that you don't
// accidentally join results of two columns that are next to each other in a table
$content = implode('|#|', array_filter($contents));
// Strips tags and be sure there's a space between words.
$content = trim(strip_tags(str_replace('<', ' <', $content)));
return $content;
}
/**
* Get field names that have a Varchar or Text like type in the database
*/
private function getTextualDatabaseFieldNames(): array
{
$fieldNames = [];
$textualDatabaseFields = DataObject::getSchema()->databaseFields($this);
foreach ($textualDatabaseFields as $fieldName => $databaseFieldType) {
$lcType = strtolower(strtok($databaseFieldType ?? '', '('));
if (str_contains($lcType, 'varchar') || str_contains($lcType, 'text')) {
$fieldNames[] = $fieldName;
}
}
return $fieldNames;
}
private function getFieldNamesExcludedFromCmsSearch(): array
{
return [
// `fixed_fields` contains ['ID', 'ClassName', 'LastEdited', 'Created'] and possibly more
...array_keys(static::config()->get('fixed_fields')),
// manually excluded fields
...static::config()->get('fields_excluded_from_cms_search')
];
}
/**
* Default way to render element in templates. Note that all blocks should
* be rendered through their {@link ElementController} class as this
* contains the holder styles.
*
* @return string|null HTML
*/
public function forTemplate($holder = true)
{
$templates = $this->getRenderTemplates();
if ($templates) {
return $this->renderWith($templates);
}
return null;
}
/**
* @param string $suffix
*
* @return array
*/
public function getRenderTemplates($suffix = '')
{
$classes = ClassInfo::ancestry($this->ClassName);
$classes[static::class] = static::class;
$classes = array_reverse($classes ?? []);
$templates = [];
foreach ($classes as $key => $class) {
if ($class == BaseElement::class) {
continue;
}
if ($class == DataObject::class) {
break;
}
if ($style = $this->Style) {
$templates[$class][] = $class . $suffix . '_'. $this->getAreaRelationName() . '_' . $style;
$templates[$class][] = $class . $suffix . '_' . $style;
}
$templates[$class][] = $class . $suffix . '_'. $this->getAreaRelationName();
$templates[$class][] = $class . $suffix;
}
$this->extend('updateRenderTemplates', $templates, $suffix);
$templateFlat = [];
foreach ($templates as $class => $variations) {
$templateFlat = array_merge($templateFlat, $variations);
}
return $templateFlat;
}
/**
* Given form data (wit
*
* @param $data
*/
public function updateFromFormData($data)
{
$cmsFields = $this->getCMSFields();
foreach ($data as $field => $datum) {
$field = $cmsFields->dataFieldByName($field);
if (!$field) {
continue;
}
$field->setSubmittedValue($datum);
$field->saveInto($this);
}
}
/**
* Strip all namespaces from class namespace.
*
* @param string $classname e.g. "\Fully\Namespaced\Class"
*
* @return string following the param example, "Class"
*/
protected function stripNamespacing($classname)
{
$classParts = explode('\\', $classname ?? '');
return array_pop($classParts);
}
/**
* @return string
*/
public function getSimpleClassName()
{
return strtolower($this->sanitiseClassName($this->ClassName, '__') ?? '');
}
/**
* Despite the name of the method, getPage can return any type of DataObject
*
* @return null|DataObject
* @throws \Psr\Container\NotFoundExceptionInterface
* @throws \SilverStripe\ORM\ValidationException
*/
public function getPage()
{
if (isset($this->cacheData['page'])) {
if (isset($this->cacheData['parent_id']) && $this->cacheData['parent_id'] === $this->ParentID) {
return $this->cacheData['page'];
}
}
$class = DataObject::getSchema()->hasOneComponent($this, 'Parent');
$area = ($this->ParentID) ? DataObject::get_by_id($class, $this->ParentID) : null;
if ($area instanceof ElementalArea && $area->exists()) {
$page = $area->getOwnerPage();
$this->cacheData['page'] = $page;
$this->cacheData['parent_id'] = $this->ParentID;
return $this->cacheData['page'];
}
return null;
}
/**
* Get a unique anchor name
*
* @return string
*/
public function getAnchor()
{
if ($this->anchor !== null) {
return $this->anchor;
}
$anchorTitle = '';
if (!$this->config()->disable_pretty_anchor_name) {
if ($this->hasMethod('getAnchorTitle')) {
$anchorTitle = $this->getAnchorTitle();
} elseif ($this->config()->enable_title_in_template) {
$anchorTitle = $this->getField('Title');
}
}
if (!$anchorTitle) {
$anchorTitle = 'e'.$this->ID;
}
$filter = URLSegmentFilter::create();
$titleAsURL = $filter->filter($anchorTitle);
// Ensure that this anchor name isn't already in use
// ie. If two elemental blocks have the same title, it'll append '-2', '-3'
$result = $titleAsURL;
$count = 1;
while (isset(self::$used_anchors[$result]) && self::$used_anchors[$result] !== $this->ID) {
++$count;
$result = $titleAsURL . '-' . $count;
}
self::$used_anchors[$result] = $this->ID;
return $this->anchor = $result;
}
/**
* Get anchors in this block's content.
* Used to populate the "anchor on a page" link in the WYSIWYG
*
* By default, this finds anchors in any HTMLText field on the block, but
* this method should be overridden if anchors are provided in other ways
* for this block or if not all HTMLText fields for this block are
* displayed on the front-end.
*/
public function getAnchorsInContent(): array
{
$anchors = [$this->getAnchor()];
$anchorRegex = "/\\s+(name|id)\\s*=\\s*([\"'])([^\\2\\s>]*?)\\2|\\s+(name|id)\\s*=\\s*([^\"']+)[\\s +>]/im";
$allFields = DataObject::getSchema()->fieldSpecs($this);
foreach ($allFields as $field => $fieldSpec) {
$fieldObj = $this->owner->dbObject($field);
if ($fieldObj instanceof DBHTMLText) {
$parseSuccess = preg_match_all($anchorRegex, $fieldObj->getValue() ?? '', $matches);
if ($parseSuccess >= 1) {
$fieldAnchors = array_values(array_filter(
array_merge($matches[3], $matches[5])
));
$anchors = array_merge($anchors, $fieldAnchors);
}
}
}
$anchors = array_unique($anchors);
$this->extend('updateAnchorsInContent', $anchors);
return $anchors;
}
/**
* @param string|null $action
* @return string|null
* @throws \Psr\Container\NotFoundExceptionInterface
* @throws \SilverStripe\ORM\ValidationException
*/
public function AbsoluteLink($action = null)
{
$page = $this->getPage();
if ($page && ClassInfo::hasMethod($page, 'AbsoluteLink')) {
$link = $page->AbsoluteLink($action) . '#' . $this->getAnchor();
$this->extend('updateAbsoluteLink', $link);
return $link;
}
return null;
}
/**
* @param string|null $action
* @return string|null
* @throws \Psr\Container\NotFoundExceptionInterface
* @throws \SilverStripe\ORM\ValidationException
*/
public function Link($action = null)
{
$page = $this->getPage();
if ($page && ClassInfo::hasMethod($page, 'Link')) {
$link = $page->Link($action) . '#' . $this->getAnchor();
$this->extend('updateLink', $link);
return $link;
}
return null;
}
/**
* @param string|null $action
* @return string|null
* @throws \Psr\Container\NotFoundExceptionInterface
* @throws \SilverStripe\ORM\ValidationException
*/
public function PreviewLink($action = null)
{
$link = null;
if ($page = $this->getPage()) {
if (ClassInfo::hasMethod($page, 'Link')) {
$link = $page->Link($action);
}
if (!$link && ($page instanceof CMSPreviewable)) {
$link = $page->PreviewLink($action);
}
if ($link) {
// The ElementalPreview getvar is used in ElementalPageExtension
// The anchor must be at the end of the URL to function correctly
$link = Controller::join_links($link, '?ElementalPreview=' . mt_rand() . '#' . $this->getAnchor());
}
}
$this->extend('updatePreviewLink', $link);
return $link;
}
/**
* @return boolean
*/
public function isCMSPreview()
{
if (Controller::has_curr()) {
$controller = Controller::curr();
if ($controller->getRequest()->requestVar('CMSPreview')) {
return true;
}
}
return false;
}
/**
* @param bool $directLink Indicates that the GridFieldDetailEdit form link should be given even if the block can be
* edited in-line.
* @return null|string
* @throws \SilverStripe\ORM\ValidationException
*/
public function CMSEditLink($directLink = false)
{
// Allow for repeated calls to be returned from cache
if (isset($this->cacheData['cms_edit_link'])) {
return $this->cacheData['cms_edit_link'];
}
$link = $this->getElementCMSLink($directLink);
$this->extend('updateCMSEditLink', $link);
if ($link) {
$this->cacheData['cms_edit_link'] = $link;
}
return $link;
}
/**
* @param bool $directLink
* @return null|string
*/
private function getElementCMSLink(bool $directLink)
{
$relationName = $this->getAreaRelationName();
$page = $this->getPage();
$link = null;
if (!$page) {
return $link;
}
if ($page instanceof SiteTree) {
$link = $page->CMSEditLink();
} elseif (ClassInfo::hasMethod($page, 'CMSEditLink')) {
$link = Controller::join_links($page->CMSEditLink(), 'ItemEditForm');
}
// In-line editable blocks should just take you to the page.
// Editable ones should add the suffix for detail form.
if (!$this->inlineEditable() || $directLink) {
if ($page instanceof SiteTree) {
return Controller::join_links(
singleton(CMSPageEditController::class)->Link('EditForm'),
$page->ID,
'field',
$relationName,
'item',
$this->ID,
'edit'
);
} else {
// If $page is not a Page, then generate $link base on $page->CMSEditLink()
return Controller::join_links(
$link,
'field',
$relationName,
'item',
$this->ID,
'edit'
);
}
}
return $link;
}
/**
* Retrieve a elemental area relation for creating cms links
*
* @return int|string The name of a valid elemental area relation
* @throws \Psr\Container\NotFoundExceptionInterface
* @throws \SilverStripe\ORM\ValidationException
*/
public function getAreaRelationName()
{
// Allow repeated calls to return from internal cache
if (isset($this->cacheData['area_relation_name'])) {
return $this->cacheData['area_relation_name'];
}
$page = $this->getPage();
$result = 'ElementalArea';
if ($page) {
$class = DataObject::getSchema()->hasOneComponent($this, 'Parent');
$area = $this->ParentID ? DataObject::get_by_id($class, $this->ParentID) : null;
if ($area) {
$has_one = $page->config()->get('has_one');
foreach ($has_one as $relationName => $relationClass) {
if ($page instanceof BaseElement && $relationName === 'Parent') {
continue;
}
if ($relationClass === $area->ClassName && $page->{$relationName}()->ID === $area->ID) {
$result = $relationName;
break;
}
}
}
}
$this->setAreaRelationNameCache($result);
return $result;
}
/**
* Sanitise a model class' name for inclusion in a link.
*
* @return string
*/
public function sanitiseClassName($class, $delimiter = '-')
{
return str_replace('\\', $delimiter ?? '', $class ?? '');
}
public function unsanitiseClassName($class, $delimiter = '-')