-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathLeftAndMain.php
2125 lines (1892 loc) · 69.2 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 BadMethodCallException;
use InvalidArgumentException;
use LogicException;
use ReflectionClass;
use SilverStripe\CMS\Controllers\CMSMain;
use SilverStripe\Admin\Navigator\SilverStripeNavigator;
use SilverStripe\Control\ContentNegotiator;
use SilverStripe\Control\Controller;
use SilverStripe\Control\Director;
use SilverStripe\Control\HTTPRequest;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Control\HTTPResponse_Exception;
use SilverStripe\Control\Middleware\HTTPCacheControlMiddleware;
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\Deprecation;
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\HTMLEditor\HTMLEditorConfig;
use SilverStripe\Forms\HTMLEditor\TinyMCEConfig;
use SilverStripe\Forms\LiteralField;
use SilverStripe\Forms\PrintableTransformation;
use SilverStripe\Forms\Schema\FormSchema;
use SilverStripe\i18n\i18n;
use SilverStripe\ORM\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\ORM\SS_List;
use SilverStripe\ORM\ValidationException;
use SilverStripe\ORM\ValidationResult;
use SilverStripe\Security\Member;
use SilverStripe\Security\Permission;
use SilverStripe\Security\PermissionProvider;
use SilverStripe\Security\Security;
use SilverStripe\Security\SecurityToken;
use SilverStripe\SiteConfig\SiteConfig;
use SilverStripe\Versioned\Versioned;
use SilverStripe\View\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 Controller implements PermissionProvider
{
/**
* Form schema header identifier
*/
const SCHEMA_HEADER = 'X-Formschema-Request';
/**
* Enable front-end debugging (increases verbosity) in dev mode.
* Will be ignored in live environments.
*
* @var bool
*/
private static $client_debugging = true;
/**
* The current url segment attached to the LeftAndMain instance
*
* @config
* @var string
*/
private static $url_segment = null;
/**
* @config
* @var string Used by {@link AdminRootController} to augment Director route rules for sub-classes of LeftAndMain
*/
private static $url_rule = '/$Action/$ID/$OtherID';
/**
* @config
* @var string
*/
private static $menu_title;
/**
* @config
* @var string
*/
private static $menu_icon;
/**
* @config
* @var int
*/
private static $menu_priority = 0;
/**
* @config
* @var int
*/
private static $url_priority = 50;
/**
* 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.
*
* @config
* @var string
* @deprecated 2.4.0 Will be renamed to model_class
*/
private static $tree_class = null;
/**
* @var array
*/
private static $allowed_actions = [
'index',
'save',
'printable',
'show',
'Modals',
'EditForm',
'AddForm',
'batchactions',
'BatchActionsForm',
'schema',
'methodSchema',
];
private static $url_handlers = [
'GET schema/$FormName/$ItemID/$OtherItemID' => 'schema',
'GET methodSchema/$Method/$FormName/$ItemID' => 'methodSchema',
];
private static $dependencies = [
'FormSchema' => '%$' . FormSchema::class,
'VersionProvider' => '%$' . VersionProvider::class,
];
/**
* Current form schema helper
*
* @var FormSchema
*/
protected $schema = null;
/**
* Current pageID for this request
*
* @var null
* @deprecated 2.4.0 Will be renamed to recordID.
*/
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 = [];
/**
* Codes which are required from the current user to view this controller.
* If multiple codes are provided, all of them are required.
* All CMS controllers require "CMS_ACCESS_LeftAndMain" as a baseline check,
* and fall back to "CMS_ACCESS_<class>" if no permissions are defined here.
* See {@link canView()} for more details on permission checks.
*
* @config
* @var array
*/
private static $required_permission_codes;
/**
* 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 configuration passed to the supporting JS for each CMS section includes a 'name' key
* that by default matches the FQCN of the current class. This setting allows you to change
* the key if necessary (for example, if you are overloading CMSMain or another core class
* and want to keep the core JS - which depends on the core class names - functioning, you
* would need to set this to the FQCN of the class you are overloading).
*
* @config
* @var string|null
*/
private static $section_name = null;
/**
* @var PjaxResponseNegotiator
*/
protected $responseNegotiator;
/**
* @var VersionProvider
*/
protected $versionProvider;
/**
* 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(LeftAndMain::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);
}
/**
* Returns configuration required by the client app.
*
* @return array
*
* WARNING: Experimental API
*/
public function getClientConfig()
{
// Allows the section name to be overridden in config
$name = $this->config()->get('section_name');
$url = trim($this->Link() ?? '', '/');
if (!$name) {
$name = static::class;
}
$clientConfig = [
// Trim leading/trailing slash to make it easier to concatenate URL
// and use in routing definitions.
'name' => $name,
'url' => $url,
'reactRoutePath' => preg_replace('/^' . preg_quote(AdminRootController::admin_url(), '/') . '/', '', $url),
'form' => [
'EditorExternalLink' => [
'schemaUrl' => $this->Link('methodSchema/Modals/EditorExternalLink'),
],
'EditorEmailLink' => [
'schemaUrl' => $this->Link('methodSchema/Modals/EditorEmailLink'),
],
],
];
$this->extend('updateClientConfig', $clientConfig);
return $clientConfig;
}
/**
* Get form schema helper
*
* @return FormSchema
*/
public function getFormSchema()
{
return $this->schema;
}
/**
* Set form schema helper for this controller
*
* @param FormSchema $schema
* @return $this
*/
public function setFormSchema(FormSchema $schema)
{
$this->schema = $schema;
return $this;
}
/**
* Gets a JSON schema representing the current edit form.
*/
public function schema(HTTPRequest $request): HTTPResponse
{
$formName = $request->param('FormName');
$itemID = $request->param('ItemID');
if (!$formName) {
$this->jsonError(400, 'Missing request params');
}
$formMethod = "get{$formName}";
if (!$this->hasMethod($formMethod)) {
$this->jsonError(404, 'Form not found');
}
if (!$this->hasAction($formName)) {
$this->jsonError(401, 'Form not accessible');
}
if ($itemID) {
$form = $this->{$formMethod}($itemID);
} else {
$form = $this->{$formMethod}();
}
$schemaID = $request->getURL();
return $this->getSchemaResponse($schemaID, $form);
}
/**
* Creates a successful json response
*/
protected function jsonSuccess(int $statusCode, array $data = []): HTTPResponse
{
if ($statusCode < 200 || $statusCode >= 300) {
throw new InvalidArgumentException("Status code $statusCode must be between 200 and 299");
}
$body = empty($data) ? '' : json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
return $this->getResponse()
->addHeader('Content-Type', 'application/json')
->setStatusCode($statusCode)
->setBody($body);
}
/**
* Return an error HTTPResponse encoded as json
*
* @param int $errorCode
* @param string $errorMessage
* @return HTTPResponse
* @throws HTTPResponse_Exception
*/
public function jsonError($errorCode, $errorMessage = null)
{
// Build error from message
$error = [
'type' => 'error',
'code' => $errorCode,
];
if ($errorMessage) {
$error['value'] = $errorMessage;
}
// Support explicit error handling with status = error, or generic message handling
// with a message of type = error
$result = [
'status' => 'error',
'errors' => [$error]
];
$response = HTTPResponse::create(json_encode($result), $errorCode)
->addHeader('Content-Type', 'application/json');
// Call a handler method such as onBeforeHTTPError404
$this->extend("onBeforeJSONError{$errorCode}", $request, $response);
// Call a handler method such as onBeforeHTTPError, passing 404 as the first arg
$this->extend('onBeforeJSONError', $errorCode, $request, $response);
// Throw a new exception
throw new HTTPResponse_Exception($response);
}
/**
* @deprecated 2.4.0 Will be replaced with SilverStripe\Admin\FormSchemaController::schema()
*/
public function methodSchema(HTTPRequest $request): HTTPResponse
{
Deprecation::noticeWithNoReplacment('2.4.0', 'Will be replaced with SilverStripe\Admin\FormSchemaController::schema()');
$method = $request->param('Method');
$formName = $request->param('FormName');
$itemID = $request->param('ItemID');
if (!$formName || !$method) {
$this->jsonError(400, 'Missing request params');
}
if (!$this->hasMethod($method)) {
$this->jsonError(404, 'Method not found');
}
if (!$this->hasAction($method)) {
$this->jsonError(401, 'Method not accessible');
}
$methodItem = $this->{$method}();
if (!$methodItem->hasMethod($formName)) {
$this->jsonError(404, 'Form not found');
}
if (!$methodItem->hasAction($formName)) {
$this->jsonError(401, 'Form not accessible');
}
$form = $methodItem->{$formName}($itemID);
$schemaID = $request->getURL();
return $this->getSchemaResponse($schemaID, $form);
}
/**
* Check if the current request has a X-Formschema-Request header set.
* Used by conditional logic that responds to validation results
*
* @return bool
*/
protected function getSchemaRequested()
{
$parts = $this->getRequest()->getHeader(static::SCHEMA_HEADER);
return !empty($parts);
}
/**
* Generate schema for the given form based on the X-Formschema-Request header value
*
* @param string $schemaID ID for this schema. Required.
* @param Form $form Required for 'state' or 'schema' response
* @param ValidationResult $errors Required for 'error' response
* @param array $extraData Any extra data to be merged with the schema response
*/
protected function getSchemaResponse($schemaID, $form = null, ValidationResult $errors = null, $extraData = []): HTTPResponse
{
$parts = $this->getRequest()->getHeader(static::SCHEMA_HEADER);
$data = $this
->getFormSchema()
->getMultipartSchema($parts, $schemaID, $form, $errors);
if ($extraData) {
$data = array_merge($data, $extraData);
}
$response = new HTTPResponse(json_encode($data));
$response->addHeader('Content-Type', 'application/json');
return $response;
}
/**
* @param Member $member
* @return bool
*/
public function canView($member = null)
{
if (!$member && $member !== false) {
$member = Security::getCurrentUser();
}
// cms menus only for logged-in members
if (!$member) {
return false;
}
// alternative extended checks
if ($this->hasMethod('alternateAccessCheck')) {
$alternateAllowed = $this->alternateAccessCheck($member);
if ($alternateAllowed === false) {
return false;
}
}
// Check for "CMS admin" permission
if (Permission::checkMember($member, "CMS_ACCESS_LeftAndMain")) {
return true;
}
// Check for LeftAndMain sub-class permissions
$codes = $this->getRequiredPermissions();
if ($codes === false) { // allow explicit FALSE to disable subclass check
return true;
}
foreach ((array)$codes as $code) {
if (!Permission::checkMember($member, $code)) {
return false;
}
}
return true;
}
/**
* Get list of required permissions
*
* @return array|string|bool Code, array of codes, or false if no permission required
*/
public static function getRequiredPermissions()
{
$class = get_called_class();
// If the user is accessing LeftAndMain directly, only generic permissions are required.
if ($class === LeftAndMain::class) {
return 'CMS_ACCESS';
}
$code = Config::inst()->get($class, 'required_permission_codes');
if ($code === false) {
return false;
}
if ($code) {
return $code;
}
return 'CMS_ACCESS_' . $class;
}
/**
* @uses LeftAndMainExtension->init()
* @uses LeftAndMainExtension->accessedCMS()
* @uses CMSMenu
*/
protected function init()
{
parent::init();
HTTPCacheControlMiddleware::singleton()->disableCache();
SSViewer::setRewriteHashLinksDefault(false);
ContentNegotiator::setEnabled(false);
// set language
$member = Security::getCurrentUser();
if (!empty($member->Locale)) {
i18n::set_locale($member->Locale);
}
// Allow customisation of the access check by a extension
// Also all the canView() check to execute Controller::redirect()
if (!$this->canView() && !$this->getResponse()->isFinished()) {
// When access /admin/, we should try a redirect to another part of the admin rather than be locked out
$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;
}
}
if (Security::getCurrentUser()) {
$this->getRequest()->getSession()->clear("BackURL");
}
// if no alternate menu items have matched, return a permission error
$messageSet = [
'default' => _t(
__CLASS__ . '.PERMDEFAULT',
"You must be logged in to access the administration area; please enter your credentials below."
),
'alreadyLoggedIn' => _t(
__CLASS__ . '.PERMALREADY',
"I'm sorry, but you can't access that part of the CMS. If you want to log in as someone else, do"
. " so below."
),
'logInAgain' => _t(
__CLASS__ . '.PERMAGAIN',
"You have been logged out of the CMS. If you would like to log in again, enter a username and"
. " password below."
),
];
$this->suppressAdminErrorContext = true;
Security::permissionFailure($this, $messageSet);
return;
}
// Don't continue if there's already been a redirection request.
if ($this->redirectedTo()) {
return;
}
// Audit logging hook
if (empty($_REQUEST['executeForm']) && !$this->getRequest()->isAjax()) {
$this->extend('accessedCMS');
}
// Set the members html editor config
if (Security::getCurrentUser()) {
HTMLEditorConfig::set_active_identifier(Security::getCurrentUser()->getHtmlEditorConfigForCMS());
}
// Set default values in the config if missing. These things can't be defined in the config
// file because insufficient information exists when that is being processed
$htmlEditorConfig = HTMLEditorConfig::get_active();
$htmlEditorConfig->setOption('language', TinyMCEConfig::get_tinymce_lang());
$langUrl = TinyMCEConfig::get_tinymce_lang_url();
if ($langUrl) {
$htmlEditorConfig->setOption('language_url', $langUrl);
}
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);
}
}
$this->extend('init');
// Load the editor with original user themes before overwriting
// them with admin themes
$themes = HTMLEditorConfig::getThemes();
if (empty($themes)) {
HTMLEditorConfig::setThemes(SSViewer::get_themes());
}
// Assign default cms theme and replace user-specified themes
SSViewer::set_themes(LeftAndMain::config()->uninherited('admin_themes'));
// Set the current reading mode
Versioned::set_stage(Versioned::DRAFT);
// Set default reading mode to suppress ?stage=Stage querystring params in CMS
Versioned::set_default_reading_mode(Versioned::get_reading_mode());
}
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;
}
/**
* Overloaded redirection logic to trigger a fake redirect on ajax requests.
* While this violates HTTP principles, its the only way to work around the
* fact that browsers handle HTTP redirects opaquely, no intervention via JS is possible.
* In isolation, that's not a problem - but combined with history.pushState()
* it means we would request the same redirection URL twice if we want to update the URL as well.
* See LeftAndMain.js for the required jQuery ajaxComplete handlers.
*/
public function redirect(string $url, int $code = 302): HTTPResponse
{
if ($this->getRequest()->isAjax()) {
$response = $this->getResponse();
$response->addHeader('X-ControllerURL', $url);
if ($this->getRequest()->getHeader('X-Pjax') && !$response->getHeader('X-Pjax')) {
$response->addHeader('X-Pjax', $this->getRequest()->getHeader('X-Pjax'));
}
$newResponse = new LeftAndMain_HTTPResponse(
$response->getBody(),
$response->getStatusCode(),
$response->getStatusDescription()
);
foreach ($response->getHeaders() as $k => $v) {
$newResponse->addHeader($k, $v);
}
$newResponse->setIsFinished(true);
$this->setResponse($newResponse);
// Actual response will be re-requested by client
return $newResponse;
} else {
return parent::redirect($url, $code);
}
}
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;
}
//------------------------------------------------------------------------------------------//
// Main controllers
/**
* You should implement a Link() function in your subclass of LeftAndMain,
* to point to the URL of that particular controller.
*
* @param string $action
* @return string
*/
public function Link($action = null)
{
// LeftAndMain methods have a top-level uri access
if (static::class === LeftAndMain::class) {
$segment = '';
} else {
// Get url_segment
$segment = $this->config()->get('url_segment');
if (!$segment) {
throw new BadMethodCallException(
sprintf('LeftAndMain subclasses (%s) must have url_segment', static::class)
);
}
}
$link = Controller::join_links(
AdminRootController::admin_url(),
$segment,
"$action"
);
$this->extend('updateLink', $link);
return $link;
}
/**
* 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