BackendController.php 35.3 KB
Newer Older
1
2
3
<?php
namespace TYPO3\CMS\Backend\Controller;

4
/*
5
 * This file is part of the TYPO3 CMS project.
6
 *
7
8
9
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
10
 *
11
12
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
13
 *
14
15
 * The TYPO3 project - inspiring people to share!
 */
16

17
use Psr\Http\Message\ResponseInterface;
18
use Psr\Http\Message\ServerRequestInterface;
19
20
21
use TYPO3\CMS\Backend\Domain\Repository\Module\BackendModuleRepository;
use TYPO3\CMS\Backend\Module\ModuleLoader;
use TYPO3\CMS\Backend\Toolbar\ToolbarItemInterface;
22
use TYPO3\CMS\Backend\Utility\BackendUtility;
23
use TYPO3\CMS\Core\Imaging\IconFactory;
24
25
26
use TYPO3\CMS\Core\Page\PageRenderer;
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
27
use TYPO3\CMS\Core\Utility\MathUtility;
28
use TYPO3\CMS\Core\Utility\PathUtility;
29
use TYPO3\CMS\Fluid\View\StandaloneView;
30
use TYPO3\CMS\Rsaauth\RsaEncryptionEncoder;
Nicole Cordes's avatar
Nicole Cordes committed
31

