[TASK] Cleanup BackendController.php (part 1)
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Controller / BackendController.php
1 <?php
2 namespace TYPO3\CMS\Backend\Controller;
3
4 /**
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Backend\Utility\BackendUtility;
18 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
19 use TYPO3\CMS\Core\Utility\GeneralUtility;
20
21 /**
22 * Class for rendering the TYPO3 backend version 4.2+
23 *
24 * @author Ingo Renner <ingo@typo3.org>
25 */
26 class BackendController {
27
28 /**
29 * @var string
30 */
31 protected $content;
32
33 /**
34 * @var string
35 */
36 protected $css;
37
38 /**
39 * @var array
40 */
41 protected $cssFiles = array();
42
43 /**
44 * @var string
45 */
46 protected $js;
47
48 /**
49 * @var array
50 */
51 protected $jsFiles;
52
53 /**
54 * @var array
55 */
56 protected $toolbarItems = array();
57
58 /**
59 * @var int Intentionally private as nobody should modify defaults
60 */
61 private $menuWidthDefault = 190;
62
63 /**
64 * @var int
65 */
66 protected $menuWidth;
67
68 /**
69 * @var bool
70 */
71 protected $debug;
72
73 /**
74 * @var \TYPO3\CMS\Backend\Domain\Repository\Module\BackendModuleRepository
75 */
76 protected $backendModuleRepository;
77
78 /**
79 * @var \TYPO3\CMS\Backend\Module\ModuleLoader Object for loading backend modules
80 */
81 protected $moduleLoader;
82
83 /**
84 * @var \TYPO3\CMS\Core\Page\PageRenderer
85 */
86 protected $pageRenderer;
87
88 /**
89 * @return \TYPO3\CMS\Core\Page\PageRenderer
90 */
91 public function getPageRenderer() {
92 return $this->pageRenderer;
93 }
94
95 /**
96 * Constructor
97 */
98 public function __construct() {
99 $this->backendModuleRepository = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Domain\Repository\Module\BackendModuleRepository::class);
100
101 // Set debug flag for BE development only
102 $this->debug = (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['debug'] === 1;
103 // Initializes the backend modules structure for use later.
104 $this->moduleLoader = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\Module\ModuleLoader::class);
105 $this->moduleLoader->load($GLOBALS['TBE_MODULES']);
106 $this->pageRenderer = $GLOBALS['TBE_TEMPLATE']->getPageRenderer();
107 $this->pageRenderer->loadExtJS();
108 // included for the module menu JavaScript, please note that this is subject to change
109 $this->pageRenderer->loadJquery();
110 $this->pageRenderer->enableExtJSQuickTips();
111 $this->pageRenderer->addJsInlineCode('consoleOverrideWithDebugPanel', '//already done', FALSE);
112 $this->pageRenderer->addExtDirectCode();
113 // Add default BE javascript
114 $this->js = '';
115 $this->jsFiles = array(
116 'locallang' => $this->getLocalLangFileName(),
117 'modernizr' => 'contrib/modernizr/modernizr.min.js',
118 'md5' => 'sysext/backend/Resources/Public/JavaScript/md5.js',
119 'modulemenu' => 'sysext/backend/Resources/Public/JavaScript/modulemenu.js',
120 'evalfield' => 'sysext/backend/Resources/Public/JavaScript/jsfunc.evalfield.js',
121 'flashmessages' => 'sysext/backend/Resources/Public/JavaScript/flashmessages.js',
122 'tabclosemenu' => 'js/extjs/ux/ext.ux.tabclosemenu.js',
123 'notifications' => 'sysext/backend/Resources/Public/JavaScript/notifications.js',
124 'backend' => 'sysext/backend/Resources/Public/JavaScript/backend.js',
125 'loginrefresh' => 'sysext/backend/Resources/Public/JavaScript/loginrefresh.js',
126 'debugPanel' => 'js/extjs/debugPanel.js',
127 'viewport' => 'js/extjs/viewport.js',
128 'iframepanel' => 'sysext/backend/Resources/Public/JavaScript/iframepanel.js',
129 'backendcontentiframe' => 'js/extjs/backendcontentiframe.js',
130 'viewportConfiguration' => 'js/extjs/viewportConfiguration.js',
131 'util' => 'sysext/backend/Resources/Public/JavaScript/util.js'
132 );
133 if ($this->debug) {
134 unset($this->jsFiles['loginrefresh']);
135 }
136 // Add default BE css
137 $this->pageRenderer->addCssLibrary('contrib/normalize/normalize.css', 'stylesheet', 'all', '', TRUE, TRUE);
138
139 $this->css = '';
140 $this->initializeToolbarItems();
141 $this->menuWidth = isset($GLOBALS['TBE_STYLES']['dims']['leftMenuFrameW']) ? (int)$GLOBALS['TBE_STYLES']['dims']['leftMenuFrameW'] : $this->menuWidthDefault;
142 $this->executeHook('constructPostProcess');
143 }
144
145 /**
146 * Initialize toolbar item objects
147 *
148 * @throws \RuntimeException
149 * @return void
150 */
151 protected function initializeToolbarItems() {
152 $toolbarItemInstances = array();
153 $classNameRegistry = $GLOBALS['TYPO3_CONF_VARS']['BE']['toolbarItems'];
154 foreach ($classNameRegistry as $className) {
155 $toolbarItemInstance = GeneralUtility::makeInstance($className);
156 if (!$toolbarItemInstance instanceof \TYPO3\CMS\Backend\Toolbar\ToolbarItemInterface) {
157 throw new \RuntimeException(
158 'class ' . $className . ' is registered as toolbar item but does not implement'
159 . '\TYPO3\CMS\Backend\Toolbar\ToolbarItemInterface',
160 1415958218
161 );
162 }
163 $index = (int)$toolbarItemInstance->getIndex();
164 if ($index < 0 || $index > 100) {
165 throw new \RuntimeException(
166 'getIndex() must return an integer between 0 and 100',
167 1415968498
168 );
169 }
170 // Find next free position in array
171 while(array_key_exists($index, $toolbarItemInstances)) {
172 $index++;
173 }
174 $toolbarItemInstances[$index] = $toolbarItemInstance;
175 }
176 ksort($toolbarItemInstances);
177 $this->toolbarItems = $toolbarItemInstances;
178 }
179
180 /**
181 * Main function generating the BE scaffolding
182 *
183 * @return void
184 */
185 public function render() {
186 $this->executeHook('renderPreProcess');
187
188 // Prepare the scaffolding, at this point extension may still add javascript and css
189 $view = $this->getFluidTemplateObject('EXT:backend/Resources/Private/Templates/Backend/Main.html');
190 // @todo: kick logo view class and move all logic to Fluid
191 $view->assign('logo', GeneralUtility::makeInstance(\TYPO3\CMS\Backend\View\LogoView::class)->render());
192 $view->assign('moduleMenu', $this->generateModuleMenu());
193 $view->assign('toolbar', $this->renderToolbar());
194
195 /******************************************************
196 * Now put the complete backend document together
197 ******************************************************/
198 foreach ($this->cssFiles as $cssFileName => $cssFile) {
199 $this->pageRenderer->addCssFile($cssFile);
200 // Load additional css files to overwrite existing core styles
201 if (!empty($GLOBALS['TBE_STYLES']['stylesheets'][$cssFileName])) {
202 $this->pageRenderer->addCssFile($GLOBALS['TBE_STYLES']['stylesheets'][$cssFileName]);
203 }
204 }
205 if (!empty($this->css)) {
206 $this->pageRenderer->addCssInlineBlock('BackendInlineCSS', $this->css);
207 }
208 foreach ($this->jsFiles as $jsFile) {
209 $this->pageRenderer->addJsFile($jsFile);
210 }
211 $this->generateJavascript();
212 $this->pageRenderer->addJsInlineCode('BackendInlineJavascript', $this->js, FALSE);
213 $this->loadResourcesForRegisteredNavigationComponents();
214
215 // Add state provider
216 $GLOBALS['TBE_TEMPLATE']->setExtDirectStateProvider();
217 $states = $GLOBALS['BE_USER']->uc['BackendComponents']['States'];
218 // Save states in BE_USER->uc
219 $extOnReadyCode = '
220 Ext.state.Manager.setProvider(new TYPO3.state.ExtDirectProvider({
221 key: "BackendComponents.States",
222 autoRead: false
223 }));
224 ';
225
226 if ($states) {
227 $extOnReadyCode .= 'Ext.state.Manager.getProvider().initState(' . json_encode($states) . ');';
228 }
229
230 $extOnReadyCode .= '
231 TYPO3.Backend = new TYPO3.Viewport(TYPO3.Viewport.configuration);
232 if (typeof console === "undefined") {
233 console = TYPO3.Backend.DebugConsole;
234 }
235 TYPO3.ContextHelpWindow.init(' . GeneralUtility::quoteJSvalue(BackendUtility::getModuleUrl('help_cshmanual')) . ');';
236 $this->pageRenderer->addExtOnReadyCode($extOnReadyCode);
237 // Set document title:
238 $title = $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] ? $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'] . ' [TYPO3 CMS ' . TYPO3_version . ']' : 'TYPO3 CMS ' . TYPO3_version;
239 // Renders the module page
240 $this->content = $GLOBALS['TBE_TEMPLATE']->render($title, $view->render());
241 $hookConfiguration = array('content' => &$this->content);
242 $this->executeHook('renderPostProcess', $hookConfiguration);
243 echo $this->content;
244 }
245
246 /**
247 * Loads the css and javascript files of all registered navigation widgets
248 *
249 * @return void
250 */
251 protected function loadResourcesForRegisteredNavigationComponents() {
252 if (!is_array($GLOBALS['TBE_MODULES']['_navigationComponents'])) {
253 return;
254 }
255 $loadedComponents = array();
256 foreach ($GLOBALS['TBE_MODULES']['_navigationComponents'] as $module => $info) {
257 if (in_array($info['componentId'], $loadedComponents)) {
258 continue;
259 }
260 $loadedComponents[] = $info['componentId'];
261 $component = strtolower(substr($info['componentId'], strrpos($info['componentId'], '-') + 1));
262 $componentDirectory = 'components/' . $component . '/';
263 if ($info['isCoreComponent']) {
264 $absoluteComponentPath = PATH_site . 'typo3/js/extjs/' . $componentDirectory;
265 $relativeComponentPath = '../' . str_replace(PATH_site, '', $absoluteComponentPath);
266 } else {
267 $absoluteComponentPath = ExtensionManagementUtility::extPath($info['extKey']) . $componentDirectory;
268 $relativeComponentPath = ExtensionManagementUtility::extRelPath($info['extKey']) . $componentDirectory;
269 }
270 $cssFiles = GeneralUtility::getFilesInDir($absoluteComponentPath . 'css/', 'css');
271 if (file_exists($absoluteComponentPath . 'css/loadorder.txt')) {
272 // Don't allow inclusion outside directory
273 $loadOrder = str_replace('../', '', GeneralUtility::getUrl($absoluteComponentPath . 'css/loadorder.txt'));
274 $cssFilesOrdered = GeneralUtility::trimExplode(LF, $loadOrder, TRUE);
275 $cssFiles = array_merge($cssFilesOrdered, $cssFiles);
276 }
277 foreach ($cssFiles as $cssFile) {
278 $this->pageRenderer->addCssFile($relativeComponentPath . 'css/' . $cssFile);
279 }
280 $jsFiles = GeneralUtility::getFilesInDir($absoluteComponentPath . 'javascript/', 'js');
281 if (file_exists($absoluteComponentPath . 'javascript/loadorder.txt')) {
282 // Don't allow inclusion outside directory
283 $loadOrder = str_replace('../', '', GeneralUtility::getUrl($absoluteComponentPath . 'javascript/loadorder.txt'));
284 $jsFilesOrdered = GeneralUtility::trimExplode(LF, $loadOrder, TRUE);
285 $jsFiles = array_merge($jsFilesOrdered, $jsFiles);
286 }
287 foreach ($jsFiles as $jsFile) {
288 $this->pageRenderer->addJsFile($relativeComponentPath . 'javascript/' . $jsFile);
289 }
290 $this->pageRenderer->addInlineSetting('RecordHistory', 'moduleUrl', BackendUtility::getModuleUrl('record_history'));
291 }
292 }
293
294 /**
295 * Renders the items in the top toolbar
296 *
297 * @return string top toolbar elements as HTML
298 */
299 protected function renderToolbar() {
300 $toolbar = array();
301 foreach ($this->toolbarItems as $toolbarItem) {
302 /** @var \TYPO3\CMS\Backend\Toolbar\ToolbarItemInterface $toolbarItem */
303 if ($toolbarItem->checkAccess()) {
304 $hasDropDown = (bool)$toolbarItem->hasDropDown();
305 $additionalAttributes = (array)$toolbarItem->getAdditionalAttributes();
306
307 $liAttributes = array();
308
309 // Merge class: Add dropdown class if hasDropDown, add classes from additonal attributes
310 $classes = array();
311 if ($hasDropDown) {
312 $classes[] = 'dropdown';
313 }
314 if (isset($additionalAttributes['class'])) {
315 $classes[] = $additionalAttributes['class'];
316 unset($additionalAttributes['class']);
317 }
318 $liAttributes[] = 'class="' . implode(' ', $classes) . '"';
319
320 // Add further attributes
321 foreach($additionalAttributes as $name => $value) {
322 $liAttributes[] = $name . '="' . $value . '"';
323 }
324
325 // Create a unique id from class name
326 $className = get_class($toolbarItem);
327 $className = GeneralUtility::underscoredToLowerCamelCase($className);
328 $className = GeneralUtility::camelCaseToLowerCaseUnderscored($className);
329 $className = str_replace(array('_', '\\'), '-', $className);
330 $liAttributes[] = 'id="' . $className . '"';
331
332 $toolbar[] = '<li ' . implode(' ', $liAttributes) . '>';
333
334 if ($hasDropDown) {
335 $toolbar[] = '<a href="#" class="dropdown-toggle" data-toggle="dropdown">';
336 $toolbar[] = $toolbarItem->getItem();
337 $toolbar[] = '</a>';
338 $toolbar[] = '<div class="dropdown-menu" role="menu">';
339 $toolbar[] = $toolbarItem->getDropDown();
340 $toolbar[] = '</div>';
341 } else {
342 $toolbar[] = $toolbarItem->getItem();
343 }
344 $toolbar[] = '</li>';
345 }
346 }
347 return implode(LF, $toolbar);
348 }
349
350 /**
351 * Returns the file name to the LLL JavaScript, containing the localized labels,
352 * which can be used in JavaScript code.
353 *
354 * @return string File name of the JS file, relative to TYPO3_mainDir
355 */
356 protected function getLocalLangFileName() {
357 $code = $this->generateLocalLang();
358 $filePath = 'typo3temp/locallang-BE-' . sha1($code) . '.js';
359 if (!file_exists((PATH_site . $filePath))) {
360 // writeFileToTypo3tempDir() returns NULL on success (please double-read!)
361 if (GeneralUtility::writeFileToTypo3tempDir(PATH_site . $filePath, $code) !== NULL) {
362 throw new \RuntimeException('LocalLangFile could not be written to ' . $filePath, 1295193026);
363 }
364 }
365 return '../' . $filePath;
366 }
367
368 /**
369 * Reads labels required in JavaScript code from the localization system and returns them as JSON
370 * array in TYPO3.LLL.
371 *
372 * @return string JavaScript code containing the LLL labels in TYPO3.LLL
373 */
374 protected function generateLocalLang() {
375 $coreLabels = array(
376 'waitTitle' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_logging_in'),
377 'refresh_login_failed' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_failed'),
378 'refresh_login_failed_message' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_failed_message'),
379 'refresh_login_title' => sprintf($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_title'), htmlspecialchars($GLOBALS['BE_USER']->user['username'])),
380 'login_expired' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.login_expired'),
381 'refresh_login_username' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_username'),
382 'refresh_login_password' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_password'),
383 'refresh_login_emptyPassword' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_emptyPassword'),
384 'refresh_login_button' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_button'),
385 'refresh_logout_button' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_logout_button'),
386 'please_wait' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.please_wait'),
387 'loadingIndicator' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:loadingIndicator'),
388 'be_locked' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.be_locked'),
389 'refresh_login_countdown_singular' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_countdown_singular'),
390 'refresh_login_countdown' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_countdown'),
391 'login_about_to_expire' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.login_about_to_expire'),
392 'login_about_to_expire_title' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.login_about_to_expire_title'),
393 'refresh_login_refresh_button' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_login_refresh_button'),
394 'refresh_direct_logout_button' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:mess.refresh_direct_logout_button'),
395 'tabs_closeAll' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:tabs.closeAll'),
396 'tabs_closeOther' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:tabs.closeOther'),
397 'tabs_close' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:tabs.close'),
398 'tabs_openInBrowserWindow' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:tabs.openInBrowserWindow'),
399 'csh_tooltip_loading' => $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:csh_tooltip_loading')
400 );
401 $labels = array(
402 'fileUpload' => array(
403 'windowTitle',
404 'buttonSelectFiles',
405 'buttonCancelAll',
406 'infoComponentMaxFileSize',
407 'infoComponentFileUploadLimit',
408 'infoComponentFileTypeLimit',
409 'infoComponentOverrideFiles',
410 'processRunning',
411 'uploadWait',
412 'uploadStarting',
413 'uploadProgress',
414 'uploadSuccess',
415 'errorQueueLimitExceeded',
416 'errorQueueFileSizeLimit',
417 'errorQueueZeroByteFile',
418 'errorQueueInvalidFiletype',
419 'errorUploadHttp',
420 'errorUploadMissingUrl',
421 'errorUploadIO',
422 'errorUploadSecurityError',
423 'errorUploadLimit',
424 'errorUploadFailed',
425 'errorUploadFileIDNotFound',
426 'errorUploadFileValidation',
427 'errorUploadFileCancelled',
428 'errorUploadStopped',
429 'allErrorMessageTitle',
430 'allErrorMessageText',
431 'allError401',
432 'allError2038'
433 ),
434 'liveSearch' => array(
435 'title',
436 'helpTitle',
437 'emptyText',
438 'loadingText',
439 'listEmptyText',
440 'showAllResults',
441 'helpDescription',
442 'helpDescriptionPages',
443 'helpDescriptionContent'
444 ),
445 'viewPort' => array(
446 'tooltipModuleMenuSplit',
447 'tooltipNavigationContainerSplitDrag',
448 'tooltipDebugPanelSplitDrag'
449 )
450 );
451 $generatedLabels = array();
452 $generatedLabels['core'] = $coreLabels;
453 // First loop over all categories (fileUpload, liveSearch, ..)
454 foreach ($labels as $categoryName => $categoryLabels) {
455 // Then loop over every single label
456 foreach ($categoryLabels as $label) {
457 // LLL identifier must be called $categoryName_$label, e.g. liveSearch_loadingText
458 $generatedLabels[$categoryName][$label] = $GLOBALS['LANG']->getLL($categoryName . '_' . $label);
459 }
460 }
461 return 'TYPO3.LLL = ' . json_encode($generatedLabels) . ';';
462 }
463
464 /**
465 * Generates the JavaScript code for the backend.
466 *
467 * @return void
468 */
469 protected function generateJavascript() {
470 $pathTYPO3 = GeneralUtility::dirname(GeneralUtility::getIndpEnv('SCRIPT_NAME')) . '/';
471 // If another page module was specified, replace the default Page module with the new one
472 $newPageModule = trim($GLOBALS['BE_USER']->getTSConfigVal('options.overridePageModule'));
473 $pageModule = BackendUtility::isModuleSetInTBE_MODULES($newPageModule) ? $newPageModule : 'web_layout';
474 if (!$GLOBALS['BE_USER']->check('modules', $pageModule)) {
475 $pageModule = '';
476 }
477 $menuFrameName = 'menu';
478 if ($GLOBALS['BE_USER']->uc['noMenuMode'] === 'icons') {
479 $menuFrameName = 'topmenuFrame';
480 }
481 // Determine security level from conf vars and default to super challenged
482 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['loginSecurityLevel']) {
483 $this->loginSecurityLevel = $GLOBALS['TYPO3_CONF_VARS']['BE']['loginSecurityLevel'];
484 } else {
485 $this->loginSecurityLevel = 'superchallenged';
486 }
487 $t3Configuration = array(
488 'siteUrl' => GeneralUtility::getIndpEnv('TYPO3_SITE_URL'),
489 'PATH_typo3' => $pathTYPO3,
490 'PATH_typo3_enc' => rawurlencode($pathTYPO3),
491 'username' => htmlspecialchars($GLOBALS['BE_USER']->user['username']),
492 'uniqueID' => GeneralUtility::shortMD5(uniqid('', TRUE)),
493 'securityLevel' => $this->loginSecurityLevel,
494 'TYPO3_mainDir' => TYPO3_mainDir,
495 'pageModule' => $pageModule,
496 'inWorkspace' => $GLOBALS['BE_USER']->workspace !== 0,
497 'workspaceFrontendPreviewEnabled' => $GLOBALS['BE_USER']->user['workspace_preview'] ? 1 : 0,
498 'veriCode' => $GLOBALS['BE_USER']->veriCode(),
499 'denyFileTypes' => PHP_EXTENSIONS_DEFAULT,
500 'moduleMenuWidth' => $this->menuWidth - 1,
501 'topBarHeight' => isset($GLOBALS['TBE_STYLES']['dims']['topFrameH']) ? (int)$GLOBALS['TBE_STYLES']['dims']['topFrameH'] : 30,
502 'showRefreshLoginPopup' => isset($GLOBALS['TYPO3_CONF_VARS']['BE']['showRefreshLoginPopup']) ? (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['showRefreshLoginPopup'] : FALSE,
503 'listModulePath' => ExtensionManagementUtility::extRelPath('recordlist') . 'mod1/',
504 'debugInWindow' => $GLOBALS['BE_USER']->uc['debugInWindow'] ? 1 : 0,
505 'ContextHelpWindows' => array(
506 'width' => 600,
507 'height' => 400
508 ),
509 );
510 $this->js .= '
511 TYPO3.configuration = ' . json_encode($t3Configuration) . ';
512
513 /**
514 * TypoSetup object.
515 */
516 function typoSetup() { //
517 this.PATH_typo3 = TYPO3.configuration.PATH_typo3;
518 this.PATH_typo3_enc = TYPO3.configuration.PATH_typo3_enc;
519 this.username = TYPO3.configuration.username;
520 this.uniqueID = TYPO3.configuration.uniqueID;
521 this.navFrameWidth = 0;
522 this.securityLevel = TYPO3.configuration.securityLevel;
523 this.veriCode = TYPO3.configuration.veriCode;
524 this.denyFileTypes = TYPO3.configuration.denyFileTypes;
525 }
526 var TS = new typoSetup();
527 //backwards compatibility
528 /**
529 * Frameset Module object
530 *
531 * Used in main modules with a frameset for submodules to keep the ID between modules
532 * Typically that is set by something like this in a Web>* sub module:
533 * if (top.fsMod) top.fsMod.recentIds["web"] = "\'.(int)$this->id.\'";
534 * if (top.fsMod) top.fsMod.recentIds["file"] = "...(file reference/string)...";
535 */
536 function fsModules() { //
537 this.recentIds=new Array(); // used by frameset modules to track the most recent used id for list frame.
538 this.navFrameHighlightedID=new Array(); // used by navigation frames to track which row id was highlighted last time
539 this.currentMainLoaded="";
540 this.currentBank="0";
541 }
542 var fsMod = new fsModules();
543
544 top.goToModule = function(modName, cMR_flag, addGetVars) {
545 TYPO3.ModuleMenu.App.showModule(modName, addGetVars);
546 }
547 ' . $this->setStartupModule();
548 // Check editing of page:
549 $this->handlePageEditing();
550 }
551
552 /**
553 * Checking if the "&edit" variable was sent so we can open it for editing the page.
554 *
555 * @return void
556 */
557 protected function handlePageEditing() {
558 // EDIT page:
559 $editId = preg_replace('/[^[:alnum:]_]/', '', GeneralUtility::_GET('edit'));
560 $editRecord = '';
561 if ($editId) {
562 // Looking up the page to edit, checking permissions:
563 $where = ' AND (' . $GLOBALS['BE_USER']->getPagePermsClause(2) . ' OR ' . $GLOBALS['BE_USER']->getPagePermsClause(16) . ')';
564 if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($editId)) {
565 $editRecord = BackendUtility::getRecordWSOL('pages', $editId, '*', $where);
566 } else {
567 $records = BackendUtility::getRecordsByField('pages', 'alias', $editId, $where);
568 if (is_array($records)) {
569 $editRecord = reset($records);
570 BackendUtility::workspaceOL('pages', $editRecord);
571 }
572 }
573 // If the page was accessible, then let the user edit it.
574 if (is_array($editRecord) && $GLOBALS['BE_USER']->isInWebMount($editRecord['uid'])) {
575 // Setting JS code to open editing:
576 $this->js .= '
577 // Load page to edit:
578 window.setTimeout("top.loadEditId(' . (int)$editRecord['uid'] . ');", 500);
579 ';
580 // Checking page edit parameter:
581 if (!$GLOBALS['BE_USER']->getTSConfigVal('options.bookmark_onEditId_dontSetPageTree')) {
582 $bookmarkKeepExpanded = $GLOBALS['BE_USER']->getTSConfigVal('options.bookmark_onEditId_keepExistingExpanded');
583 // Expanding page tree:
584 BackendUtility::openPageTree((int)$editRecord['pid'], !$bookmarkKeepExpanded);
585 }
586 } else {
587 $this->js .= '
588 // Warning about page editing:
589 alert(' . GeneralUtility::quoteJSvalue(sprintf($GLOBALS['LANG']->getLL('noEditPage'), $editId)) . ');
590 ';
591 }
592 }
593 }
594
595 /**
596 * Sets the startup module from either GETvars module and modParams or user configuration.
597 *
598 * @return string the JavaScript code for the startup module
599 */
600 protected function setStartupModule() {
601 $startModule = preg_replace('/[^[:alnum:]_]/', '', GeneralUtility::_GET('module'));
602 if (!$startModule) {
603 // start module on first login, will be removed once used the first time
604 if (isset($GLOBALS['BE_USER']->uc['startModuleOnFirstLogin'])) {
605 $startModule = $GLOBALS['BE_USER']->uc['startModuleOnFirstLogin'];
606 unset($GLOBALS['BE_USER']->uc['startModuleOnFirstLogin']);
607 $GLOBALS['BE_USER']->writeUC();
608 } elseif ($GLOBALS['BE_USER']->uc['startModule']) {
609 $startModule = $GLOBALS['BE_USER']->uc['startModule'];
610 } elseif ($GLOBALS['BE_USER']->uc['startInTaskCenter']) {
611 $startModule = 'user_task';
612 }
613
614 // check if the start module has additional parameters, so a redirect to a specific
615 // action is possible
616 if (strpos($startModule, '->') !== FALSE) {
617 list($startModule, $startModuleParameters) = explode('->', $startModule, 2);
618 }
619 }
620
621 $moduleParameters = GeneralUtility::_GET('modParams');
622 // if no GET parameters are set, check if there are parameters given from the UC
623 if (!$moduleParameters && $startModuleParameters) {
624 $moduleParameters = $startModuleParameters;
625 }
626
627 if ($startModule) {
628 return '
629 // start in module:
630 top.startInModule = [\'' . $startModule . '\', ' . GeneralUtility::quoteJSvalue($moduleParameters) . '];
631 ';
632 } else {
633 return '';
634 }
635 }
636
637 /**
638 * Adds a javascript snippet to the backend
639 *
640 * @param string $javascript Javascript snippet
641 * @return void
642 * @throws \InvalidArgumentException
643 */
644 public function addJavascript($javascript) {
645 // TODO do we need more checks?
646 if (!is_string($javascript)) {
647 throw new \InvalidArgumentException('parameter $javascript must be of type string', 1195129553);
648 }
649 $this->js .= $javascript;
650 }
651
652 /**
653 * Adds a javscript file to the backend after it has been checked that it exists
654 *
655 * @param string $javascriptFile Javascript file reference
656 * @return bool TRUE if the javascript file was successfully added, FALSE otherwise
657 */
658 public function addJavascriptFile($javascriptFile) {
659 $jsFileAdded = FALSE;
660 //TODO add more checks if necessary
661 if (file_exists(GeneralUtility::resolveBackPath(PATH_typo3 . $javascriptFile))) {
662 $this->jsFiles[] = $javascriptFile;
663 $jsFileAdded = TRUE;
664 }
665 return $jsFileAdded;
666 }
667
668 /**
669 * Adds a css snippet to the backend
670 *
671 * @param string $css Css snippet
672 * @return void
673 */
674 public function addCss($css) {
675 if (!is_string($css)) {
676 throw new \InvalidArgumentException('parameter $css must be of type string', 1195129642);
677 }
678 $this->css .= $css;
679 }
680
681 /**
682 * Adds a css file to the backend after it has been checked that it exists
683 *
684 * @param string $cssFileName The css file's name with out the .css ending
685 * @param string $cssFile Css file reference
686 * @return bool TRUE if the css file was added, FALSE otherwise
687 */
688 public function addCssFile($cssFileName, $cssFile) {
689 $cssFileAdded = FALSE;
690 if (empty($this->cssFiles[$cssFileName])) {
691 $this->cssFiles[$cssFileName] = $cssFile;
692 $cssFileAdded = TRUE;
693 }
694 return $cssFileAdded;
695 }
696
697 /**
698 * Adds an item to the toolbar, the class file for the toolbar item must be loaded at this point
699 *
700 * @param string $toolbarItemName Toolbar item name, f.e. tx_toolbarExtension_coolItem
701 * @param string $toolbarItemClassName Toolbar item class name, f.e. tx_toolbarExtension_coolItem
702 * @return void
703 * @throws \UnexpectedValueException
704 * @deprecated since CMS 7, will be removed with CMS 8. Toolbar items are registered in $GLOBALS['TYPO3_CONF_VARS']['BE']['toolbarItems'] now.
705 */
706 public function addToolbarItem($toolbarItemName, $toolbarItemClassName) {
707 GeneralUtility::logDeprecatedFunction();
708 }
709
710 /**
711 * Executes defined hooks functions for the given identifier.
712 *
713 * These hook identifiers are valid:
714 * + constructPostProcess
715 * + renderPreProcess
716 * + renderPostProcess
717 *
718 * @param string $identifier Specific hook identifier
719 * @param array $hookConfiguration Additional configuration passed to hook functions
720 * @return void
721 */
722 protected function executeHook($identifier, array $hookConfiguration = array()) {
723 $options = &$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/backend.php'];
724 if (isset($options[$identifier]) && is_array($options[$identifier])) {
725 foreach ($options[$identifier] as $hookFunction) {
726 GeneralUtility::callUserFunction($hookFunction, $hookConfiguration, $this);
727 }
728 }
729 }
730
731 /**
732 * loads all modules from the repository
733 * and renders it with a template
734 *
735 * @return string
736 */
737 protected function generateModuleMenu() {
738 // get all modules except the user modules for the side menu
739 $moduleStorage = $this->backendModuleRepository->loadAllowedModules(array('user', 'help'));
740
741 $view = $this->getFluidTemplateObject('EXT:backend/Resources/Private/Templates/ModuleMenu/Main.html');
742 $view->assign('modules', $moduleStorage);
743 return $view->render();
744 }
745
746 /**
747 * Returns the Module menu for the AJAX API
748 *
749 * @param array $params
750 * @param \TYPO3\CMS\Core\Http\AjaxRequestHandler $ajaxRequestHandler
751 * @return void
752 */
753 public function getModuleMenuForReload($params, $ajaxRequestHandler) {
754 $content = $this->generateModuleMenu();
755 $ajaxRequestHandler->addContent('menu', $content);
756 $ajaxRequestHandler->setContentFormat('json');
757 }
758
759 /**
760 * returns a new standalone view, shorthand function
761 *
762 * @param string $templatePathAndFileName optional the path to set the template path and filename
763 * @return \TYPO3\CMS\Fluid\View\StandaloneView
764 */
765 protected function getFluidTemplateObject($templatePathAndFileName = NULL) {
766 $view = GeneralUtility::makeInstance(\TYPO3\CMS\Fluid\View\StandaloneView::class);
767 if ($templatePathAndFileName) {
768 $view->setTemplatePathAndFilename(GeneralUtility::getFileAbsFileName($templatePathAndFileName));
769 }
770 return $view;
771 }
772 }