[!!!][TASK] Remove path-based backend module registration
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / Template / DocumentTemplate.php
1 <?php
2 namespace TYPO3\CMS\Backend\Template;
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 Psr\Http\Message\ResponseInterface;
18 use Psr\Http\Message\ServerRequestInterface;
19 use TYPO3\CMS\Backend\Utility\BackendUtility;
20 use TYPO3\CMS\Core\Imaging\Icon;
21 use TYPO3\CMS\Core\Imaging\IconFactory;
22 use TYPO3\CMS\Core\Page\PageRenderer;
23 use TYPO3\CMS\Core\Service\MarkerBasedTemplateService;
24 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
25 use TYPO3\CMS\Core\Utility\GeneralUtility;
26 use TYPO3\CMS\Fluid\View\StandaloneView;
27
28 /**
29 * TYPO3 Backend Template Class
30 *
31 * This class contains functions for starting and ending the HTML of backend modules
32 * It also contains methods for outputting sections of content.
33 * Further there are functions for making icons, links, setting form-field widths etc.
34 * Color scheme and stylesheet definitions are also available here.
35 * Finally this file includes the language class for TYPO3's backend.
36 *
37 * After this file $LANG and $TBE_TEMPLATE are global variables / instances of their respective classes.
38 *
39 * Please refer to Inside TYPO3 for a discussion of how to use this API.
40 */
41 class DocumentTemplate
42 {
43 // Vars you typically might want to/should set from outside after making instance of this class:
44 /**
45 * This can be set to the HTML-code for a formtag.
46 * Useful when you need a form to span the whole page; Inserted exactly after the body-tag.
47 *
48 * @var string
49 */
50 public $form = '';
51
52 /**
53 * Additional header code (eg. a JavaScript section) could be accommulated in this var. It will be directly outputted in the header.
54 *
55 * @var string
56 */
57 public $JScode = '';
58
59 /**
60 * Additional header code for ExtJS. It will be included in document header and inserted in a Ext.onReady(function()
61 *
62 * @var string
63 */
64 public $extJScode = '';
65
66 /**
67 * Similar to $JScode but for use as array with associative keys to prevent double inclusion of JS code. a <script> tag is automatically wrapped around.
68 *
69 * @var array
70 */
71 public $JScodeArray = array('jumpToUrl' => '
72 function jumpToUrl(URL) {
73 window.location.href = URL;
74 return false;
75 }
76 ');
77
78 /**
79 * Additional 'page-end' code could be accumulated in this var. It will be outputted at the end of page before </body> and some other internal page-end code.
80 *
81 * @var string
82 */
83 public $postCode = '';
84
85 /**
86 * HTML template with markers for module
87 *
88 * @var string
89 */
90 public $moduleTemplate = '';
91
92 /**
93 * The base file (not overlaid by TBE_STYLES) for the current module, useful for hooks when finding out which modules is rendered currently
94 *
95 * @var string
96 */
97 protected $moduleTemplateFilename = '';
98
99 /**
100 * Script ID
101 *
102 * @var string
103 */
104 public $scriptID = '';
105
106 /**
107 * Id which can be set for the body tag. Default value is based on script ID
108 *
109 * @var string
110 */
111 public $bodyTagId = '';
112
113 /**
114 * You can add additional attributes to the body-tag through this variable.
115 *
116 * @var string
117 */
118 public $bodyTagAdditions = '';
119
120 /**
121 * Additional CSS styles which will be added to the <style> section in the header
122 * used as array with associative keys to prevent double inclusion of CSS code
123 *
124 * @var array
125 */
126 public $inDocStylesArray = array();
127
128 /**
129 * Compensation for large documents (used in \TYPO3\CMS\Backend\Form\FormEngine)
130 *
131 * @var float
132 */
133 public $form_largeComp = 1.33;
134
135 /**
136 * Filename of stylesheet (relative to PATH_typo3)
137 *
138 * @var string
139 */
140 public $styleSheetFile = '';
141
142 /**
143 * Filename of stylesheet #2 - linked to right after the $this->styleSheetFile script (relative to PATH_typo3)
144 *
145 * @var string
146 */
147 public $styleSheetFile2 = '';
148
149 /**
150 * Filename of a post-stylesheet - included right after all inline styles.
151 *
152 * @var string
153 */
154 public $styleSheetFile_post = '';
155
156 /**
157 * Whether to use the X-UA-Compatible meta tag
158 *
159 * @var bool
160 */
161 protected $useCompatibilityTag = true;
162
163 /**
164 * X-Ua-Compatible version output in meta tag
165 *
166 * @var string
167 */
168 protected $xUaCompatibilityVersion = 'IE=edge';
169
170 // Skinning
171 /**
172 * stylesheets from core
173 *
174 * @var array
175 */
176 protected $stylesheetsCore = array(
177 'generatedSprites' => '../typo3temp/sprites/'
178 );
179
180 /**
181 * Include these CSS directories from skins by default
182 *
183 * @var array
184 */
185 protected $stylesheetsSkins = array(
186 'structure' => 'Resources/Public/Css/structure/',
187 'visual' => 'Resources/Public/Css/visual/'
188 );
189
190 /**
191 * JavaScript files loaded for every page in the Backend
192 *
193 * @var array
194 */
195 protected $jsFiles = array();
196
197 /**
198 * JavaScript files loaded for every page in the Backend, but explicitly excluded from concatenation (useful for libraries etc.)
199 *
200 * @var array
201 */
202 protected $jsFilesNoConcatenation = array();
203
204 /**
205 * Indicates if a <div>-output section is open
206 *
207 * @var int
208 * @internal
209 */
210 public $sectionFlag = 0;
211
212 /**
213 * (Default) Class for wrapping <DIV>-tag of page. Is set in class extensions.
214 *
215 * @var string
216 */
217 public $divClass = '';
218
219 /**
220 * @var string
221 */
222 public $pageHeaderBlock = '';
223
224 /**
225 * @var string
226 */
227 public $endOfPageJsBlock = '';
228
229 /**
230 * @var bool
231 */
232 public $hasDocheader = true;
233
234 /**
235 * @var PageRenderer
236 */
237 protected $pageRenderer = null;
238
239 /**
240 * Alternative template file
241 *
242 * @var string
243 */
244 protected $pageHeaderFooterTemplateFile = '';
245
246 /**
247 * @var bool
248 */
249 protected $extDirectStateProvider = false;
250
251 /**
252 * Whether flashmessages should be rendered or not
253 *
254 * @var bool $showFlashMessages
255 */
256 public $showFlashMessages = true;
257
258 /**
259 * @var IconFactory
260 */
261 protected $iconFactory;
262
263 /**
264 * @var MarkerBasedTemplateService
265 */
266 protected $templateService;
267
268 const STATUS_ICON_ERROR = 3;
269 const STATUS_ICON_WARNING = 2;
270 const STATUS_ICON_NOTIFICATION = 1;
271 const STATUS_ICON_OK = -1;
272
273 /**
274 * Constructor
275 */
276 public function __construct()
277 {
278 // Initializes the page rendering object:
279 $this->initPageRenderer();
280
281 // load Legacy CSS Support
282 $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/LegacyCssClasses');
283 $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
284
285 // initialize Marker Support
286 $this->templateService = GeneralUtility::makeInstance(MarkerBasedTemplateService::class);
287
288 // Setting default scriptID:
289 $this->scriptID = GeneralUtility::_GET('M') !== null ? GeneralUtility::_GET('M') : GeneralUtility::_GET('route');
290 $this->bodyTagId = preg_replace('/[^A-Za-z0-9-]/', '-', $this->scriptID);
291 // Individual configuration per script? If so, make a recursive merge of the arrays:
292 if (is_array($GLOBALS['TBE_STYLES']['scriptIDindex'][$this->scriptID])) {
293 // Make copy
294 $ovr = $GLOBALS['TBE_STYLES']['scriptIDindex'][$this->scriptID];
295 // merge styles.
296 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($GLOBALS['TBE_STYLES'], $ovr);
297 // Have to unset - otherwise the second instantiation will do it again!
298 unset($GLOBALS['TBE_STYLES']['scriptIDindex'][$this->scriptID]);
299 }
300 // Main Stylesheets:
301 if ($GLOBALS['TBE_STYLES']['stylesheet']) {
302 $this->styleSheetFile = $GLOBALS['TBE_STYLES']['stylesheet'];
303 }
304 if ($GLOBALS['TBE_STYLES']['stylesheet2']) {
305 $this->styleSheetFile2 = $GLOBALS['TBE_STYLES']['stylesheet2'];
306 }
307 if ($GLOBALS['TBE_STYLES']['styleSheetFile_post']) {
308 $this->styleSheetFile_post = $GLOBALS['TBE_STYLES']['styleSheetFile_post'];
309 }
310 if ($GLOBALS['TBE_STYLES']['inDocStyles_TBEstyle']) {
311 $this->inDocStylesArray['TBEstyle'] = $GLOBALS['TBE_STYLES']['inDocStyles_TBEstyle'];
312 }
313 // include all stylesheets
314 foreach ($this->getSkinStylesheetDirectories() as $stylesheetDirectory) {
315 $this->addStylesheetDirectory($stylesheetDirectory);
316 }
317 // Background image
318 if ($GLOBALS['TBE_STYLES']['background']) {
319 GeneralUtility::deprecationLog('Usage of $TBE_STYLES["background"] is deprecated. Please use stylesheets directly.');
320 }
321 }
322
323 /**
324 * Initializes the page renderer object
325 */
326 protected function initPageRenderer()
327 {
328 if ($this->pageRenderer !== null) {
329 return;
330 }
331 $this->pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
332 $this->pageRenderer->setLanguage($GLOBALS['LANG']->lang);
333 $this->pageRenderer->enableConcatenateFiles();
334 $this->pageRenderer->enableCompressCss();
335 $this->pageRenderer->enableCompressJavascript();
336 // Add all JavaScript files defined in $this->jsFiles to the PageRenderer
337 foreach ($this->jsFilesNoConcatenation as $file) {
338 $this->pageRenderer->addJsFile(
339 $GLOBALS['BACK_PATH'] . $file,
340 'text/javascript',
341 true,
342 false,
343 '',
344 true
345 );
346 }
347 // Add all JavaScript files defined in $this->jsFiles to the PageRenderer
348 foreach ($this->jsFiles as $file) {
349 $this->pageRenderer->addJsFile($GLOBALS['BACK_PATH'] . $file);
350 }
351 if ((int)$GLOBALS['TYPO3_CONF_VARS']['BE']['debug'] === 1) {
352 $this->pageRenderer->enableDebugMode();
353 }
354 }
355
356 /**
357 * Sets inclusion of StateProvider
358 *
359 * @return void
360 */
361 public function setExtDirectStateProvider()
362 {
363 $this->extDirectStateProvider = true;
364 }
365
366 /*****************************************
367 *
368 * EVALUATION FUNCTIONS
369 * Various centralized processing
370 *
371 *****************************************/
372
373 /**
374 * Makes link to page $id in frontend (view page)
375 * Returns an icon which links to the frontend index.php document for viewing the page with id $id
376 * $id must be a page-uid
377 * If the BE_USER has access to Web>List then a link to that module is shown as well (with return-url)
378 *
379 * @param int $id The page id
380 * @return string HTML string with linked icon(s)
381 */
382 public function viewPageIcon($id)
383 {
384 // If access to Web>List for user, then link to that module.
385 $str = BackendUtility::getListViewLink(array(
386 'id' => $id,
387 'returnUrl' => GeneralUtility::getIndpEnv('REQUEST_URI')
388 ), $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.showList'));
389 // Make link to view page
390 $str .= '<a href="#" onclick="' . htmlspecialchars(BackendUtility::viewOnClick($id, '', BackendUtility::BEgetRootLine($id))) . '" title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.showPage', true) . '">' . $this->iconFactory->getIcon('actions-document-view', Icon::SIZE_SMALL)->render() . '</a>';
391 return $str;
392 }
393
394 /**
395 * Makes the header (icon+title) for a page (or other record). Used in most modules under Web>*
396 * $table and $row must be a tablename/record from that table
397 * $path will be shown as alt-text for the icon.
398 * The title will be truncated to 45 chars.
399 *
400 * @param string $table Table name
401 * @param array $row Record row
402 * @param string $path Alt text
403 * @param bool $noViewPageIcon Set $noViewPageIcon TRUE if you don't want a magnifier-icon for viewing the page in the frontend
404 * @param array $tWrap is an array with indexes 0 and 1 each representing HTML-tags (start/end) which will wrap the title
405 * @param bool $enableClickMenu If TRUE, render click menu code around icon image
406 * @return string HTML content
407 */
408 public function getHeader($table, $row, $path, $noViewPageIcon = false, $tWrap = array('', ''), $enableClickMenu = true)
409 {
410 $viewPage = '';
411 if (is_array($row) && $row['uid']) {
412 $iconImgTag = '<span title="' . htmlspecialchars($path) . '">' . $this->iconFactory->getIconForRecord($table, $row, Icon::SIZE_SMALL)->render() . '</span>';
413 $title = strip_tags(BackendUtility::getRecordTitle($table, $row));
414 $viewPage = $noViewPageIcon ? '' : $this->viewPageIcon($row['uid']);
415 } else {
416 $iconImgTag = '<span title="' . htmlspecialchars($path) . '">' . $this->iconFactory->getIcon('apps-pagetree-page-domain', Icon::SIZE_SMALL)->render() . '</span>';
417 $title = $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'];
418 }
419
420 if ($enableClickMenu) {
421 $iconImgTag = BackendUtility::wrapClickMenuOnIcon($iconImgTag, $table, $row['uid']);
422 }
423
424 return '<span class="typo3-moduleHeader">' . $iconImgTag . $viewPage . $tWrap[0] . htmlspecialchars(GeneralUtility::fixed_lgd_cs($title, 45)) . $tWrap[1] . '</span>';
425 }
426
427 /**
428 * Like ->getHeader() but for files and folders
429 * Returns the icon with the path of the file/folder set in the alt/title attribute. Shows the name after the icon.
430 *
431 * @param \TYPO3\CMS\Core\Resource\ResourceInterface $resource
432 * @param array $tWrap is an array with indexes 0 and 1 each representing HTML-tags (start/end) which will wrap the title
433 * @param bool $enableClickMenu If TRUE, render click menu code around icon image
434 * @return string
435 */
436 public function getResourceHeader(\TYPO3\CMS\Core\Resource\ResourceInterface $resource, $tWrap = array('', ''), $enableClickMenu = true)
437 {
438 try {
439 $path = $resource->getStorage()->getName() . $resource->getParentFolder()->getIdentifier();
440 $iconImgTag = '<span title="' . htmlspecialchars($path) . '">' . $this->iconFactory->getIconForResource($resource, Icon::SIZE_SMALL)->render() . '</span>';
441 } catch (\TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException $e) {
442 $iconImgTag = '';
443 }
444
445 if ($enableClickMenu && ($resource instanceof \TYPO3\CMS\Core\Resource\File)) {
446 $metaData = $resource->_getMetaData();
447 $iconImgTag = BackendUtility::wrapClickMenuOnIcon($iconImgTag, 'sys_file_metadata', $metaData['uid']);
448 }
449
450 return '<span class="typo3-moduleHeader">' . $iconImgTag . $tWrap[0] . htmlspecialchars(GeneralUtility::fixed_lgd_cs($resource->getName(), 45)) . $tWrap[1] . '</span>';
451 }
452
453 /**
454 * Returns a linked shortcut-icon which will call the shortcut frame and set a shortcut there back to the calling page/module
455 *
456 * @param string $gvList Is the list of GET variables to store (if any)
457 * @param string $setList Is the list of SET[] variables to store (if any) - SET[] variables a stored in $GLOBALS["SOBE"]->MOD_SETTINGS for backend modules
458 * @param string $modName Module name string
459 * @param string|int $motherModName Is used to enter the "parent module name" if the module is a submodule under eg. Web>* or File>*. You can also set this value to 1 in which case the currentLoadedModule is sent to the shortcut script (so - not a fixed value!) - that is used in file_edit and wizard_rte modules where those are really running as a part of another module.
460 * @param string $classes
461 * @return string HTML content
462 */
463 public function makeShortcutIcon($gvList, $setList, $modName, $motherModName = '', $classes = '')
464 {
465 $gvList = 'route,' . $gvList;
466 $storeUrl = $this->makeShortcutUrl($gvList, $setList);
467 $pathInfo = parse_url(GeneralUtility::getIndpEnv('REQUEST_URI'));
468 // Fallback for alt_mod. We still pass in the old xMOD... stuff, but TBE_MODULES only knows about "record_edit".
469 // We still need to pass the xMOD name to createShortcut below, since this is used for icons.
470 $moduleName = $modName === 'xMOD_alt_doc.php' ? 'record_edit' : $modName;
471 // Add the module identifier automatically if typo3/index.php is used:
472 if (GeneralUtility::_GET('M') !== null) {
473 $storeUrl = '&M=' . $moduleName . $storeUrl;
474 }
475 if ((int)$motherModName === 1) {
476 $motherModule = 'top.currentModuleLoaded';
477 } elseif ($motherModName) {
478 $motherModule = GeneralUtility::quoteJSvalue($motherModName);
479 } else {
480 $motherModule = '\'\'';
481 }
482 $confirmationText = GeneralUtility::quoteJSvalue($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.makeBookmark'));
483
484 $shortcutUrl = $pathInfo['path'] . '?' . $storeUrl;
485 $shortcutExist = BackendUtility::shortcutExists($shortcutUrl);
486
487 if ($shortcutExist) {
488 return '<a class="active ' . htmlspecialchars($classes) . '" title="">' .
489 $this->iconFactory->getIcon('actions-system-shortcut-active', Icon::SIZE_SMALL)->render() . '</a>';
490 }
491 $url = GeneralUtility::quoteJSvalue(rawurlencode($shortcutUrl));
492 $onClick = 'top.TYPO3.ShortcutMenu.createShortcut(' . GeneralUtility::quoteJSvalue(rawurlencode($modName)) .
493 ', ' . $url . ', ' . $confirmationText . ', ' . $motherModule . ', this);return false;';
494
495 return '<a href="#" class="' . htmlspecialchars($classes) . '" onclick="' . htmlspecialchars($onClick) . '" title="' .
496 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.makeBookmark', true) . '">' .
497 $this->iconFactory->getIcon('actions-system-shortcut-new', Icon::SIZE_SMALL)->render() . '</a>';
498 }
499
500 /**
501 * MAKE url for storing
502 * Internal func
503 *
504 * @param string $gvList Is the list of GET variables to store (if any)
505 * @param string $setList Is the list of SET[] variables to store (if any) - SET[] variables a stored in $GLOBALS["SOBE"]->MOD_SETTINGS for backend modules
506 * @return string
507 * @access private
508 * @see makeShortcutIcon()
509 */
510 public function makeShortcutUrl($gvList, $setList)
511 {
512 $GET = GeneralUtility::_GET();
513 $storeArray = array_merge(GeneralUtility::compileSelectedGetVarsFromArray($gvList, $GET), array('SET' => GeneralUtility::compileSelectedGetVarsFromArray($setList, (array)$GLOBALS['SOBE']->MOD_SETTINGS)));
514 $storeUrl = GeneralUtility::implodeArrayForUrl('', $storeArray);
515 return $storeUrl;
516 }
517
518 /**
519 * Returns <input> attributes to set the width of an text-type input field.
520 * For client browsers with no CSS support the cols/size attribute is returned.
521 * For CSS compliant browsers (recommended) a ' style="width: ...px;"' is returned.
522 *
523 * @param int $size A relative number which multiplied with approx. 10 will lead to the width in pixels
524 * @param bool $textarea A flag you can set for textareas - DEPRECATED as there is no difference any more between the two
525 * @param string $styleOverride A string which will be returned as attribute-value for style="" instead of the calculated width (if CSS is enabled)
526 * @return string Tag attributes for an <input> tag (regarding width)
527 */
528 public function formWidth($size = 48, $textarea = false, $styleOverride = '')
529 {
530 return ' style="' . ($styleOverride ?: 'width:' . ceil($size * 9.58) . 'px;') . '"';
531 }
532
533 /**
534 * Returns JavaScript variables setting the returnUrl and thisScript location for use by JavaScript on the page.
535 * Used in fx. db_list.php (Web>List)
536 *
537 * @param string $thisLocation URL to "this location" / current script
538 * @return string Urls are returned as JavaScript variables T3_RETURN_URL and T3_THIS_LOCATION
539 * @see typo3/db_list.php
540 */
541 public function redirectUrls($thisLocation = '')
542 {
543 $thisLocation = $thisLocation ? $thisLocation : GeneralUtility::linkThisScript(array(
544 'CB' => '',
545 'SET' => '',
546 'cmd' => '',
547 'popViewId' => ''
548 ));
549 $out = '
550 var T3_RETURN_URL = ' . GeneralUtility::quoteJSvalue(str_replace('%20', '', rawurlencode(GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('returnUrl'))))) . ';
551 var T3_THIS_LOCATION = ' . GeneralUtility::quoteJSvalue(str_replace('%20', '', rawurlencode($thisLocation))) . '
552 ';
553 return $out;
554 }
555
556 /**
557 * Defines whether to use the X-UA-Compatible meta tag.
558 *
559 * @param bool $useCompatibilityTag Whether to use the tag
560 * @return void
561 */
562 public function useCompatibilityTag($useCompatibilityTag = true)
563 {
564 $this->useCompatibilityTag = (bool)$useCompatibilityTag;
565 }
566
567 /*****************************************
568 *
569 * PAGE BUILDING FUNCTIONS.
570 * Use this to build the HTML of your backend modules
571 *
572 *****************************************/
573 /**
574 * Returns page start
575 * This includes the proper header with charset, title, meta tag and beginning body-tag.
576 *
577 * @param string $title HTML Page title for the header
578 * @return string Returns the whole header section of a HTML-document based on settings in internal variables (like styles, javascript code, charset, generator and docType)
579 * @see endPage()
580 */
581 public function startPage($title)
582 {
583 // hook pre start page
584 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['preStartPageHook'])) {
585 $preStartPageHook = &$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['preStartPageHook'];
586 if (is_array($preStartPageHook)) {
587 $hookParameters = array(
588 'title' => &$title
589 );
590 foreach ($preStartPageHook as $hookFunction) {
591 GeneralUtility::callUserFunction($hookFunction, $hookParameters, $this);
592 }
593 }
594 }
595 // alternative template for Header and Footer
596 if ($this->pageHeaderFooterTemplateFile) {
597 $file = GeneralUtility::getFileAbsFileName($this->pageHeaderFooterTemplateFile, true);
598 if ($file) {
599 $this->pageRenderer->setTemplateFile($file);
600 }
601 }
602
603 // Disable rendering of XHTML tags
604 $this->pageRenderer->setRenderXhtml(false);
605
606 $languageCode = $this->pageRenderer->getLanguage() === 'default' ? 'en' : $this->pageRenderer->getLanguage();
607 $this->pageRenderer->setHtmlTag('<html lang="' . $languageCode . '">');
608
609 $headerStart = '<!DOCTYPE html>';
610 $this->pageRenderer->setXmlPrologAndDocType($headerStart);
611 $this->pageRenderer->setHeadTag('<head>' . LF . '<!-- TYPO3 Script ID: ' . htmlspecialchars($this->scriptID) . ' -->');
612 header('Content-Type:text/html;charset=utf-8');
613 $this->pageRenderer->setCharSet('utf-8');
614 $this->pageRenderer->addMetaTag($this->generator());
615 $this->pageRenderer->addMetaTag('<meta name="robots" content="noindex,follow">');
616 $this->pageRenderer->addMetaTag('<meta charset="utf-8">');
617 $this->pageRenderer->addMetaTag('<meta name="viewport" content="width=device-width, initial-scale=1">');
618 $this->pageRenderer->setFavIcon($this->getBackendFavicon());
619 if ($this->useCompatibilityTag) {
620 $this->pageRenderer->addMetaTag($this->xUaCompatible($this->xUaCompatibilityVersion));
621 }
622 $this->pageRenderer->setTitle($title);
623 // add docstyles
624 $this->docStyle();
625 if ($this->extDirectStateProvider) {
626 $this->pageRenderer->addJsFile('sysext/backend/Resources/Public/JavaScript/ExtDirect.StateProvider.js');
627 }
628 $this->pageRenderer->addHeaderData($this->JScode);
629 foreach ($this->JScodeArray as $name => $code) {
630 $this->pageRenderer->addJsInlineCode($name, $code, false);
631 }
632 if (!empty($this->JScodeLibArray)) {
633 GeneralUtility::deprecationLog('DocumentTemplate->JScodeLibArray is deprecated since TYPO3 CMS 7. Use the functionality within pageRenderer directly');
634 foreach ($this->JScodeLibArray as $library) {
635 $this->pageRenderer->addHeaderData($library);
636 }
637 }
638 if ($this->extJScode) {
639 $this->pageRenderer->addExtOnReadyCode($this->extJScode);
640 }
641
642 // Load jquery and twbs JS libraries on every backend request
643 $this->pageRenderer->loadJquery();
644 // Note: please do not reference "bootstrap" outside of the TYPO3 Core (not in your own extensions)
645 // as this is preliminary as long as Twitter bootstrap does not support AMD modules
646 // this logic will be changed once Twitter bootstrap 4 is included
647 $this->pageRenderer->addJsFile('sysext/core/Resources/Public/JavaScript/Contrib/bootstrap/bootstrap.js');
648
649 // hook for additional headerData
650 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['preHeaderRenderHook'])) {
651 $preHeaderRenderHook = &$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['preHeaderRenderHook'];
652 if (is_array($preHeaderRenderHook)) {
653 $hookParameters = array(
654 'pageRenderer' => &$this->pageRenderer
655 );
656 foreach ($preHeaderRenderHook as $hookFunction) {
657 GeneralUtility::callUserFunction($hookFunction, $hookParameters, $this);
658 }
659 }
660 }
661 // Construct page header.
662 $str = $this->pageRenderer->render(PageRenderer::PART_HEADER);
663 $this->JScode = ($this->extJScode = '');
664 $this->JScodeArray = array();
665 $this->endOfPageJsBlock = $this->pageRenderer->render(PageRenderer::PART_FOOTER);
666 $str .= $this->docBodyTagBegin() . ($this->divClass ? '
667
668 <!-- Wrapping DIV-section for whole page BEGIN -->
669 <div class="' . $this->divClass . '">
670 ' : '') . trim($this->form);
671 return $str;
672 }
673
674 /**
675 * Returns page end; This includes finishing form, div, body and html tags.
676 *
677 * @return string The HTML end of a page
678 * @see startPage()
679 */
680 public function endPage()
681 {
682 $str = $this->sectionEnd() . $this->postCode . $this->wrapScriptTags(BackendUtility::getUpdateSignalCode()) . ($this->form ? '
683 </form>' : '');
684 // If something is in buffer like debug, put it to end of page
685 if (ob_get_contents()) {
686 $str .= ob_get_clean();
687 if (!headers_sent()) {
688 header('Content-Encoding: None');
689 }
690 }
691 $str .= ($this->divClass ? '
692
693 <!-- Wrapping DIV-section for whole page END -->
694 </div>' : '') . $this->endOfPageJsBlock;
695
696 // Logging: Can't find better place to put it:
697 if (TYPO3_DLOG) {
698 GeneralUtility::devLog('END of BACKEND session', \TYPO3\CMS\Backend\Template\DocumentTemplate::class, 0, array('_FLUSH' => true));
699 }
700 return $str;
701 }
702
703 /**
704 * Shortcut for render the complete page of a module
705 *
706 * @param string $title page title
707 * @param string $content page content
708 * @return string complete page
709 */
710 public function render($title, $content)
711 {
712 $pageContent = $this->startPage($title);
713 $pageContent .= $content;
714 $pageContent .= $this->endPage();
715 return $this->insertStylesAndJS($pageContent);
716 }
717
718 /**
719 * Returns the header-bar in the top of most backend modules
720 * Closes section if open.
721 *
722 * @param string $text The text string for the header
723 * @return string HTML content
724 */
725 public function header($text)
726 {
727 $str = '
728
729 <!-- MAIN Header in page top -->
730 <h1 class="t3js-title-inlineedit">' . htmlspecialchars($text) . '</h1>
731 ';
732 return $this->sectionEnd() . $str;
733 }
734
735 /**
736 * Begins an output section and sets header and content
737 *
738 * @param string $label The header
739 * @param string $text The HTML-content
740 * @param bool $nostrtoupper A flag that will prevent the header from being converted to uppercase
741 * @param bool $sH Defines the type of header (if set, "<h3>" rather than the default "h4")
742 * @param int $type The number of an icon to show with the header (see the icon-function). -1,1,2,3
743 * @param bool $allowHTMLinHeader If set, HTML tags are allowed in $label (otherwise this value is by default htmlspecialchars()'ed)
744 * @return string HTML content
745 * @see icons(), sectionHeader()
746 */
747 public function section($label, $text, $nostrtoupper = false, $sH = false, $type = 0, $allowHTMLinHeader = false)
748 {
749 $str = '';
750 // Setting header
751 if ($label) {
752 if (!$allowHTMLinHeader) {
753 $label = htmlspecialchars($label);
754 }
755 $str .= $this->sectionHeader($this->icons($type) . $label, $sH, $nostrtoupper ? '' : ' class="uppercase"');
756 }
757 // Setting content
758 $str .= '
759
760 <!-- Section content -->
761 ' . $text;
762 return $this->sectionBegin() . $str;
763 }
764
765 /**
766 * Inserts a divider image
767 * Ends a section (if open) before inserting the image
768 *
769 * @param int $dist The margin-top/-bottom of the <hr> ruler.
770 * @return string HTML content
771 */
772 public function divider($dist)
773 {
774 $dist = (int)$dist;
775 $str = '
776
777 <!-- DIVIDER -->
778 <hr style="margin-top: ' . $dist . 'px; margin-bottom: ' . $dist . 'px;" />
779 ';
780 return $this->sectionEnd() . $str;
781 }
782
783 /**
784 * Make a section header.
785 * Begins a section if not already open.
786 *
787 * @param string $label The label between the <h3> or <h4> tags. (Allows HTML)
788 * @param bool $sH If set, <h3> is used, otherwise <h4>
789 * @param string $addAttrib Additional attributes to h-tag, eg. ' class=""'
790 * @return string HTML content
791 */
792 public function sectionHeader($label, $sH = false, $addAttrib = '')
793 {
794 $tag = $sH ? 'h2' : 'h3';
795 if ($addAttrib && $addAttrib[0] !== ' ') {
796 $addAttrib = ' ' . $addAttrib;
797 }
798 $str = '
799
800 <!-- Section header -->
801 <' . $tag . $addAttrib . '>' . $label . '</' . $tag . '>
802 ';
803 return $this->sectionBegin() . $str;
804 }
805
806 /**
807 * Begins an output section.
808 * Returns the <div>-begin tag AND sets the ->sectionFlag TRUE (if the ->sectionFlag is not already set!)
809 * You can call this function even if a section is already begun since the function will only return something if the sectionFlag is not already set!
810 *
811 * @return string HTML content
812 */
813 public function sectionBegin()
814 {
815 if (!$this->sectionFlag) {
816 $this->sectionFlag = 1;
817 $str = '
818
819 <!-- ***********************
820 Begin output section.
821 *********************** -->
822 <div>
823 ';
824 return $str;
825 } else {
826 return '';
827 }
828 }
829
830 /**
831 * Ends and output section
832 * Returns the </div>-end tag AND clears the ->sectionFlag (but does so only IF the sectionFlag is set - that is a section is 'open')
833 * See sectionBegin() also.
834 *
835 * @return string HTML content
836 */
837 public function sectionEnd()
838 {
839 if ($this->sectionFlag) {
840 $this->sectionFlag = 0;
841 return '
842 </div>
843 <!-- *********************
844 End output section.
845 ********************* -->
846 ';
847 } else {
848 return '';
849 }
850 }
851
852 /**
853 * Creates the bodyTag.
854 * You can add to the bodyTag by $this->bodyTagAdditions
855 *
856 * @return string HTML body tag
857 */
858 public function docBodyTagBegin()
859 {
860 return '<body ' . trim($this->bodyTagAdditions . ($this->bodyTagId ? ' id="' . $this->bodyTagId . '"' : '')) . '>';
861 }
862
863 /**
864 * Outputting document style
865 *
866 * @return string HTML style section/link tags
867 */
868 public function docStyle()
869 {
870 // Implode it all:
871 $inDocStyles = implode(LF, $this->inDocStylesArray);
872
873 // Reset styles so they won't be added again in insertStylesAndJS()
874 $this->inDocStylesArray = array();
875
876 if ($this->styleSheetFile) {
877 $this->pageRenderer->addCssFile($this->styleSheetFile);
878 }
879 if ($this->styleSheetFile2) {
880 $this->pageRenderer->addCssFile($this->styleSheetFile2);
881 }
882
883 if ($inDocStyles !== '') {
884 $this->pageRenderer->addCssInlineBlock('inDocStyles', $inDocStyles . LF . '/*###POSTCSSMARKER###*/');
885 }
886
887 if ($this->styleSheetFile_post) {
888 $this->pageRenderer->addCssFile($this->styleSheetFile_post);
889 }
890 }
891
892 /**
893 * Insert additional style sheet link
894 *
895 * @param string $key some key identifying the style sheet
896 * @param string $href uri to the style sheet file
897 * @param string $title value for the title attribute of the link element
898 * @param string $relation value for the rel attribute of the link element
899 * @return void
900 */
901 public function addStyleSheet($key, $href, $title = '', $relation = 'stylesheet')
902 {
903 $this->pageRenderer->addCssFile($href, $relation, 'screen', $title);
904 }
905
906 /**
907 * Add all *.css files of the directory $path to the stylesheets
908 *
909 * @param string $path directory to add
910 * @return void
911 */
912 public function addStyleSheetDirectory($path)
913 {
914 // Calculation needed, when TYPO3 source is used via a symlink
915 // absolute path to the stylesheets
916 $filePath = dirname(GeneralUtility::getIndpEnv('SCRIPT_FILENAME')) . '/' . $GLOBALS['BACK_PATH'] . $path;
917 // Clean the path
918 $resolvedPath = GeneralUtility::resolveBackPath($filePath);
919 // Read all files in directory and sort them alphabetically
920 $files = GeneralUtility::getFilesInDir($resolvedPath, 'css', false, 1);
921 foreach ($files as $file) {
922 $this->pageRenderer->addCssFile($GLOBALS['BACK_PATH'] . $path . $file, 'stylesheet', 'all');
923 }
924 }
925
926 /**
927 * Insert post rendering document style into already rendered content
928 * This is needed for extobjbase
929 *
930 * @param string $content style-content to insert.
931 * @return string content with inserted styles
932 */
933 public function insertStylesAndJS($content)
934 {
935 $styles = LF . implode(LF, $this->inDocStylesArray);
936 $content = str_replace('/*###POSTCSSMARKER###*/', $styles, $content);
937
938 // Insert accumulated JS
939 $jscode = $this->JScode . LF . $this->wrapScriptTags(implode(LF, $this->JScodeArray));
940 $content = str_replace('<!--###POSTJSMARKER###-->', $jscode, $content);
941 return $content;
942 }
943
944 /**
945 * Returns an array of all stylesheet directories belonging to core and skins
946 *
947 * @return array Stylesheet directories
948 */
949 public function getSkinStylesheetDirectories()
950 {
951 $stylesheetDirectories = array();
952 // Add default core stylesheets
953 foreach ($this->stylesheetsCore as $stylesheetDir) {
954 $stylesheetDirectories[] = $stylesheetDir;
955 }
956 // Stylesheets from skins
957 // merge default css directories ($this->stylesheetsSkin) with additional ones and include them
958 if (is_array($GLOBALS['TBE_STYLES']['skins'])) {
959 // loop over all registered skins
960 foreach ($GLOBALS['TBE_STYLES']['skins'] as $skinExtKey => $skin) {
961 $skinStylesheetDirs = $this->stylesheetsSkins;
962 // Skins can add custom stylesheetDirectories using
963 // $GLOBALS['TBE_STYLES']['skins'][$_EXTKEY]['stylesheetDirectories']
964 if (is_array($skin['stylesheetDirectories'])) {
965 $skinStylesheetDirs = array_merge($skinStylesheetDirs, $skin['stylesheetDirectories']);
966 }
967 // Add all registered directories
968 foreach ($skinStylesheetDirs as $stylesheetDir) {
969 // for EXT:myskin/stylesheets/ syntax
970 if (substr($stylesheetDir, 0, 4) === 'EXT:') {
971 list($extKey, $path) = explode('/', substr($stylesheetDir, 4), 2);
972 if (!empty($extKey) && ExtensionManagementUtility::isLoaded($extKey) && !empty($path)) {
973 $stylesheetDirectories[] = ExtensionManagementUtility::extRelPath($extKey) . $path;
974 }
975 } else {
976 // For relative paths
977 $stylesheetDirectories[] = ExtensionManagementUtility::extRelPath($skinExtKey) . $stylesheetDir;
978 }
979 }
980 }
981 }
982 return $stylesheetDirectories;
983 }
984
985 /**
986 * Returns generator meta tag
987 *
988 * @return string <meta> tag with name "generator
989 */
990 public function generator()
991 {
992 $str = 'TYPO3 CMS, ' . TYPO3_URL_GENERAL . ', &#169; Kasper Sk&#229;rh&#248;j ' . TYPO3_copyright_year . ', extensions are copyright of their respective owners.';
993 return '<meta name="generator" content="' . $str . '" />';
994 }
995
996 /**
997 * Returns X-UA-Compatible meta tag
998 *
999 * @param string $content Content of the compatible tag (default: IE-8)
1000 * @return string <meta http-equiv="X-UA-Compatible" content="???" />
1001 */
1002 public function xUaCompatible($content = 'IE=8')
1003 {
1004 return '<meta http-equiv="X-UA-Compatible" content="' . $content . '" />';
1005 }
1006
1007 /*****************************************
1008 *
1009 * OTHER ELEMENTS
1010 * Tables, buttons, formatting dimmed/red strings
1011 *
1012 ******************************************/
1013 /**
1014 * Returns an image-tag with an 18x16 icon of the following types:
1015 *
1016 * $type:
1017 * -1: OK icon (Check-mark)
1018 * 1: Notice (Speach-bubble)
1019 * 2: Warning (Yellow triangle)
1020 * 3: Fatal error (Red stop sign)
1021 *
1022 * @param int $type See description
1023 * @param string $styleAttribValue Value for style attribute
1024 * @return string HTML image tag (if applicable)
1025 */
1026 public function icons($type, $styleAttribValue = '')
1027 {
1028 switch ($type) {
1029 case self::STATUS_ICON_ERROR:
1030 $icon = 'status-dialog-error';
1031 break;
1032 case self::STATUS_ICON_WARNING:
1033 $icon = 'status-dialog-warning';
1034 break;
1035 case self::STATUS_ICON_NOTIFICATION:
1036 $icon = 'status-dialog-notification';
1037 break;
1038 case self::STATUS_ICON_OK:
1039 $icon = 'status-dialog-ok';
1040 break;
1041 default:
1042 // Do nothing
1043 }
1044 if ($icon) {
1045 return $this->iconFactory->getIcon($icon, Icon::SIZE_SMALL)->render();
1046 }
1047 }
1048
1049 /**
1050 * Returns an <input> button with the $onClick action and $label
1051 *
1052 * @param string $onClick The value of the onclick attribute of the input tag (submit type)
1053 * @param string $label The label for the button (which will be htmlspecialchar'ed)
1054 * @return string A <input> tag of the type "submit
1055 */
1056 public function t3Button($onClick, $label)
1057 {
1058 $button = '<input class="btn btn-default" type="submit" onclick="' . htmlspecialchars($onClick) . '; return false;" value="' . htmlspecialchars($label) . '" />';
1059 return $button;
1060 }
1061
1062 /**
1063 * Returns string wrapped in CDATA "tags" for XML / XHTML (wrap content of <script> and <style> sections in those!)
1064 *
1065 * @param string $string Input string
1066 * @return string Output string
1067 */
1068 public function wrapInCData($string)
1069 {
1070 $string = '/*<![CDATA[*/' . $string . '/*]]>*/';
1071 return $string;
1072 }
1073
1074 /**
1075 * Wraps the input string in script tags.
1076 * Automatic re-identing of the JS code is done by using the first line as ident reference.
1077 * This is nice for identing JS code with PHP code on the same level.
1078 *
1079 * @param string $string Input string
1080 * @param bool $linebreak Wrap script element in linebreaks? Default is TRUE.
1081 * @return string Output string
1082 */
1083 public function wrapScriptTags($string, $linebreak = true)
1084 {
1085 if (trim($string)) {
1086 // <script wrapped in nl?
1087 $cr = $linebreak ? LF : '';
1088 // Remove nl from the beginning
1089 $string = ltrim($string, LF);
1090 // Re-ident to one tab using the first line as reference
1091 if ($string[0] === TAB) {
1092 $string = TAB . ltrim($string, TAB);
1093 }
1094 $string = $cr . '<script type="text/javascript">
1095 /*<![CDATA[*/
1096 ' . $string . '
1097 /*]]>*/
1098 </script>' . $cr;
1099 }
1100 return trim($string);
1101 }
1102
1103 // These vars defines the layout for the table produced by the table() function.
1104 // You can override these values from outside if you like.
1105 public $tableLayout = array(
1106 'defRow' => array(
1107 'defCol' => array('<td valign="top">', '</td>')
1108 )
1109 );
1110
1111 public $table_TR = '<tr>';
1112
1113 public $table_TABLE = '<table border="0" cellspacing="0" cellpadding="0" class="typo3-dblist" id="typo3-tmpltable">';
1114
1115 /**
1116 * Returns a one-row/two-celled table with $content and $menu side by side.
1117 * The table is a 100% width table and each cell is aligned left / right
1118 *
1119 * @param string $content Content cell content (left)
1120 * @param string $menu Menu cell content (right)
1121 * @return string HTML output
1122 */
1123 public function funcMenu($content, $menu)
1124 {
1125 return '
1126 <table border="0" cellpadding="0" cellspacing="0" width="100%" id="typo3-funcmenu">
1127 <tr>
1128 <td valign="top" nowrap="nowrap">' . $content . '</td>
1129 <td valign="top" align="right" nowrap="nowrap">' . $menu . '</td>
1130 </tr>
1131 </table>';
1132 }
1133
1134 /**
1135 * Includes a javascript library that exists in the core /typo3/ directory
1136 *
1137 * @param string $lib: Library name. Call it with the full path like "sysext/core/Resources/Public/JavaScript/QueryGenerator.js" to load it
1138 * @return void
1139 */
1140 public function loadJavascriptLib($lib)
1141 {
1142 // @todo: maybe we can remove this one as well
1143 $this->pageRenderer->addJsFile($lib);
1144 }
1145
1146 /**
1147 * Includes the necessary Javascript function for the clickmenu (context sensitive menus) in the document
1148 *
1149 * @return void
1150 */
1151 public function getContextMenuCode()
1152 {
1153 $this->pageRenderer->loadJquery();
1154 $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/ClickMenu');
1155 }
1156
1157 /**
1158 * Includes the necessary javascript file for use on pages which have the
1159 * drag and drop functionality (legacy folder tree)
1160 *
1161 * @param string $table indicator of which table the drag and drop function should work on (pages or folders)
1162 * @param string $additionalJavaScriptCode adds more code to the additional javascript code
1163 * @return void
1164 */
1165 public function getDragDropCode($table, $additionalJavaScriptCode = '')
1166 {
1167 $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/LegacyTree', 'function() {
1168 DragDrop.table = "' . $table . '";
1169 ' . $additionalJavaScriptCode . '
1170 }');
1171 }
1172
1173 /**
1174 * Creates a tab menu from an array definition
1175 *
1176 * Returns a tab menu for a module
1177 * Requires the JS function jumpToUrl() to be available
1178 *
1179 * @param mixed $mainParams is the "&id=" parameter value to be sent to the module, but it can be also a parameter array which will be passed instead of the &id=...
1180 * @param string $elementName it the form elements name, probably something like "SET[...]
1181 * @param string $currentValue is the value to be selected currently.
1182 * @param array $menuItems is an array with the menu items for the selector box
1183 * @param string $script is the script to send the &id to, if empty it's automatically found
1184 * @param string $addparams is additional parameters to pass to the script.
1185 * @return string HTML code for tab menu
1186 */
1187 public function getTabMenu($mainParams, $elementName, $currentValue, $menuItems, $script = '', $addparams = '')
1188 {
1189 $content = '';
1190 if (is_array($menuItems)) {
1191 if (!is_array($mainParams)) {
1192 $mainParams = array('id' => $mainParams);
1193 }
1194 $mainParams = GeneralUtility::implodeArrayForUrl('', $mainParams);
1195 if (!$script) {
1196 $script = basename(PATH_thisScript);
1197 }
1198 $menuDef = array();
1199 foreach ($menuItems as $value => $label) {
1200 $menuDef[$value]['isActive'] = (string)$currentValue === (string)$value;
1201 $menuDef[$value]['label'] = htmlspecialchars($label, ENT_COMPAT, 'UTF-8', false);
1202 $menuDef[$value]['url'] = $script . '?' . $mainParams . $addparams . '&' . $elementName . '=' . $value;
1203 }
1204 $content = $this->getTabMenuRaw($menuDef);
1205 }
1206 return $content;
1207 }
1208
1209 /**
1210 * Creates the HTML content for the tab menu
1211 *
1212 * @param array $menuItems Menu items for tabs
1213 * @return string Table HTML
1214 * @access private
1215 */
1216 public function getTabMenuRaw($menuItems)
1217 {
1218 if (!is_array($menuItems)) {
1219 return '';
1220 }
1221
1222 $options = '';
1223 foreach ($menuItems as $id => $def) {
1224 $class = $def['isActive'] ? 'active' : '';
1225 $label = $def['label'];
1226 $url = htmlspecialchars($def['url']);
1227 $params = $def['addParams'];
1228
1229 $options .= '<li class="' . $class . '">' .
1230 '<a href="' . $url . '" ' . $params . '>' . $label . '</a>' .
1231 '</li>';
1232 }
1233
1234 return '<ul class="nav nav-tabs" role="tablist">' .
1235 $options .
1236 '</ul>';
1237 }
1238
1239 /**
1240 * Creates the version selector for the page id inputted.
1241 * Requires the core version management extension, "version" to be loaded.
1242 *
1243 * @param int $id Page id to create selector for.
1244 * @param bool $noAction If set, there will be no button for swapping page.
1245 * @return string
1246 */
1247 public function getVersionSelector($id, $noAction = false)
1248 {
1249 if (
1250 ExtensionManagementUtility::isLoaded('version') &&
1251 !ExtensionManagementUtility::isLoaded('workspaces')
1252 ) {
1253 $versionGuiObj = GeneralUtility::makeInstance(\TYPO3\CMS\Version\View\VersionView::class);
1254 return $versionGuiObj->getVersionSelector($id, $noAction);
1255 }
1256 }
1257
1258 /**
1259 * Function to load a HTML template file with markers.
1260 * When calling from own extension, use syntax getHtmlTemplate('EXT:extkey/template.html')
1261 *
1262 * @param string $filename tmpl name, usually in the typo3/template/ directory
1263 * @return string HTML of template
1264 */
1265 public function getHtmlTemplate($filename)
1266 {
1267 // setting the name of the original HTML template
1268 $this->moduleTemplateFilename = $filename;
1269 if ($GLOBALS['TBE_STYLES']['htmlTemplates'][$filename]) {
1270 $filename = $GLOBALS['TBE_STYLES']['htmlTemplates'][$filename];
1271 }
1272 if (GeneralUtility::isFirstPartOfStr($filename, 'EXT:')) {
1273 $filename = GeneralUtility::getFileAbsFileName($filename, true, true);
1274 } elseif (!GeneralUtility::isAbsPath($filename)) {
1275 $filename = GeneralUtility::resolveBackPath($filename);
1276 } elseif (!GeneralUtility::isAllowedAbsPath($filename)) {
1277 $filename = '';
1278 }
1279 $htmlTemplate = '';
1280 if ($filename !== '') {
1281 $htmlTemplate = GeneralUtility::getUrl($filename);
1282 }
1283 return $htmlTemplate;
1284 }
1285
1286 /**
1287 * Define the template for the module
1288 *
1289 * @param string $filename filename
1290 * @return void
1291 */
1292 public function setModuleTemplate($filename)
1293 {
1294 $this->moduleTemplate = $this->getHtmlTemplate($filename);
1295 }
1296
1297 /**
1298 * Put together the various elements for the module <body> using a static HTML
1299 * template
1300 *
1301 * @param array $pageRecord Record of the current page, used for page path and info
1302 * @param array $buttons HTML for all buttons
1303 * @param array $markerArray HTML for all other markers
1304 * @param array $subpartArray HTML for the subparts
1305 * @return string Composite HTML
1306 */
1307 public function moduleBody($pageRecord = array(), $buttons = array(), $markerArray = array(), $subpartArray = array())
1308 {
1309 // Get the HTML template for the module
1310 $moduleBody = $this->templateService->getSubpart($this->moduleTemplate, '###FULLDOC###');
1311 // Add CSS
1312 $this->inDocStylesArray[] = 'html { overflow: hidden; }';
1313 // Get the page path for the docheader
1314 $markerArray['PAGEPATH'] = $this->getPagePath($pageRecord);
1315 // Get the page info for the docheader
1316 $markerArray['PAGEINFO'] = $this->getPageInfo($pageRecord);
1317 // Get all the buttons for the docheader
1318 $docHeaderButtons = $this->getDocHeaderButtons($buttons);
1319 // Merge docheader buttons with the marker array
1320 $markerArray = array_merge($markerArray, $docHeaderButtons);
1321 // replacing subparts
1322 foreach ($subpartArray as $marker => $content) {
1323 $moduleBody = $this->templateService->substituteSubpart($moduleBody, $marker, $content);
1324 }
1325 // adding flash messages
1326 if ($this->showFlashMessages) {
1327 $flashMessages = $this->getFlashMessages();
1328 if (!empty($flashMessages)) {
1329 $markerArray['FLASHMESSAGES'] = $flashMessages;
1330 // If there is no dedicated marker for the messages present
1331 // then force them to appear before the content
1332 if (strpos($moduleBody, '###FLASHMESSAGES###') === false) {
1333 $moduleBody = str_replace('###CONTENT###', '###FLASHMESSAGES######CONTENT###', $moduleBody);
1334 }
1335 }
1336 }
1337 // Hook for adding more markers/content to the page, like the version selector
1338 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['moduleBodyPostProcess'])) {
1339 $params = array(
1340 'moduleTemplateFilename' => &$this->moduleTemplateFilename,
1341 'moduleTemplate' => &$this->moduleTemplate,
1342 'moduleBody' => &$moduleBody,
1343 'markers' => &$markerArray,
1344 'parentObject' => &$this
1345 );
1346 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['moduleBodyPostProcess'] as $funcRef) {
1347 GeneralUtility::callUserFunction($funcRef, $params, $this);
1348 }
1349 }
1350 // Replacing all markers with the finished markers and return the HTML content
1351 return $this->templateService->substituteMarkerArray($moduleBody, $markerArray, '###|###');
1352 }
1353
1354 /**
1355 * Get the default rendered FlashMessages from queue
1356 *
1357 * @return string
1358 */
1359 public function getFlashMessages()
1360 {
1361 /** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
1362 $flashMessageService = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessageService::class);
1363 /** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
1364 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
1365 return $defaultFlashMessageQueue->renderFlashMessages();
1366 }
1367
1368 /**
1369 * Renders the FlashMessages from queue and returns them as AJAX.
1370 *
1371 * @param ServerRequestInterface $request
1372 * @param ResponseInterface $response
1373 * @return ResponseInterface
1374 */
1375 public function renderQueuedFlashMessages(ServerRequestInterface $request, ResponseInterface $response)
1376 {
1377 /** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
1378 $flashMessageService = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessageService::class);
1379 /** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
1380 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
1381 $flashMessages = $defaultFlashMessageQueue->getAllMessagesAndFlush();
1382
1383 $messages = [];
1384 foreach ($flashMessages as $flashMessage) {
1385 $messages[] = [
1386 'title' => $flashMessage->getTitle(),
1387 'message' => $flashMessage->getMessage(),
1388 'severity' => $flashMessage->getSeverity()
1389 ];
1390 }
1391
1392 $response->getBody()->write(json_encode($messages));
1393 return $response;
1394 }
1395
1396 /**
1397 * Fill the button lists with the defined HTML
1398 *
1399 * @param array $buttons HTML for all buttons
1400 * @return array Containing HTML for both buttonlists
1401 */
1402 protected function getDocHeaderButtons($buttons)
1403 {
1404 $markers = array();
1405 // Fill buttons for left and right float
1406 $floats = array('left', 'right');
1407 foreach ($floats as $key) {
1408 // Get the template for each float
1409 $buttonTemplate = $this->templateService->getSubpart($this->moduleTemplate, '###BUTTON_GROUPS_' . strtoupper($key) . '###');
1410 // Fill the button markers in this float
1411 $buttonTemplate = $this->templateService->substituteMarkerArray($buttonTemplate, $buttons, '###|###', true);
1412 // getting the wrap for each group
1413 $buttonWrap = $this->templateService->getSubpart($this->moduleTemplate, '###BUTTON_GROUP_WRAP###');
1414 // looping through the groups (max 6) and remove the empty groups
1415 for ($groupNumber = 1; $groupNumber < 6; $groupNumber++) {
1416 $buttonMarker = '###BUTTON_GROUP' . $groupNumber . '###';
1417 $buttonGroup = $this->templateService->getSubpart($buttonTemplate, $buttonMarker);
1418 if (trim($buttonGroup)) {
1419 if ($buttonWrap) {
1420 $buttonGroup = $this->templateService->substituteMarker($buttonWrap, '###BUTTONS###', $buttonGroup);
1421 }
1422 $buttonTemplate = $this->templateService->substituteSubpart($buttonTemplate, $buttonMarker, trim($buttonGroup));
1423 }
1424 }
1425 // Replace the marker with the template and remove all line breaks (for IE compat)
1426 $markers['BUTTONLIST_' . strtoupper($key)] = str_replace(LF, '', $buttonTemplate);
1427 }
1428 // Hook for manipulating docHeaderButtons
1429 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['docHeaderButtonsHook'])) {
1430 $params = array(
1431 'buttons' => $buttons,
1432 'markers' => &$markers,
1433 'pObj' => &$this
1434 );
1435 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['docHeaderButtonsHook'] as $funcRef) {
1436 GeneralUtility::callUserFunction($funcRef, $params, $this);
1437 }
1438 }
1439 return $markers;
1440 }
1441
1442 /**
1443 * Generate the page path for docheader
1444 *
1445 * @param array $pageRecord Current page
1446 * @return string Page path
1447 */
1448 protected function getPagePath($pageRecord)
1449 {
1450 // Is this a real page
1451 if (is_array($pageRecord) && $pageRecord['uid']) {
1452 $title = substr($pageRecord['_thePathFull'], 0, -1);
1453 // Remove current page title
1454 $pos = strrpos($title, $pageRecord['title']);
1455 if ($pos !== false) {
1456 $title = substr($title, 0, $pos);
1457 }
1458 } else {
1459 $title = '';
1460 }
1461 // Setting the path of the page
1462 $pagePath = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.path', true) . ': <span class="typo3-docheader-pagePath">';
1463 // crop the title to title limit (or 50, if not defined)
1464 $cropLength = empty($GLOBALS['BE_USER']->uc['titleLen']) ? 50 : $GLOBALS['BE_USER']->uc['titleLen'];
1465 $croppedTitle = GeneralUtility::fixed_lgd_cs($title, -$cropLength);
1466 if ($croppedTitle !== $title) {
1467 $pagePath .= '<abbr title="' . htmlspecialchars($title) . '">' . htmlspecialchars($croppedTitle) . '</abbr>';
1468 } else {
1469 $pagePath .= htmlspecialchars($title);
1470 }
1471 $pagePath .= '</span>';
1472 return $pagePath;
1473 }
1474
1475 /**
1476 * Setting page icon with clickmenu + uid for docheader
1477 *
1478 * @param array $pageRecord Current page
1479 * @return string Page info
1480 */
1481 protected function getPageInfo($pageRecord)
1482 {
1483 // Add icon with clickmenu, etc:
1484 // If there IS a real page
1485 if (is_array($pageRecord) && $pageRecord['uid']) {
1486 $alttext = BackendUtility::getRecordIconAltText($pageRecord, 'pages');
1487 $iconImg = '<span title="' . htmlspecialchars($alttext) . '">' . $this->iconFactory->getIconForRecord('pages', $pageRecord, Icon::SIZE_SMALL)->render() . '</span>';
1488 // Make Icon:
1489 $theIcon = BackendUtility::wrapClickMenuOnIcon($iconImg, 'pages', $pageRecord['uid']);
1490 $uid = $pageRecord['uid'];
1491 $title = BackendUtility::getRecordTitle('pages', $pageRecord);
1492 } else {
1493 // On root-level of page tree
1494 // Make Icon
1495 $iconImg = '<span title="' . htmlspecialchars($GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename']) . '">' . $this->iconFactory->getIcon('apps-pagetree-root', Icon::SIZE_SMALL)->render() . '</span>';
1496 if ($GLOBALS['BE_USER']->user['admin']) {
1497 $theIcon = BackendUtility::wrapClickMenuOnIcon($iconImg, 'pages', 0);
1498 } else {
1499 $theIcon = $iconImg;
1500 }
1501 $uid = '0';
1502 $title = $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'];
1503 }
1504 // Setting icon with clickmenu + uid
1505 $pageInfo = $theIcon . '<strong>' . htmlspecialchars($title) . '&nbsp;[' . $uid . ']</strong>';
1506 return $pageInfo;
1507 }
1508
1509 /**
1510 * Retrieves configured favicon for backend (with fallback)
1511 *
1512 * @return string
1513 */
1514 protected function getBackendFavicon()
1515 {
1516 return $GLOBALS['TBE_STYLES']['favicon'] ?: 'sysext/backend/Resources/Public/Icons/favicon.ico';
1517 }
1518 }