32
/**
Benni Mack's avatar
Benni Mack committed
33
 * Class for rendering the TYPO3 backend
34
 */
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class BackendController
{
    /**
     * @var string
     */
    protected $content = '';

    /**
     * @var string
     */
    protected $css = '';

    /**
     * @var array
     */
50
    protected $cssFiles = [];
51
52
53
54
55
56
57
58
59

    /**
     * @var string
     */
    protected $js = '';

    /**
     * @var array
     */
60
    protected $jsFiles = [];
61
62
63
64

    /**
     * @var array
     */
65
    protected $toolbarItems = [];
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

    /**
     * @var bool
     */
    protected $debug;

    /**
     * @var string
     */
    protected $templatePath = 'EXT:backend/Resources/Private/Templates/';

    /**
     * @var \TYPO3\CMS\Backend\Domain\Repository\Module\BackendModuleRepository
     */
    protected $backendModuleRepository;

    /**
     * @var \TYPO3\CMS\Backend\Module\ModuleLoader Object for loading backend modules
     */
    protected $moduleLoader;

    /**
     * @var PageRenderer
     */
    protected $pageRenderer;

92
93
94
95
96
    /**
     * @var IconFactory
     */
    protected $iconFactory;

97
98
99
100
101
102
103
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->getLanguageService()->includeLLFile('EXT:lang/locallang_misc.xlf');
        $this->backendModuleRepository = GeneralUtility::makeInstance(BackendModuleRepository::class);
104
        $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
105
106
107
108
109
110
111
112
113
114
115
116

        // Set debug flag for BE development only
        $this->debug = (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['debug'] === 1;
        // Initializes the backend modules structure for use later.
        $this->moduleLoader = GeneralUtility::makeInstance(ModuleLoader::class);
        $this->moduleLoader->load($GLOBALS['TBE_MODULES']);
        $this->pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
        $this->pageRenderer->loadExtJS();
        // included for the module menu JavaScript, please note that this is subject to change
        $this->pageRenderer->loadJquery();
        $this->pageRenderer->addExtDirectCode();
        // Add default BE javascript
117
        $this->jsFiles = [
118
            'locallang' => $this->getLocalLangFileName(),
119
120
121
122
            'md5' => 'EXT:backend/Resources/Public/JavaScript/md5.js',
            'evalfield' => 'EXT:backend/Resources/Public/JavaScript/jsfunc.evalfield.js',
            'backend' => 'EXT:backend/Resources/Public/JavaScript/backend.js',
            'iframepanel' => 'EXT:backend/Resources/Public/JavaScript/iframepanel.js',
123
        ];
124
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/LoginRefresh', 'function(LoginRefresh) {
125
			LoginRefresh.setIntervalTime(' . MathUtility::forceIntegerInRange((int)$GLOBALS['TYPO3_CONF_VARS']['BE']['sessionTimeout'] - 60, 60) . ');
126
127
			LoginRefresh.setLoginFramesetUrl(' . GeneralUtility::quoteJSvalue(BackendUtility::getModuleUrl('login_frameset')) . ');
			LoginRefresh.setLogoutUrl(' . GeneralUtility::quoteJSvalue(BackendUtility::getModuleUrl('logout')) . ');
128
			LoginRefresh.initialize();
129
		}');
130

131
132
133
        // load module menu
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/ModuleMenu');

134
135
136
        // load Toolbar class
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/Toolbar');

137
138
        // load Utility class
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/Utility');
139

140
141
        // load Notification functionality
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/Notification');
142

143
144
        // load Modals
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/Modal');
145

146
147
        // load the storage API and fill the UC into the PersistentStorage, so no additional AJAX call is needed
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/Storage', 'function(Storage) {
148
			Storage.Persistent.load(' . json_encode($this->getBackendUser()->uc) . ');
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
        // load debug console
        $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/DebugConsole');

        // Load RSA encryption
        $rsaEncryptionEncoder = GeneralUtility::makeInstance(RsaEncryptionEncoder::class);
        $rsaEncryptionEncoder->enableRsaEncryption(true);

        $this->pageRenderer->addInlineSetting('ShowItem', 'moduleUrl', BackendUtility::getModuleUrl('show_item'));

        $this->css = '';

        $this->initializeToolbarItems();
        $this->executeHook('constructPostProcess');
        $this->includeLegacyBackendItems();
    }

    /**
     * Add hooks from the additional backend items to load certain things for the main backend.
     * This was previously called from the global scope from backend.php.
     */
    protected function includeLegacyBackendItems()
    {
        $TYPO3backend = $this;
        // Include extensions which may add css, javascript or toolbar items
        if (is_array($GLOBALS['TYPO3_CONF_VARS']['typo3/backend.php']['additionalBackendItems'])) {
            foreach ($GLOBALS['TYPO3_CONF_VARS']['typo3/backend.php']['additionalBackendItems'] as $additionalBackendItem) {
                include_once $additionalBackendItem;
            }
        }

        // Process ExtJS module js and css
        if (is_array($GLOBALS['TBE_MODULES']['_configuration'])) {
            foreach ($GLOBALS['TBE_MODULES']['_configuration'] as $moduleConfig) {
                if (is_array($moduleConfig['cssFiles'])) {
                    foreach ($moduleConfig['cssFiles'] as $cssFileName => $cssFile) {
186
187
188
                        $cssFile = GeneralUtility::getFileAbsFileName($cssFile);
                        $cssFile = PathUtility::getAbsoluteWebPath($cssFile);
                        $TYPO3backend->addCssFile($cssFileName, $cssFile);
189
190
191
192
                    }
                }
                if (is_array($moduleConfig['jsFiles'])) {
                    foreach ($moduleConfig['jsFiles'] as $jsFile) {
193
194
195
                        $jsFile = GeneralUtility::getFileAbsFileName($jsFile);
                        $jsFile = PathUtility::getAbsoluteWebPath($jsFile);
                        $TYPO3backend->addJavascriptFile($jsFile);
196
197
198
199
200
201
202
203
204
205
206
207
208
209
                    }
                }
            }
        }
    }

    /**
     * Initialize toolbar item objects
     *
     * @throws \RuntimeException
     * @return void
     */
    protected function initializeToolbarItems()
    {
210
        $toolbarItemInstances = [];
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
        $classNameRegistry = $GLOBALS['TYPO3_CONF_VARS']['BE']['toolbarItems'];
        foreach ($classNameRegistry as $className) {
            $toolbarItemInstance = GeneralUtility::makeInstance($className);
            if (!$toolbarItemInstance instanceof ToolbarItemInterface) {
                throw new \RuntimeException(
                    'class ' . $className . ' is registered as toolbar item but does not implement'
                        . ToolbarItemInterface::class,
                    1415958218
                );
            }
            $index = (int)$toolbarItemInstance->getIndex();
            if ($index < 0 || $index > 100) {
                throw new \RuntimeException(
                    'getIndex() must return an integer between 0 and 100',
                    1415968498
                );
            }
            // Find next free position in array
            while (array_key_exists($index, $toolbarItemInstances)) {
                $index++;
            }
            $toolbarItemInstances[$index] = $toolbarItemInstance;
        }
        ksort($toolbarItemInstances);
        $this->toolbarItems = $toolbarItemInstances;
    }

    /**
     * Injects the request object for the current request or subrequest
     * As this controller goes only through the render() method, it is rather simple for now
     *
     * @param ServerRequestInterface $request the current request
     * @param ResponseInterface $response
     * @return ResponseInterface the response with the content
     */
    public function mainAction(ServerRequestInterface $request, ResponseInterface $response)
    {
        $this->render();
        $response->getBody()->write($this->content);
        return $response;
    }

    /**
     * Main function generating the BE scaffolding
     *
     * @return void
     */
    public function render()
    {
        $this->executeHook('renderPreProcess');

        // Prepare the scaffolding, at this point extension may still add javascript and css
        $view = $this->getFluidTemplateObject($this->templatePath . 'Backend/Main.html');

265
        // Extension Configuration to find the TYPO3 logo in the left corner
266
        $extConf = unserialize($GLOBALS['TYPO3_CONF_VARS']['EXT']['extConf']['backend'], ['allowed_classes' => false]);
267
268
269
270
271
272
273
274
275
        $logoPath = '';
        if (!empty($extConf['backendLogo'])) {
            $customBackendLogo = GeneralUtility::getFileAbsFileName($extConf['backendLogo']);
            if (!empty($customBackendLogo)) {
                $logoPath = $customBackendLogo;
            }
        }
        // if no custom logo was set or the path is invalid, use the original one
        if (empty($logoPath)) {
276
277
278
279
280
281
282
283
284
285
286
            $logoPath = GeneralUtility::getFileAbsFileName('EXT:backend/Resources/Public/Images/typo3_logo_orange.svg');
            $logoWidth = 22;
            $logoHeight = 22;
        } else {
            list($logoWidth, $logoHeight) = @getimagesize($logoPath);

            // High-resolution?
            if (strpos($logoPath, '@2x.') !== false) {
                $logoWidth /= 2;
                $logoHeight /= 2;
            }
287
288
        }

289
        $view->assign('logoUrl', PathUtility::getAbsoluteWebPath($logoPath));
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
        $view->assign('logoWidth', $logoWidth);
        $view->assign('logoHeight', $logoHeight);
        $view->assign('applicationVersion', TYPO3_version);
        $view->assign('siteName', $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename']);
        $view->assign('moduleMenu', $this->generateModuleMenu());
        $view->assign('toolbar', $this->renderToolbar());

        /******************************************************
         * Now put the complete backend document together
         ******************************************************/
        foreach ($this->cssFiles as $cssFileName => $cssFile) {
            $this->pageRenderer->addCssFile($cssFile);
            // Load additional css files to overwrite existing core styles
            if (!empty($GLOBALS['TBE_STYLES']['stylesheets'][$cssFileName])) {
                $this->pageRenderer->addCssFile($GLOBALS['TBE_STYLES']['stylesheets'][$cssFileName]);
            }
        }
        if (!empty($this->css)) {
            $this->pageRenderer->addCssInlineBlock('BackendInlineCSS', $this->css);
        }
        foreach ($this->jsFiles as $jsFile) {
            $this->pageRenderer->addJsFile($jsFile);
        }
        $this->generateJavascript();
        $this->pageRenderer->addJsInlineCode('BackendInlineJavascript', $this->js, false);
        $this->loadResourcesForRegisteredNavigationComponents();

        // Add state provider
        $this->getDocumentTemplate()->setExtDirectStateProvider();
        $states = $this->getBackendUser()->uc['BackendComponents']['States'];
        // Save states in BE_USER->uc
        $extOnReadyCode = '
322
323
324
325
326
			Ext.state.Manager.setProvider(new TYPO3.state.ExtDirectProvider({
				key: "BackendComponents.States",
				autoRead: false
			}));
		';
Benni Mack's avatar
Benni Mack committed
327

328
329
330
        if ($states) {
            $extOnReadyCode .= 'Ext.state.Manager.getProvider().initState(' . json_encode($states) . ');';
        }
Benni Mack's avatar
Benni Mack committed
331

332
        $this->pageRenderer->addExtOnReadyCode($extOnReadyCode);
333

334
335
336
337
        // Set document title:
        $title = $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] ? $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . ' [TYPO3 CMS ' . TYPO3_version . ']' : 'TYPO3 CMS ' . TYPO3_version;
        // Renders the module page
        $this->content = $this->getDocumentTemplate()->render($title, $view->render());
338
        $hookConfiguration = ['content' => &$this->content];
339
340
341
342
343
344
345
346
347
348
349
350
351
        $this->executeHook('renderPostProcess', $hookConfiguration);
    }

    /**
     * Loads the css and javascript files of all registered navigation widgets
     *
     * @return void
     */
    protected function loadResourcesForRegisteredNavigationComponents()
    {
        if (!is_array($GLOBALS['TBE_MODULES']['_navigationComponents'])) {
            return;
        }
352
        $loadedComponents = [];
353
354
355
356
357
358
359
360
        foreach ($GLOBALS['TBE_MODULES']['_navigationComponents'] as $module => $info) {
            if (in_array($info['componentId'], $loadedComponents)) {
                continue;
            }
            $loadedComponents[] = $info['componentId'];
            $component = strtolower(substr($info['componentId'], strrpos($info['componentId'], '-') + 1));
            $componentDirectory = 'components/' . $component . '/';
            if ($info['isCoreComponent']) {
361
362
                $componentDirectory = 'Resources/Public/JavaScript/extjs/' . $componentDirectory;
                $info['extKey'] = 'backend';
363
            }
364
            $absoluteComponentPath = ExtensionManagementUtility::extPath($info['extKey']) . $componentDirectory;
365
            $relativeComponentPath = PathUtility::getRelativePath(PATH_site . TYPO3_mainDir, $absoluteComponentPath);
366
367
368
            $cssFiles = GeneralUtility::getFilesInDir($absoluteComponentPath . 'css/', 'css');
            if (file_exists($absoluteComponentPath . 'css/loadorder.txt')) {
                // Don't allow inclusion outside directory
369
                $loadOrder = str_replace('../', '', file_get_contents($absoluteComponentPath . 'css/loadorder.txt'));
370
371
372
373
374
375
376
377
378
                $cssFilesOrdered = GeneralUtility::trimExplode(LF, $loadOrder, true);
                $cssFiles = array_merge($cssFilesOrdered, $cssFiles);
            }
            foreach ($cssFiles as $cssFile) {
                $this->pageRenderer->addCssFile($relativeComponentPath . 'css/' . $cssFile);
            }
            $jsFiles = GeneralUtility::getFilesInDir($absoluteComponentPath . 'javascript/', 'js');
            if (file_exists($absoluteComponentPath . 'javascript/loadorder.txt')) {
                // Don't allow inclusion outside directory
379
                $loadOrder = str_replace('../', '', file_get_contents($absoluteComponentPath . 'javascript/loadorder.txt'));
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
                $jsFilesOrdered = GeneralUtility::trimExplode(LF, $loadOrder, true);
                $jsFiles = array_merge($jsFilesOrdered, $jsFiles);
            }
            foreach ($jsFiles as $jsFile) {
                $this->pageRenderer->addJsFile($relativeComponentPath . 'javascript/' . $jsFile);
            }
            $this->pageRenderer->addInlineSetting('RecordHistory', 'moduleUrl', BackendUtility::getModuleUrl('record_history'));
            $this->pageRenderer->addInlineSetting('NewRecord', 'moduleUrl', BackendUtility::getModuleUrl('db_new'));
            $this->pageRenderer->addInlineSetting('FormEngine', 'moduleUrl', BackendUtility::getModuleUrl('record_edit'));
        }
    }

    /**
     * Renders the items in the top toolbar
     *
     * @return string top toolbar elements as HTML
     */
    protected function renderToolbar()
    {
399
        $toolbar = [];
400
401
402
403
404
405
        foreach ($this->toolbarItems as $toolbarItem) {
            /** @var \TYPO3\CMS\Backend\Toolbar\ToolbarItemInterface $toolbarItem */
            if ($toolbarItem->checkAccess()) {
                $hasDropDown = (bool)$toolbarItem->hasDropDown();
                $additionalAttributes = (array)$toolbarItem->getAdditionalAttributes();

406
                $liAttributes = [];
407
408

                // Merge class: Add dropdown class if hasDropDown, add classes from additonal attributes
409
                $classes = [];
410
411
                $classes[] = 'toolbar-item';
                $classes[] = 't3js-toolbar-item';
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
                if (isset($additionalAttributes['class'])) {
                    $classes[] = $additionalAttributes['class'];
                    unset($additionalAttributes['class']);
                }
                $liAttributes[] = 'class="' . implode(' ', $classes) . '"';

                // Add further attributes
                foreach ($additionalAttributes as $name => $value) {
                    $liAttributes[] = $name . '="' . $value . '"';
                }

                // Create a unique id from class name
                $className = get_class($toolbarItem);
                $className = GeneralUtility::underscoredToLowerCamelCase($className);
                $className = GeneralUtility::camelCaseToLowerCaseUnderscored($className);
427
                $className = str_replace(['_', '\\'], '-', $className);
428
429
430
431
432
                $liAttributes[] = 'id="' . $className . '"';

                $toolbar[] = '<li ' . implode(' ', $liAttributes) . '>';

                if ($hasDropDown) {
433
                    $toolbar[] = '<a href="#" class="toolbar-item-link dropdown-toggle" data-toggle="dropdown">';
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
                    $toolbar[] = $toolbarItem->getItem();
                    $toolbar[] = '</a>';
                    $toolbar[] = '<div class="dropdown-menu" role="menu">';
                    $toolbar[] = $toolbarItem->getDropDown();
                    $toolbar[] = '</div>';
                } else {
                    $toolbar[] = $toolbarItem->getItem();
                }
                $toolbar[] = '</li>';
            }
        }
        return implode(LF, $toolbar);
    }

    /**
     * Returns the file name to the LLL JavaScript, containing the localized labels,
     * which can be used in JavaScript code.
     *
     * @return string File name of the JS file, relative to TYPO3_mainDir
     * @throws \RuntimeException
     */
    protected function getLocalLangFileName()
    {
        $code = $this->generateLocalLang();
458
        $filePath = 'typo3temp/assets/js/backend-' . sha1($code) . '.js';
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
        if (!file_exists(PATH_site . $filePath)) {
            // writeFileToTypo3tempDir() returns NULL on success (please double-read!)
            $error = GeneralUtility::writeFileToTypo3tempDir(PATH_site . $filePath, $code);
            if ($error !== null) {
                throw new \RuntimeException('Locallang JS file could not be written to ' . $filePath . '. Reason: ' . $error, 1295193026);
            }
        }
        return '../' . $filePath;
    }

    /**
     * Reads labels required in JavaScript code from the localization system and returns them as JSON
     * array in TYPO3.LLL.
     *
     * @return string JavaScript code containing the LLL labels in TYPO3.LLL
     */
    protected function generateLocalLang()
    {
        $lang = $this->getLanguageService();
478
        $coreLabels = [
479
480
481
            'waitTitle' => $lang->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_logging_in'),
            'refresh_login_failed' => $lang->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_failed'),
            'refresh_login_failed_message' => $lang->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_failed_message'),
482
            'refresh_login_title' => $lang->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_title'),
483
484
485
486
487
            'login_expired' => $lang->sL('LLL:EXT:lang/locallang_core.xlf:mess.login_expired'),
            'refresh_login_username' => $lang->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_username'),
            'refresh_login_password' => $lang->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_password'),
            'refresh_login_emptyPassword' => $lang->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_emptyPassword'),
            'refresh_login_button' => $lang->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_button'),
488
            'refresh_exit_button' => $lang->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_exit_button'),
489
490
491
492
493
494
495
            'please_wait' => $lang->sL('LLL:EXT:lang/locallang_core.xlf:mess.please_wait'),
            'be_locked' => $lang->sL('LLL:EXT:lang/locallang_core.xlf:mess.be_locked'),
            'login_about_to_expire' => $lang->sL('LLL:EXT:lang/locallang_core.xlf:mess.login_about_to_expire'),
            'login_about_to_expire_title' => $lang->sL('LLL:EXT:lang/locallang_core.xlf:mess.login_about_to_expire_title'),
            'refresh_login_logout_button' => $lang->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_logout_button'),
            'refresh_login_refresh_button' => $lang->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_refresh_button'),
            'csh_tooltip_loading' => $lang->sL('LLL:EXT:lang/locallang_core.xlf:csh_tooltip_loading')
496
497
498
        ];
        $labels = [
            'fileUpload' => [
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
                'windowTitle',
                'buttonSelectFiles',
                'buttonCancelAll',
                'infoComponentMaxFileSize',
                'infoComponentFileUploadLimit',
                'infoComponentFileTypeLimit',
                'infoComponentOverrideFiles',
                'processRunning',
                'uploadWait',
                'uploadStarting',
                'uploadProgress',
                'uploadSuccess',
                'errorQueueLimitExceeded',
                'errorQueueFileSizeLimit',
                'errorQueueZeroByteFile',
                'errorQueueInvalidFiletype',
                'errorUploadHttp',
                'errorUploadMissingUrl',
                'errorUploadIO',
                'errorUploadSecurityError',
                'errorUploadLimit',
                'errorUploadFailed',
                'errorUploadFileIDNotFound',
                'errorUploadFileValidation',
                'errorUploadFileCancelled',
                'errorUploadStopped',
                'allErrorMessageTitle',
                'allErrorMessageText',
                'allError401',
                'allError2038'
529
530
            ],
            'liveSearch' => [
531
532
533
534
535
536
537
538
539
                'title',
                'helpTitle',
                'emptyText',
                'loadingText',
                'listEmptyText',
                'showAllResults',
                'helpDescription',
                'helpDescriptionPages',
                'helpDescriptionContent'
540
541
            ],
            'viewPort' => [
542
543
544
545
                'tooltipModuleMenuSplit',
                'tooltipNavigationContainerSplitDrag',
                'tooltipNavigationContainerSplitClick',
                'tooltipDebugPanelSplitDrag'
546
547
548
            ]
        ];
        $generatedLabels = [];
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
        $generatedLabels['core'] = $coreLabels;
        // First loop over all categories (fileUpload, liveSearch, ..)
        foreach ($labels as $categoryName => $categoryLabels) {
            // Then loop over every single label
            foreach ($categoryLabels as $label) {
                // LLL identifier must be called $categoryName_$label, e.g. liveSearch_loadingText
                $generatedLabels[$categoryName][$label] = $this->getLanguageService()->getLL($categoryName . '_' . $label);
            }
        }
        return 'TYPO3.LLL = ' . json_encode($generatedLabels) . ';';
    }

    /**
     * Generates the JavaScript code for the backend.
     *
     * @return void
     */
    protected function generateJavascript()
    {
        $beUser = $this->getBackendUser();
        // Needed for FormEngine manipulation (date picker)
570
        $dateFormat = ($GLOBALS['TYPO3_CONF_VARS']['SYS']['USdateFormat'] ? ['MM-DD-YYYY', 'HH:mm MM-DD-YYYY'] : ['DD-MM-YYYY', 'HH:mm DD-MM-YYYY']);
571
572
573
574
575
576
577
578
        $this->pageRenderer->addInlineSetting('DateTimePicker', 'DateFormat', $dateFormat);

        // If another page module was specified, replace the default Page module with the new one
        $newPageModule = trim($beUser->getTSConfigVal('options.overridePageModule'));
        $pageModule = BackendUtility::isModuleSetInTBE_MODULES($newPageModule) ? $newPageModule : 'web_layout';
        if (!$beUser->check('modules', $pageModule)) {
            $pageModule = '';
        }
579
        $t3Configuration = [
580
581
582
583
584
585
            'siteUrl' => GeneralUtility::getIndpEnv('TYPO3_SITE_URL'),
            'username' => htmlspecialchars($beUser->user['username']),
            'uniqueID' => GeneralUtility::shortMD5(uniqid('', true)),
            'pageModule' => $pageModule,
            'inWorkspace' => $beUser->workspace !== 0,
            'showRefreshLoginPopup' => isset($GLOBALS['TYPO3_CONF_VARS']['BE']['showRefreshLoginPopup']) ? (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['showRefreshLoginPopup'] : false,
586
            'ContextHelpWindows' => [
587
588
                'width' => 600,
                'height' => 400
589
590
            ]
        ];
591
        $this->js .= '
592
	TYPO3.configuration = ' . json_encode($t3Configuration) . ';
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607

	/**
	 * TypoSetup object.
	 */
	function typoSetup() {	//
		this.username = TYPO3.configuration.username;
		this.uniqueID = TYPO3.configuration.uniqueID;
	}
	var TS = new typoSetup();
		//backwards compatibility
	/**
	 * Frameset Module object
	 *
	 * Used in main modules with a frameset for submodules to keep the ID between modules
	 * Typically that is set by something like this in a Web>* sub module:
608
	 *		if (top.fsMod) top.fsMod.recentIds["web"] = "\'.(int)$this->id.\'";
609
610
611
612
613
614
615
616
617
618
619
620
	 * 		if (top.fsMod) top.fsMod.recentIds["file"] = "...(file reference/string)...";
	 */
	function fsModules() {	//
		this.recentIds=new Array();					// used by frameset modules to track the most recent used id for list frame.
		this.navFrameHighlightedID=new Array();		// used by navigation frames to track which row id was highlighted last time
		this.currentBank="0";
	}
	var fsMod = new fsModules();

	top.goToModule = function(modName, cMR_flag, addGetVars) {
		TYPO3.ModuleMenu.App.showModule(modName, addGetVars);
	}
621
	' . $this->setStartupModule();
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
        // Check editing of page:
        $this->handlePageEditing();
    }

    /**
     * Checking if the "&edit" variable was sent so we can open it for editing the page.
     *
     * @return void
     */
    protected function handlePageEditing()
    {
        $beUser = $this->getBackendUser();
        // EDIT page:
        $editId = preg_replace('/[^[:alnum:]_]/', '', GeneralUtility::_GET('edit'));
        $editRecord = '';
        if ($editId) {
            // Looking up the page to edit, checking permissions:
            $where = ' AND (' . $beUser->getPagePermsClause(2) . ' OR ' . $beUser->getPagePermsClause(16) . ')';
            if (MathUtility::canBeInterpretedAsInteger($editId)) {
                $editRecord = BackendUtility::getRecordWSOL('pages', $editId, '*', $where);
            } else {
                $records = BackendUtility::getRecordsByField('pages', 'alias', $editId, $where);
                if (is_array($records)) {
                    $editRecord = reset($records);
                    BackendUtility::workspaceOL('pages', $editRecord);
                }
            }
            // If the page was accessible, then let the user edit it.
            if (is_array($editRecord) && $beUser->isInWebMount($editRecord['uid'])) {
                // Setting JS code to open editing:
                $this->js .= '
653
		// Load page to edit:
654
	window.setTimeout("top.loadEditId(' . (int)$editRecord['uid'] . ');", 500);
655
			';
656
657
658
659
660
661
662
663
                // Checking page edit parameter:
                if (!$beUser->getTSConfigVal('options.bookmark_onEditId_dontSetPageTree')) {
                    $bookmarkKeepExpanded = $beUser->getTSConfigVal('options.bookmark_onEditId_keepExistingExpanded');
                    // Expanding page tree:
                    BackendUtility::openPageTree((int)$editRecord['pid'], !$bookmarkKeepExpanded);
                }
            } else {
                $this->js .= '
664
665
666
667
668
669
670
671
672
673
674
675
            // Warning about page editing:
            require(["TYPO3/CMS/Backend/Modal", "TYPO3/CMS/Backend/Severity"], function(Modal, Severity) {
                Modal.show("", ' . GeneralUtility::quoteJSvalue(sprintf($this->getLanguageService()->getLL('noEditPage'), $editId)) . ', Severity.notice, [{
                    text: ' . GeneralUtility::quoteJSvalue($this->getLanguageService()->sL('LLL:EXT:lang/locallang_common.xlf:close')) . ',
                    active: true,
                    btnClass: "btn-info",
                    name: "cancel",
                    trigger: function () {
                        Modal.currentModal.trigger("modal-dismiss");
                    }
                }])
            });';
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
            }
        }
    }

    /**
     * Sets the startup module from either GETvars module and modParams or user configuration.
     *
     * @return string the JavaScript code for the startup module
     */
    protected function setStartupModule()
    {
        $startModule = preg_replace('/[^[:alnum:]_]/', '', GeneralUtility::_GET('module'));
        $startModuleParameters = '';
        if (!$startModule) {
            $beUser = $this->getBackendUser();
            // start module on first login, will be removed once used the first time
            if (isset($beUser->uc['startModuleOnFirstLogin'])) {
                $startModule = $beUser->uc['startModuleOnFirstLogin'];
                unset($beUser->uc['startModuleOnFirstLogin']);
                $beUser->writeUC();
            } elseif ($beUser->uc['startModule']) {
                $startModule = $beUser->uc['startModule'];
            }

            // check if the start module has additional parameters, so a redirect to a specific
            // action is possible
            if (strpos($startModule, '->') !== false) {
                list($startModule, $startModuleParameters) = explode('->', $startModule, 2);
            }
        }

        $moduleParameters = GeneralUtility::_GET('modParams');
        // if no GET parameters are set, check if there are parameters given from the UC
        if (!$moduleParameters && $startModuleParameters) {
            $moduleParameters = $startModuleParameters;
        }

        if ($startModule) {
            return '
715
					// start in module:
716
				top.startInModule = [' . GeneralUtility::quoteJSvalue($startModule) . ', ' . GeneralUtility::quoteJSvalue($moduleParameters) . '];
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
        } else {
            return '';
        }
    }

    /**
     * Adds a javascript snippet to the backend
     *
     * @param string $javascript Javascript snippet
     * @return void
     * @throws \InvalidArgumentException
     */
    public function addJavascript($javascript)
    {
        // @todo do we need more checks?
        if (!is_string($javascript)) {
            throw new \InvalidArgumentException('parameter $javascript must be of type string', 1195129553);
        }
        $this->js .= $javascript;
    }

    /**
     * Adds a javscript file to the backend after it has been checked that it exists
     *
     * @param string $javascriptFile Javascript file reference
     * @return bool TRUE if the javascript file was successfully added, FALSE otherwise
     */
    public function addJavascriptFile($javascriptFile)
    {
        $jsFileAdded = false;
        // @todo add more checks if necessary
        if (file_exists(GeneralUtility::resolveBackPath(PATH_typo3 . $javascriptFile))) {
            $this->jsFiles[] = $javascriptFile;
            $jsFileAdded = true;
        }
        return $jsFileAdded;
    }

    /**
     * Adds a css snippet to the backend
     *
     * @param string $css Css snippet
     * @return void
     * @throws \InvalidArgumentException
     */
    public function addCss($css)
    {
        if (!is_string($css)) {
            throw new \InvalidArgumentException('parameter $css must be of type string', 1195129642);
        }
        $this->css .= $css;
    }

    /**
     * Adds a css file to the backend after it has been checked that it exists
     *
     * @param string $cssFileName The css file's name with out the .css ending
     * @param string $cssFile Css file reference
     * @return bool TRUE if the css file was added, FALSE otherwise
     */
    public function addCssFile($cssFileName, $cssFile)
    {
        $cssFileAdded = false;
        if (empty($this->cssFiles[$cssFileName])) {
            $this->cssFiles[$cssFileName] = $cssFile;
            $cssFileAdded = true;
        }
        return $cssFileAdded;
    }

    /**
     * Executes defined hooks functions for the given identifier.
     *
     * These hook identifiers are valid:
     * + constructPostProcess
     * + renderPreProcess
     * + renderPostProcess
     *
     * @param string $identifier Specific hook identifier
     * @param array $hookConfiguration Additional configuration passed to hook functions
     * @return void
     */
800
    protected function executeHook($identifier, array $hookConfiguration = [])
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
    {
        $options = &$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/backend.php'];
        if (isset($options[$identifier]) && is_array($options[$identifier])) {
            foreach ($options[$identifier] as $hookFunction) {
                GeneralUtility::callUserFunction($hookFunction, $hookConfiguration, $this);
            }
        }
    }

    /**
     * loads all modules from the repository
     * and renders it with a template
     *
     * @return string
     */
    protected function generateModuleMenu()
    {
        // get all modules except the user modules for the side menu
819
        $moduleStorage = $this->backendModuleRepository->loadAllowedModules(['user', 'help']);
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

        $view = $this->getFluidTemplateObject($this->templatePath . 'ModuleMenu/Main.html');
        $view->assign('modules', $moduleStorage);
        return $view->render();
    }

    /**
     * Returns the Module menu for the AJAX request
     *
     * @param ServerRequestInterface $request
     * @param ResponseInterface $response
     * @return ResponseInterface
     */
    public function getModuleMenu(ServerRequestInterface $request, ResponseInterface $response)
    {
        $content = $this->generateModuleMenu();

        $response->getBody()->write(json_encode(['menu' => $content]));
        return $response;
    }

    /**
     * returns a new standalone view, shorthand function
     *
     * @param string $templatePathAndFileName optional the path to set the template path and filename
     * @return \TYPO3\CMS\Fluid\View\StandaloneView
     */
    protected function getFluidTemplateObject($templatePathAndFileName = null)
    {
        $view = GeneralUtility::makeInstance(StandaloneView::class);
        if ($templatePathAndFileName) {
            $view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName($templatePathAndFileName));
        }
        return $view;
    }

    /**
     * Returns LanguageService
     *
     * @return \TYPO3\CMS\Lang\LanguageService
     */
    protected function getLanguageService()
    {
        return $GLOBALS['LANG'];
    }

    /**
     * Returns the current BE user.
     *
     * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
     */
    protected function getBackendUser()
    {
        return $GLOBALS['BE_USER'];
    }

    /**
     * Returns an instance of DocumentTemplate
     *
     * @return \TYPO3\CMS\Backend\Template\DocumentTemplate
     */
    protected function getDocumentTemplate()
    {
        return $GLOBALS['TBE_TEMPLATE'];
    }
885
}