forked from silverstripe/silverstripe-admin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeftAndMain.php
1568 lines (1403 loc) · 50.9 KB
/
LeftAndMain.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\Admin;
use InvalidArgumentException;
use LogicException;
use ReflectionClass;
use SilverStripe\CMS\Controllers\CMSMain;
use SilverStripe\Admin\Navigator\SilverStripeNavigator;
use SilverStripe\Control\Controller;
use SilverStripe\Control\Director;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Control\HTTPResponse_Exception;
use SilverStripe\Control\PjaxResponseNegotiator;
use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Convert;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Core\Manifest\ModuleResourceLoader;
use SilverStripe\Core\Manifest\VersionProvider;
use SilverStripe\Dev\TestOnly;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\Form;
use SilverStripe\Forms\FormAction;
use SilverStripe\Forms\HiddenField;
use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\PrintableTransformation;
use SilverStripe\i18n\i18n;
use SilverStripe\Model\List\ArrayList;
use SilverStripe\ORM\CMSPreviewable;
use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\ORM\FieldType\DBHTMLText;
use SilverStripe\ORM\Hierarchy\Hierarchy;
use SilverStripe\Model\List\SS_List;
use SilverStripe\Core\Validation\ValidationException;
use SilverStripe\Core\Validation\ValidationResult;
use SilverStripe\Security\Permission;
use SilverStripe\Security\PermissionProvider;
use SilverStripe\Security\Security;
use SilverStripe\Security\SecurityToken;
use SilverStripe\SiteConfig\SiteConfig;
use SilverStripe\Model\ArrayData;
use SilverStripe\View\Requirements;
use SilverStripe\View\SSViewer;
/**
* LeftAndMain is the parent class of all the two-pane views in the CMS.
* If you are wanting to add more areas to the CMS, you can do it by subclassing LeftAndMain.
*
* This is essentially an abstract class which should be subclassed.
* See {@link CMSMain} for a good example.
*/
class LeftAndMain extends FormSchemaController implements PermissionProvider
{
/**
* Enable front-end debugging (increases verbosity) in dev mode.
* Will be ignored in live environments.
*
* @var bool
*/
private static $client_debugging = true;
/**
* @config
* @var string
*/
private static $menu_title;
/**
* @config
* @var string
*/
private static $menu_icon;
/**
* @config
* @var int
*/
private static $menu_priority = 0;
/**
* When set to true, this controller isn't given a menu item in the left panel in the CMS.
*/
private static bool $ignore_menuitem = false;
/**
* A subclass of {@link DataObject}.
*
* Determines what is managed in this interface, through
* {@link getEditForm()} and other logic.
*/
private static ?string $model_class = null;
/**
* @var array
*/
private static $allowed_actions = [
'index',
'save',
'printable',
'show',
'EditForm',
'AddForm',
'batchactions',
'BatchActionsForm',
];
private static $dependencies = [
'VersionProvider' => '%$' . VersionProvider::class,
];
/**
* Current pageID for this request
*
* @var null
*/
protected $pageID = null;
/**
* Set by {@link LeftAndMainErrorExtension} if an http error occurs
*/
private string $httpErrorMessage;
/**
* Used to allow errors to be displayed using a front-end template
*/
private bool $suppressAdminErrorContext = false;
/**
* Themes to use within the CMS
*
* Default themes are assigned in _config/themes.yml
*
* @config
* @var array
*/
private static $admin_themes = [];
/**
* Namespace for session info, e.g. current record.
* Defaults to the current class name, but can be amended to share a namespace in case
* controllers are logically bundled together, and mainly separated
* to achieve more flexible templating.
*
* @config
* @var string
*/
private static $session_namespace;
/**
* Register additional requirements through the {@link Requirements} class.
* Used mainly to work around the missing "lazy loading" functionality
* for getting css/javascript required after an ajax-call (e.g. loading the editform).
*
* YAML configuration example:
* <code>
* LeftAndMain:
* extra_requirements_javascript:
* - mysite/javascript/myscript.js
* mysite/javascript/anotherscript.js:
* defer: true
* </code>
*
* @config
* @var array
*/
private static $extra_requirements_javascript = [];
/**
* Register additional i18n requirements through the {@link Requirements} class.
*
* YAML configuration example:
* <code>
* LeftAndMain:
* extra_requirements_i18n:
* - mysite/client/lang
* 'myorg/mymodule:client/lang': true
* </code>
* @var array See {@link extra_requirements_javascript}
*/
private static array $extra_requirements_i18n = [];
/**
* YAML configuration example:
* <code>
* LeftAndMain:
* extra_requirements_css:
* mysite/css/mystyle.css:
* media: screen
* </code>
*
* @config
* @var array See {@link extra_requirements_javascript}
*/
private static $extra_requirements_css = [];
/**
* @config
* @var array See {@link extra_requirements_javascript}
*/
private static $extra_requirements_themedCss = [];
/**
* If true, call a keepalive ping every 5 minutes from the CMS interface,
* to ensure that the session never dies.
*
* @config
* @var bool
*/
private static $session_keepalive_ping = true;
/**
* Value of X-Frame-Options header
*
* @config
* @var string
*/
private static $frame_options = 'SAMEORIGIN';
/**
* The urls used for the links in the Help dropdown in the backend
*
* Set this to `false` via yml config if you do not want to show any help links
*
* @config
* @var array
*/
private static $help_links = [
'CMS User help' => 'https://userhelp.silverstripe.org/en/6/',
'Developer docs' => 'https://docs.silverstripe.org/en/6/',
'Community' => 'https://www.silverstripe.org/',
'Feedback' => 'https://www.silverstripe.org/give-feedback/',
];
/**
* The href for the anchor on the Silverstripe logo
*
* @config
* @var string
*/
private static $application_link = '//www.silverstripe.org/';
/**
* The application name
*
* @config
* @var string
*/
private static $application_name = 'Silverstripe';
/**
* @var PjaxResponseNegotiator
*/
protected $responseNegotiator;
/**
* @var VersionProvider
*/
protected $versionProvider;
/**
* Cached search filter instance for current search
*
* @var LeftAndMain_SearchFilter
*/
protected $searchFilterCache = null;
/**
* Gets the combined configuration of all LeftAndMain subclasses required by the client app.
*
* @return string
*
* WARNING: Experimental API
*/
public function getCombinedClientConfig()
{
$combinedClientConfig = ['sections' => []];
$cmsClassNames = CMSMenu::get_cms_classes(AdminController::class, true, CMSMenu::URL_PRIORITY);
// append LeftAndMain to the list as well
$cmsClassNames[] = LeftAndMain::class;
foreach ($cmsClassNames as $className) {
$combinedClientConfig['sections'][] = Injector::inst()->get($className)->getClientConfig();
}
// Pass in base url (absolute and relative)
$combinedClientConfig['baseUrl'] = Director::baseURL();
$combinedClientConfig['absoluteBaseUrl'] = Director::absoluteBaseURL();
$combinedClientConfig['adminUrl'] = AdminRootController::admin_url();
// Get "global" CSRF token for use in JavaScript
$token = SecurityToken::inst();
$combinedClientConfig[$token->getName()] = $token->getValue();
// Set env
$combinedClientConfig['environment'] = Director::get_environment_type();
$combinedClientConfig['debugging'] = LeftAndMain::config()->uninherited('client_debugging');
return json_encode($combinedClientConfig);
}
public function getClientConfig(): array
{
// Add WYSIWYG link form schema before extensions are applied
$this->beforeExtending('updateClientConfig', function (array &$clientConfig): void {
$modalController = ModalController::singleton();
foreach (array_keys(ModalController::config()->get('link_modal_form_factories')) as $name) {
$clientConfig['form'][$name]['schemaUrl'] = $modalController->Link('linkModalFormSchema/' . $name . '/:pageid');
}
});
return parent::getClientConfig();
}
/**
* Try to redirect to an appropriate admin section if we can't access this one
*/
public function onInitPermissionFailure(): void
{
$menu = $this->MainMenu();
foreach ($menu as $candidate) {
if ($candidate->Link &&
$candidate->Link != $this->Link()
&& $candidate->MenuItem->controller
&& singleton($candidate->MenuItem->controller)->canView()
) {
$this->redirect($candidate->Link);
return;
}
}
$this->suppressAdminErrorContext = true;
}
protected function init()
{
$this->beforeExtending('onInit', function () {
// Audit logging hook
if (empty($_REQUEST['executeForm']) && !$this->getRequest()->isAjax()) {
$this->extend('accessedCMS');
}
Requirements::customScript("
window.ss = window.ss || {};
window.ss.config = " . $this->getCombinedClientConfig() . ";
");
Requirements::javascript('silverstripe/admin: client/dist/js/vendor.js');
Requirements::javascript('silverstripe/admin: client/dist/js/bundle.js');
// Bootstrap components
Requirements::javascript('silverstripe/admin: thirdparty/popper/popper.min.js');
Requirements::javascript('silverstripe/admin: thirdparty/bootstrap/js/dist/util.js');
Requirements::javascript('silverstripe/admin: thirdparty/bootstrap/js/dist/collapse.js');
Requirements::javascript('silverstripe/admin: thirdparty/bootstrap/js/dist/tooltip.js');
Requirements::customScript(
"window.jQuery('body').tooltip({ selector: '[data-toggle=tooltip]' });",
'bootstrap.tooltip-boot'
);
Requirements::css('silverstripe/admin: client/dist/styles/bundle.css');
Requirements::add_i18n_javascript('silverstripe/admin:client/lang');
Requirements::add_i18n_javascript('silverstripe/admin:client/dist/moment-locales', false);
if (LeftAndMain::config()->uninherited('session_keepalive_ping')) {
Requirements::javascript('silverstripe/admin: client/dist/js/LeftAndMain.Ping.js');
}
// Custom requirements
$extraJs = $this->config()->get('extra_requirements_javascript');
if ($extraJs) {
foreach ($extraJs as $file => $config) {
if (is_numeric($file)) {
$file = $config;
$config = [];
}
Requirements::javascript($file, $config);
}
}
$extraI18n = $this->config()->get('extra_requirements_i18n');
if ($extraI18n) {
foreach ($extraI18n as $dir => $return) {
if (is_numeric($dir)) {
$dir = $return;
$return = false;
}
Requirements::add_i18n_javascript($dir, $return);
}
}
$extraCss = $this->config()->get('extra_requirements_css');
if ($extraCss) {
foreach ($extraCss as $file => $config) {
if (is_numeric($file)) {
$file = $config;
$config = [];
}
$media = null;
if (isset($config['media'])) {
$media = $config['media'];
unset($config['media']);
}
Requirements::css($file, $media, $config);
}
}
$extraThemedCss = $this->config()->get('extra_requirements_themedCss');
if ($extraThemedCss) {
foreach ($extraThemedCss as $file => $config) {
if (is_numeric($file)) {
$file = $config;
$config = [];
}
$media = null;
if (isset($config['media'])) {
$media = $config['media'];
unset($config['media']);
}
Requirements::themedCSS($file, $media, $config);
}
}
});
// Run parent init and process the onInit extension hook
parent::init();
}
public function afterHandleRequest()
{
if (!$this->suppressAdminErrorContext
&& $this->response->isError()
&& !$this->request->isAjax()
&& $this->response->getHeader('Content-Type') !== 'application/json'
) {
$this->init();
$errorCode = $this->response->getStatusCode();
$errorType = $this->response->getStatusDescription();
$defaultMessage = _t(
LeftAndMain::class . '.ErrorMessage',
'Sorry, it seems there was a {errorcode} error.',
['errorcode' => $errorCode]
);
$this->response = HTTPResponse::create($this->render([
'Title' => $this->getApplicationName() . ' - ' . $errorType,
'Content' => $this->renderWith($this->getTemplatesWithSuffix('_Error'), [
'ErrorCode' => $errorCode,
'ErrorType' => $errorType,
'Message' => DBField::create_field(
'HTMLFragment',
/** @phpstan-ignore translation.key (we need the key to be dynamic here) */
_t(LeftAndMain::class . '.ErrorMessage' . $errorCode, $defaultMessage)
),
]),
]), $errorCode, $errorType);
}
parent::afterHandleRequest();
}
public function handleRequest(HTTPRequest $request): HTTPResponse
{
try {
$response = parent::handleRequest($request);
} catch (ValidationException $e) {
// Nicer presentation of model-level validation errors
$msgs = _t(__CLASS__ . '.ValidationError', 'Validation error') . ': '
. $e->getMessage();
$e = new HTTPResponse_Exception($msgs, 403);
$errorResponse = $e->getResponse();
$errorResponse->addHeader('Content-Type', 'text/plain');
$errorResponse->addHeader('X-Status', rawurlencode($msgs));
$e->setResponse($errorResponse);
throw $e;
}
$title = $this->Title();
if (!$response->getHeader('X-Controller')) {
$response->addHeader('X-Controller', static::class);
}
if (!$response->getHeader('X-Title')) {
$response->addHeader('X-Title', urlencode($title ?? ''));
}
// Prevent clickjacking, see https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options
$originalResponse = $this->getResponse();
$originalResponse->addHeader('X-Frame-Options', LeftAndMain::config()->uninherited('frame_options'));
$originalResponse->addHeader('Vary', 'X-Requested-With');
return $response;
}
public function index(HTTPRequest $request): HTTPResponse
{
return $this->getResponseNegotiator()->respond($request);
}
/**
* If this is set to true, the "switchView" context in the
* template is shown, with links to the staging and publish site.
*
* @return bool
*/
public function ShowSwitchView()
{
return false;
}
/**
* Get menu title for this section (translated)
*
* @param string $class Optional class name if called on LeftAndMain directly
* @param bool $localise Determine if menu title should be localised via i18n.
* @return string Menu title for the given class
*/
public static function menu_title($class = null, $localise = true)
{
if ($class && is_subclass_of($class, __CLASS__)) {
// Respect oveloading of menu_title() in subclasses
return $class::menu_title(null, $localise);
}
if (!$class) {
$class = get_called_class();
}
// Get default class title
$title = static::config()->get('menu_title');
if (!$title) {
$title = preg_replace('/Admin$/', '', $class ?? '');
}
// Check localisation
if (!$localise) {
return $title;
}
/** @phpstan-ignore translation.key (we need the key to be dynamic here) */
return i18n::_t("{$class}.MENUTITLE", $title);
}
/**
* Return styling for the menu icon, if a custom icon is set for this class
*
* Example: static $menu-icon = '/path/to/image/';
* @param string $class
* @return string
*/
public static function menu_icon_for_class($class)
{
$icon = Config::inst()->get($class, 'menu_icon');
if (!empty($icon)) {
$iconURL = ModuleResourceLoader::resourceURL($icon);
$class = strtolower(Convert::raw2htmlname(str_replace('\\', '-', $class ?? '')) ?? '');
return ".icon.icon-16.icon-{$class} { background-image: url('{$iconURL}'); } ";
}
return '';
}
/**
* Return the web font icon class name for this interface icon. Uses the
* built in SilveStripe webfont. {@see menu_icon_for_class()} for providing
* a background image.
*
* @param string $class .
* @return string
*/
public static function menu_icon_class_for_class($class)
{
return Config::inst()->get($class, 'menu_icon_class');
}
/**
* @throws HTTPResponse_Exception
*/
public function show(HTTPRequest $request): HTTPResponse
{
if ($request->param('ID')) {
$this->setCurrentRecordID($request->param('ID'));
}
return $this->getResponseNegotiator()->respond($request);
}
public function getResponseNegotiator(): PjaxResponseNegotiator
{
if (!$this->responseNegotiator) {
$this->responseNegotiator = new PjaxResponseNegotiator(
[
'CurrentForm' => function () {
return $this->getEditForm()->forTemplate();
},
'Content' => function () {
return $this->renderWith($this->getTemplatesWithSuffix('_Content'));
},
'Breadcrumbs' => function () {
return $this->renderWith([
'type' => 'Includes',
'SilverStripe\\Admin\\CMSBreadcrumbs'
]);
},
'ValidationResult' => function () {
return $this->prepareDataForPjax([
'isValid' => true,
'messages' => []
]);
},
'default' => function () {
return $this->renderWith($this->getViewer('show'));
}
],
$this->getResponse()
);
}
return $this->responseNegotiator;
}
//------------------------------------------------------------------------------------------//
// Main UI components
/**
* Returns the main menu of the CMS. This is also used by init()
* to work out which sections the user has access to.
*
* @param bool $cached
* @return SS_List
*/
public function MainMenu($cached = true)
{
if (!isset($this->_cache_MainMenu) || !$cached) {
// Don't accidentally return a menu if you're not logged in - it's used to determine access.
if (!Security::getCurrentUser()) {
return new ArrayList();
}
// Encode into DO set
$menu = new ArrayList();
$menuItems = CMSMenu::get_viewable_menu_items();
// extra styling for custom menu-icons
$menuIconStyling = '';
if ($menuItems) {
foreach ($menuItems as $code => $menuItem) {
// alternate permission checks (in addition to LeftAndMain->canView())
if (isset($menuItem->controller)
&& $this->hasMethod('alternateMenuDisplayCheck')
&& !$this->alternateMenuDisplayCheck($menuItem->controller)
) {
continue;
}
$linkingmode = "link";
if ($menuItem->controller && get_class($this) == $menuItem->controller) {
$linkingmode = "current";
} elseif (strpos($this->Link() ?? '', $menuItem->url ?? '') !== false) {
if ($this->Link() == $menuItem->url) {
$linkingmode = "current";
// default menu is the one with a blank {@link url_segment}
} elseif (singleton($menuItem->controller)->config()->get('url_segment') == '') {
if ($this->Link() == AdminRootController::admin_url()) {
$linkingmode = "current";
}
} else {
$linkingmode = "current";
}
}
// already set in CMSMenu::populate_menu(), but from a static pre-controller
// context, so doesn't respect the current user locale in _t() calls - as a workaround,
// we simply call LeftAndMain::menu_title() again
// if we're dealing with a controller
if ($menuItem->controller) {
$title = LeftAndMain::menu_title($menuItem->controller);
} else {
$title = $menuItem->title;
}
// Provide styling for custom $menu-icon. Done here instead of in
// CMSMenu::populate_menu(), because the icon is part of
// the CMS right pane for the specified class as well...
$iconClass = '';
$hasCSSIcon = false;
if ($menuItem->controller) {
$menuIcon = LeftAndMain::menu_icon_for_class($menuItem->controller);
if (!empty($menuIcon)) {
$menuIconStyling .= $menuIcon;
$hasCSSIcon = true;
} else {
$iconClass = LeftAndMain::menu_icon_class_for_class($menuItem->controller);
}
} else {
$iconClass = $menuItem->iconClass;
}
$menu->push(new ArrayData([
"MenuItem" => $menuItem,
"AttributesHTML" => $menuItem->getAttributesHTML(),
"Title" => $title,
"Code" => $code,
"Icon" => strtolower($code ?? ''),
"IconClass" => $iconClass,
"HasCSSIcon" => $hasCSSIcon,
"Link" => $menuItem->url,
"LinkingMode" => $linkingmode
]));
}
}
if ($menuIconStyling) {
Requirements::customCSS($menuIconStyling);
}
$this->_cache_MainMenu = $menu;
}
return $this->_cache_MainMenu;
}
public function Menu()
{
return $this->renderWith($this->getTemplatesWithSuffix('_Menu'));
}
/**
* @return ArrayData A single menu entry (see {@link MainMenu})
*/
public function MenuCurrentItem()
{
$items = $this->MainMenu();
return $items->find('LinkingMode', 'current');
}
/**
* Return appropriate template candidates for this class, with the given suffix using
* {@link SSViewer::get_templates_by_class()}
*/
public function getTemplatesWithSuffix(string $suffix): array
{
return SSViewer::get_templates_by_class(get_class($this), $suffix, __CLASS__);
}
public function Content()
{
return $this->renderWith($this->getTemplatesWithSuffix('_Content'));
}
/**
* Render $PreviewPanel content
*
* @return DBHTMLText
*/
public function PreviewPanel()
{
$template = $this->getTemplatesWithSuffix('_PreviewPanel');
// Only render sections with preview panel
$engine = $this->getTemplateEngine();
if ($engine->hasTemplate($template)) {
return $this->renderWith($template);
}
return null;
}
/**
* Get the class of the model which is managed by this controller.
* @return class-string<DataObject>
*/
public function getModelClass(): string
{
return static::config()->get('model_class') ?? '';
}
/**
* Get dataobject from the current ID
*
* @param int|DataObject $id ID or object
*/
public function getRecord($id): ?DataObject
{
$className = $this->getModelClass();
if (!$className) {
return null;
}
if ($id instanceof $className) {
return $id;
}
if ($id === 'root') {
return DataObject::singleton($className);
}
if (is_numeric($id)) {
return DataObject::get_by_id($className, $id);
}
return null;
}
/**
* @param bool $unlinked
* @return ArrayList<ArrayData>
*/
public function Breadcrumbs($unlinked = false)
{
$items = new ArrayList([
new ArrayData([
'Title' => $this->menu_title(),
'Link' => ($unlinked) ? false : $this->Link()
])
]);
return $items;
}
/**
* Gets the current search filter for this request, if available
*
* @throws InvalidArgumentException
* @return LeftAndMain_SearchFilter
*/
protected function getSearchFilter()
{
if ($this->searchFilterCache) {
return $this->searchFilterCache;
}
// Check for given FilterClass
$params = $this->getRequest()->getVar('q');
if (empty($params['FilterClass'])) {
return null;
}
// Validate classname
$filterClass = $params['FilterClass'];
$filterInfo = new ReflectionClass($filterClass);
if (!$filterInfo->implementsInterface(LeftAndMain_SearchFilter::class)) {
throw new InvalidArgumentException(sprintf('Invalid filter class passed: %s', $filterClass));
}
return $this->searchFilterCache = Injector::inst()->createWithArgs($filterClass, [$params]);
}
/**
* Save handler
*/
public function save(array $data, Form $form): HTTPResponse
{
$request = $this->getRequest();
$className = $this->getModelClass();
// Existing or new record?
$id = $data['ID'];
if (is_numeric($id) && $id > 0) {
$record = DataObject::get_by_id($className, $id);
if ($record && !$record->canEdit()) {
return Security::permissionFailure($this);
}
if (!$record || !$record->ID) {
$this->httpError(404, "Bad record ID #" . (int)$id);
}
} else {
if (!DataObject::singleton($className)->canCreate()) {
return Security::permissionFailure($this);
}
$record = $this->getNewItem($id, false);
}
// save form data into record
$form->saveInto($record, true);
$record->write();
$this->extend('onAfterSave', $record);
$this->setCurrentRecordID($record->ID);
$message = _t(__CLASS__ . '.SAVEDUP', 'Saved.');
if ($this->getSchemaRequested()) {
$schemaId = Controller::join_links($this->Link('schema/DetailEditForm'), $id);
// Ensure that newly created records have all their data loaded back into the form.
$form->loadDataFrom($record);
$form->setMessage($message, 'good');
$response = $this->getSchemaResponse($schemaId, $form);
} else {
$response = $this->getResponseNegotiator()->respond($request);
}
$response->addHeader('X-Status', rawurlencode($message ?? ''));
return $response;
}
/**
* Create new item.
*
* @param string|int $id
* @param bool $setID
* @return DataObject
*/
public function getNewItem($id, $setID = true)
{
$class = $this->getModelClass();
$object = Injector::inst()->create($class);
if ($setID) {
$object->ID = $id;
}
return $object;
}
public function delete(array $data, Form $form): HTTPResponse
{
$className = $this->getModelClass();
$id = $data['ID'];
$record = DataObject::get_by_id($className, $id);
if ($record && !$record->canDelete()) {
return Security::permissionFailure();
}
if (!$record || !$record->ID) {
$this->httpError(404, "Bad record ID #" . (int)$id);
}
$record->delete();
$this->getResponse()->addHeader(
'X-Status',
rawurlencode(_t(__CLASS__ . '.DELETED', 'Deleted.') ?? '')
);
return $this->getResponseNegotiator()->respond(
$this->getRequest(),
['currentform' => [$this, 'EmptyForm']]
);
}
/**
* Retrieves an edit form, either for display, or to process submitted data.
* Also used in the template rendered through {@link Right()} in the $EditForm placeholder.
*
* This is a "pseudo-abstract" method, usually connected to a {@link getEditForm()}
* method in an entwine subclass. This method can accept a record identifier,
* selected either in custom logic, or through {@link currentRecordID()}.
* The form usually construct itself from {@link DataObject->getCMSFields()}
* for the specific managed subclass defined in {@link LeftAndMain::getModelClass()}.
*
* @param HTTPRequest $request Passed if executing a HTTPRequest directly on the form.
* If empty, this is invoked as $EditForm in the template
* @return Form Should return a form regardless wether a record has been found.
* Form might be readonly if the current user doesn't have the permission to edit
* the record.
*/
public function EditForm($request = null)
{
return $this->getEditForm();
}
/**
* Calls {@link SiteTree->getCMSFields()} by default to determine the form fields to display.
*
* @param int $id
* @param FieldList $fields
* @return Form
*/
public function getEditForm($id = null, $fields = null)
{
if (!$id) {
$id = $this->currentRecordID();
}
// Check record exists
$record = $this->getRecord($id);
if (!$record) {
return $this->EmptyForm();
}
// Check if this record is viewable
if ($record && !$record->canView()) {
$response = Security::permissionFailure($this);
$this->setResponse($response);
return null;
}
$fields = $fields ?: $record->getCMSFields();
if (!$fields) {
throw new LogicException(
"getCMSFields() returned null - it should return a FieldList object.
Perhaps you forgot to put a return statement at the end of your method?"
);
}
// Add hidden fields which are required for saving the record
// and loading the UI state
if (!$fields->dataFieldByName('ClassName')) {
$fields->push(new HiddenField('ClassName'));
}
$modelClass = $this->getModelClass();
if ($modelClass::has_extension(Hierarchy::class)
&& !$fields->dataFieldByName('ParentID')
) {
$fields->push(new HiddenField('ParentID'));
}