713a0b5b2cb1a74e74df466b4ab482b47585ad2e
[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\Log\LoggerAwareInterface;
18 use Psr\Log\LoggerAwareTrait;
19 use TYPO3\CMS\Backend\Backend\Shortcut\ShortcutRepository;
20 use TYPO3\CMS\Backend\Routing\UriBuilder;
21 use TYPO3\CMS\Backend\Utility\BackendUtility;
22 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
23 use TYPO3\CMS\Core\Configuration\ExtensionConfiguration;
24 use TYPO3\CMS\Core\Imaging\Icon;
25 use TYPO3\CMS\Core\Imaging\IconFactory;
26 use TYPO3\CMS\Core\Page\PageRenderer;
27 use TYPO3\CMS\Core\Service\MarkerBasedTemplateService;
28 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
29 use TYPO3\CMS\Core\Utility\GeneralUtility;
30 use TYPO3\CMS\Core\Utility\PathUtility;
31
32 /**
33 * TYPO3 Backend Template Class
34 *
35 * This class contains functions for starting and ending the HTML of backend modules
36 * It also contains methods for outputting sections of content.
37 * Further there are functions for making icons, links, setting form-field widths etc.
38 * Color scheme and stylesheet definitions are also available here.
39 * Finally this file includes the language class for TYPO3's backend.
40 *
41 * After this file $LANG and $TBE_TEMPLATE are global variables / instances of their respective classes.
42 *
43 * Please refer to Inside TYPO3 for a discussion of how to use this API.
44 */
45 class DocumentTemplate implements LoggerAwareInterface
46 {
47 use LoggerAwareTrait;
48
49 // Vars you typically might want to/should set from outside after making instance of this class:
50 /**
51 * This can be set to the HTML-code for a formtag.
52 * Useful when you need a form to span the whole page; Inserted exactly after the body-tag.
53 *
54 * @var string
55 */
56 public $form = '';
57
58 /**
59 * Additional header code (eg. a JavaScript section) could be accommulated in this var. It will be directly outputted in the header.
60 *
61 * @var string
62 */
63 public $JScode = '';
64
65 /**
66 * 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.
67 *
68 * @var array
69 */
70 public $JScodeArray = ['jumpToUrl' => '
71 function jumpToUrl(URL) {
72 window.location.href = URL;
73 return false;
74 }
75 '];
76
77 /**
78 * 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.
79 *
80 * @var string
81 */
82 public $postCode = '';
83
84 /**
85 * HTML template with markers for module
86 *
87 * @var string
88 */
89 public $moduleTemplate = '';
90
91 /**
92 * The base file (not overlaid by TBE_STYLES) for the current module, useful for hooks when finding out which modules is rendered currently
93 *
94 * @var string
95 */
96 protected $moduleTemplateFilename = '';
97
98 /**
99 * Script ID
100 *
101 * @var string
102 */
103 public $scriptID = '';
104
105 /**
106 * Id which can be set for the body tag. Default value is based on script ID
107 *
108 * @var string
109 */
110 public $bodyTagId = '';
111
112 /**
113 * You can add additional attributes to the body-tag through this variable.
114 *
115 * @var string
116 */
117 public $bodyTagAdditions = '';
118
119 /**
120 * Additional CSS styles which will be added to the <style> section in the header
121 * used as array with associative keys to prevent double inclusion of CSS code
122 *
123 * @var array
124 */
125 public $inDocStylesArray = [];
126
127 /**
128 * Filename of stylesheet
129 *
130 * @var string
131 */
132 public $styleSheetFile = '';
133
134 /**
135 * Filename of stylesheet #2 - linked to right after the $this->styleSheetFile script
136 *
137 * @var string
138 */
139 public $styleSheetFile2 = '';
140
141 /**
142 * Filename of a post-stylesheet - included right after all inline styles.
143 *
144 * @var string
145 */
146 public $styleSheetFile_post = '';
147
148 /**
149 * Whether to use the X-UA-Compatible meta tag
150 *
151 * @var bool
152 */
153 protected $useCompatibilityTag = true;
154
155 /**
156 * X-Ua-Compatible version output in meta tag
157 *
158 * @var string
159 */
160 protected $xUaCompatibilityVersion = 'IE=edge';
161
162 // Skinning
163 /**
164 * Include these CSS directories from skins by default
165 *
166 * @var array
167 */
168 protected $stylesheetsSkins = [
169 'structure' => 'Resources/Public/Css/structure/',
170 'visual' => 'Resources/Public/Css/visual/'
171 ];
172
173 /**
174 * JavaScript files loaded for every page in the Backend
175 *
176 * @var array
177 */
178 protected $jsFiles = [];
179
180 /**
181 * JavaScript files loaded for every page in the Backend, but explicitly excluded from concatenation (useful for libraries etc.)
182 *
183 * @var array
184 */
185 protected $jsFilesNoConcatenation = [];
186
187 /**
188 * Indicates if a <div>-output section is open
189 *
190 * @var int
191 * @internal will be removed in TYPO3 v9
192 */
193 public $sectionFlag = 0;
194
195 /**
196 * (Default) Class for wrapping <DIV>-tag of page. Is set in class extensions.
197 *
198 * @var string
199 */
200 public $divClass = '';
201
202 /**
203 * @var string
204 */
205 public $pageHeaderBlock = '';
206
207 /**
208 * @var string
209 */
210 public $endOfPageJsBlock = '';
211
212 /**
213 * @var bool
214 */
215 public $hasDocheader = true;
216
217 /**
218 * @var PageRenderer
219 */
220 protected $pageRenderer;
221
222 /**
223 * Alternative template file
224 *
225 * @var string
226 */
227 protected $pageHeaderFooterTemplateFile = '';
228
229 /**
230 * Whether flashmessages should be rendered or not
231 *
232 * @var bool $showFlashMessages
233 */
234 public $showFlashMessages = true;
235
236 /**
237 * @var IconFactory
238 */
239 protected $iconFactory;
240
241 /**
242 * @var MarkerBasedTemplateService
243 */
244 protected $templateService;
245
246 /**
247 * Constructor
248 */
249 public function __construct()
250 {
251 // Initializes the page rendering object:
252 $this->initPageRenderer();
253
254 $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
255
256 // initialize Marker Support
257 $this->templateService = GeneralUtility::makeInstance(MarkerBasedTemplateService::class);
258
259 // Setting default scriptID, trim forward slash from route
260 $this->scriptID = ltrim(GeneralUtility::_GET('route'), '/');
261 $this->bodyTagId = preg_replace('/[^A-Za-z0-9-]/', '-', $this->scriptID);
262 // Individual configuration per script? If so, make a recursive merge of the arrays:
263 if (is_array($GLOBALS['TBE_STYLES']['scriptIDindex'][$this->scriptID] ?? false)) {
264 // Make copy
265 $ovr = $GLOBALS['TBE_STYLES']['scriptIDindex'][$this->scriptID];
266 // merge styles.
267 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($GLOBALS['TBE_STYLES'], $ovr);
268 // Have to unset - otherwise the second instantiation will do it again!
269 unset($GLOBALS['TBE_STYLES']['scriptIDindex'][$this->scriptID]);
270 }
271 // Main Stylesheets:
272 if (!empty($GLOBALS['TBE_STYLES']['stylesheet'])) {
273 $this->styleSheetFile = $GLOBALS['TBE_STYLES']['stylesheet'];
274 }
275 if (!empty($GLOBALS['TBE_STYLES']['stylesheet2'])) {
276 $this->styleSheetFile2 = $GLOBALS['TBE_STYLES']['stylesheet2'];
277 }
278 if (!empty($GLOBALS['TBE_STYLES']['styleSheetFile_post'])) {
279 $this->styleSheetFile_post = $GLOBALS['TBE_STYLES']['styleSheetFile_post'];
280 }
281 if (!empty($GLOBALS['TBE_STYLES']['inDocStyles_TBEstyle'])) {
282 $this->inDocStylesArray['TBEstyle'] = $GLOBALS['TBE_STYLES']['inDocStyles_TBEstyle'];
283 }
284 // include all stylesheets
285 foreach ($this->getSkinStylesheetDirectories() as $stylesheetDirectory) {
286 $this->addStyleSheetDirectory($stylesheetDirectory);
287 }
288 }
289
290 /**
291 * Initializes the page renderer object
292 */
293 protected function initPageRenderer()
294 {
295 if ($this->pageRenderer !== null) {
296 return;
297 }
298 $this->pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
299 $this->pageRenderer->setLanguage($GLOBALS['LANG']->lang);
300 $this->pageRenderer->enableConcatenateFiles();
301 $this->pageRenderer->enableCompressCss();
302 $this->pageRenderer->enableCompressJavascript();
303 // Add all JavaScript files defined in $this->jsFiles to the PageRenderer
304 foreach ($this->jsFilesNoConcatenation as $file) {
305 $this->pageRenderer->addJsFile(
306 $file,
307 'text/javascript',
308 true,
309 false,
310 '',
311 true
312 );
313 }
314 // Add all JavaScript files defined in $this->jsFiles to the PageRenderer
315 foreach ($this->jsFiles as $file) {
316 $this->pageRenderer->addJsFile($file);
317 }
318 if ((int)$GLOBALS['TYPO3_CONF_VARS']['BE']['debug'] === 1) {
319 $this->pageRenderer->enableDebugMode();
320 }
321 }
322
323 /*****************************************
324 *
325 * EVALUATION FUNCTIONS
326 * Various centralized processing
327 *
328 *****************************************/
329
330 /**
331 * Returns a linked shortcut-icon which will call the shortcut frame and set a shortcut there back to the calling page/module
332 *
333 * @param string $gvList Is the list of GET variables to store (if any)
334 * @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
335 * @param string $modName Module name string
336 * @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.
337 * @param string $classes
338 * @return string HTML content
339 */
340 public function makeShortcutIcon($gvList, $setList, $modName, $motherModName = '', $classes = '')
341 {
342 $gvList = 'route,' . $gvList;
343 $storeUrl = $this->makeShortcutUrl($gvList, $setList);
344 $pathInfo = parse_url(GeneralUtility::getIndpEnv('REQUEST_URI'));
345 // Fallback for alt_mod. We still pass in the old xMOD... stuff, but TBE_MODULES only knows about "record_edit".
346 // We still need to pass the xMOD name to createShortcut below, since this is used for icons.
347 $moduleName = $modName === 'xMOD_alt_doc.php' ? 'record_edit' : $modName;
348 // Add the module identifier automatically if typo3/index.php is used:
349 if (GeneralUtility::_GET('M') !== null) {
350 $storeUrl = '&M=' . $moduleName . $storeUrl;
351 }
352 if ((int)$motherModName === 1) {
353 $motherModule = 'top.currentModuleLoaded';
354 } elseif ($motherModName) {
355 $motherModule = GeneralUtility::quoteJSvalue($motherModName);
356 } else {
357 $motherModule = '\'\'';
358 }
359 $confirmationText = GeneralUtility::quoteJSvalue($GLOBALS['LANG']->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.makeBookmark'));
360
361 $shortcutUrl = $pathInfo['path'] . '?' . $storeUrl;
362 $shortcutRepository = GeneralUtility::makeInstance(ShortcutRepository::class);
363 $shortcutExist = $shortcutRepository->shortcutExists($shortcutUrl);
364
365 if ($shortcutExist) {
366 return '<a class="active ' . htmlspecialchars($classes) . '" title="">' .
367 $this->iconFactory->getIcon('actions-system-shortcut-active', Icon::SIZE_SMALL)->render() . '</a>';
368 }
369 $url = GeneralUtility::quoteJSvalue(rawurlencode($shortcutUrl));
370 $onClick = 'top.TYPO3.ShortcutMenu.createShortcut(' . GeneralUtility::quoteJSvalue(rawurlencode($modName)) .
371 ', ' . $url . ', ' . $confirmationText . ', ' . $motherModule . ', this);return false;';
372
373 return '<a href="#" class="' . htmlspecialchars($classes) . '" onclick="' . htmlspecialchars($onClick) . '" title="' .
374 htmlspecialchars($GLOBALS['LANG']->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.makeBookmark')) . '">' .
375 $this->iconFactory->getIcon('actions-system-shortcut-new', Icon::SIZE_SMALL)->render() . '</a>';
376 }
377
378 /**
379 * MAKE url for storing
380 * Internal func
381 *
382 * @param string $gvList Is the list of GET variables to store (if any)
383 * @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
384 * @return string
385 * @access private
386 * @see makeShortcutIcon()
387 */
388 public function makeShortcutUrl($gvList, $setList)
389 {
390 $GET = GeneralUtility::_GET();
391 $storeArray = array_merge(GeneralUtility::compileSelectedGetVarsFromArray($gvList, $GET), ['SET' => GeneralUtility::compileSelectedGetVarsFromArray($setList, (array)$GLOBALS['SOBE']->MOD_SETTINGS)]);
392 $storeUrl = GeneralUtility::implodeArrayForUrl('', $storeArray);
393 return $storeUrl;
394 }
395
396 /**
397 * Returns <input> attributes to set the width of an text-type input field.
398 * For client browsers with no CSS support the cols/size attribute is returned.
399 * For CSS compliant browsers (recommended) a ' style="width: ...px;"' is returned.
400 *
401 * @param int $size A relative number which multiplied with approx. 10 will lead to the width in pixels
402 * @param bool $textarea A flag you can set for textareas - DEPRECATED as there is no difference any more between the two
403 * @param string $styleOverride A string which will be returned as attribute-value for style="" instead of the calculated width (if CSS is enabled)
404 * @return string Tag attributes for an <input> tag (regarding width)
405 * @deprecated
406 */
407 public function formWidth($size = 48, $textarea = false, $styleOverride = '')
408 {
409 trigger_error('This method will be removed in TYPO3 10 - use responsive code or direct inline styles to format your input fields instead.', E_USER_DEPRECATED);
410 return ' style="' . ($styleOverride ?: 'width:' . ceil($size * 9.58) . 'px;') . '"';
411 }
412
413 /**
414 * Returns JavaScript variables setting the returnUrl and thisScript location for use by JavaScript on the page.
415 * Used in fx. db_list.php (Web>List)
416 *
417 * @param string $thisLocation URL to "this location" / current script
418 * @return string Urls are returned as JavaScript variables T3_RETURN_URL and T3_THIS_LOCATION
419 * @see typo3/db_list.php
420 */
421 public function redirectUrls($thisLocation = '')
422 {
423 $thisLocation = $thisLocation ? $thisLocation : GeneralUtility::linkThisScript([
424 'CB' => '',
425 'SET' => '',
426 'cmd' => '',
427 'popViewId' => ''
428 ]);
429 $out = '
430 var T3_RETURN_URL = ' . GeneralUtility::quoteJSvalue(str_replace('%20', '', rawurlencode(GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('returnUrl'))))) . ';
431 var T3_THIS_LOCATION = ' . GeneralUtility::quoteJSvalue(str_replace('%20', '', rawurlencode($thisLocation))) . '
432 ';
433 return $out;
434 }
435
436 /**
437 * Defines whether to use the X-UA-Compatible meta tag.
438 *
439 * @param bool $useCompatibilityTag Whether to use the tag
440 */
441 public function useCompatibilityTag($useCompatibilityTag = true)
442 {
443 $this->useCompatibilityTag = (bool)$useCompatibilityTag;
444 }
445
446 /*****************************************
447 *
448 * PAGE BUILDING FUNCTIONS.
449 * Use this to build the HTML of your backend modules
450 *
451 *****************************************/
452 /**
453 * Returns page start
454 * This includes the proper header with charset, title, meta tag and beginning body-tag.
455 *
456 * @param string $title HTML Page title for the header
457 * @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)
458 * @see endPage()
459 */
460 public function startPage($title)
461 {
462 // hook pre start page
463 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['preStartPageHook'] ?? [] as $hookFunction) {
464 $hookParameters = [
465 'title' => &$title
466 ];
467 GeneralUtility::callUserFunction($hookFunction, $hookParameters, $this);
468 }
469 // alternative template for Header and Footer
470 if ($this->pageHeaderFooterTemplateFile) {
471 $file = GeneralUtility::getFileAbsFileName($this->pageHeaderFooterTemplateFile);
472 if ($file) {
473 $this->pageRenderer->setTemplateFile($file);
474 }
475 }
476
477 // Disable rendering of XHTML tags
478 $this->pageRenderer->setRenderXhtml(false);
479
480 $languageCode = $this->pageRenderer->getLanguage() === 'default' ? 'en' : $this->pageRenderer->getLanguage();
481 $this->pageRenderer->setHtmlTag('<html lang="' . $languageCode . '">');
482
483 $headerStart = '<!DOCTYPE html>';
484 $this->pageRenderer->setXmlPrologAndDocType($headerStart);
485 $this->pageRenderer->setHeadTag('<head>' . LF . '<!-- TYPO3 Script ID: ' . htmlspecialchars($this->scriptID) . ' -->');
486 header('Content-Type:text/html;charset=utf-8');
487 $this->pageRenderer->setCharSet('utf-8');
488 $this->pageRenderer->setMetaTag('name', 'generator', $this->generator());
489 $this->pageRenderer->setMetaTag('name', 'robots', 'noindex,follow');
490 $this->pageRenderer->setMetaTag('name', 'viewport', 'width=device-width, initial-scale=1');
491 $this->pageRenderer->setFavIcon($this->getBackendFavicon());
492 if ($this->useCompatibilityTag) {
493 $this->pageRenderer->setMetaTag('http-equiv', 'X-UA-Compatible', $this->xUaCompatibilityVersion);
494 }
495 $this->pageRenderer->setTitle($title);
496 // add docstyles
497 $this->docStyle();
498 $this->pageRenderer->addHeaderData($this->JScode);
499 foreach ($this->JScodeArray as $name => $code) {
500 $this->pageRenderer->addJsInlineCode($name, $code, false);
501 }
502
503 // Load jquery and twbs JS libraries on every backend request
504 $this->pageRenderer->loadJquery();
505 // Note: please do not reference "bootstrap" outside of the TYPO3 Core (not in your own extensions)
506 // as this is preliminary as long as Twitter bootstrap does not support AMD modules
507 // this logic will be changed once Twitter bootstrap 4 is included
508 $this->pageRenderer->addJsFile('EXT:core/Resources/Public/JavaScript/Contrib/bootstrap/bootstrap.js');
509
510 // csh manual require js module & moduleUrl
511 if (TYPO3_MODE === 'BE' && $this->getBackendUser() && !empty($this->getBackendUser()->user)) {
512 $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
513 $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/ContextHelp');
514 $this->pageRenderer->addInlineSetting(
515 'ContextHelp',
516 'moduleUrl',
517 (string)$uriBuilder->buildUriFromRoute('help_cshmanual', ['action' => 'detail'])
518 );
519 }
520
521 // hook for additional headerData
522 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['preHeaderRenderHook'] ?? [] as $hookFunction) {
523 $hookParameters = [
524 'pageRenderer' => &$this->pageRenderer
525 ];
526 GeneralUtility::callUserFunction($hookFunction, $hookParameters, $this);
527 }
528 // Construct page header.
529 $str = $this->pageRenderer->render(PageRenderer::PART_HEADER);
530 $this->JScode = '';
531 $this->JScodeArray = [];
532 $this->endOfPageJsBlock = $this->pageRenderer->render(PageRenderer::PART_FOOTER);
533 $str .= $this->docBodyTagBegin() . ($this->divClass ? '
534
535 <!-- Wrapping DIV-section for whole page BEGIN -->
536 <div class="' . $this->divClass . '">
537 ' : '') . trim($this->form);
538 return $str;
539 }
540
541 /**
542 * Returns page end; This includes finishing form, div, body and html tags.
543 *
544 * @return string The HTML end of a page
545 * @see startPage()
546 */
547 public function endPage()
548 {
549 $str = $this->postCode . GeneralUtility::wrapJS(BackendUtility::getUpdateSignalCode()) . ($this->form ? '
550 </form>' : '');
551 // If something is in buffer like debug, put it to end of page
552 if (ob_get_contents()) {
553 $str .= ob_get_clean();
554 if (!headers_sent()) {
555 header('Content-Encoding: None');
556 }
557 }
558 $str .= ($this->divClass ? '
559
560 <!-- Wrapping DIV-section for whole page END -->
561 </div>' : '') . $this->endOfPageJsBlock;
562
563 // Logging: Can't find better place to put it:
564 $this->logger->debug('END of BACKEND session', ['_FLUSH' => true]);
565 return $str;
566 }
567
568 /**
569 * Shortcut for render the complete page of a module
570 *
571 * @param string $title page title
572 * @param string $content page content
573 * @return string complete page
574 */
575 public function render($title, $content)
576 {
577 $pageContent = $this->startPage($title);
578 $pageContent .= $content;
579 $pageContent .= $this->endPage();
580 return $this->insertStylesAndJS($pageContent);
581 }
582
583 /**
584 * Creates the bodyTag.
585 * You can add to the bodyTag by $this->bodyTagAdditions
586 *
587 * @return string HTML body tag
588 */
589 public function docBodyTagBegin()
590 {
591 return '<body ' . trim($this->bodyTagAdditions . ($this->bodyTagId ? ' id="' . $this->bodyTagId . '"' : '')) . '>';
592 }
593
594 /**
595 * Outputting document style
596 *
597 * @return string HTML style section/link tags
598 */
599 public function docStyle()
600 {
601 // Implode it all:
602 $inDocStyles = implode(LF, $this->inDocStylesArray);
603
604 // Reset styles so they won't be added again in insertStylesAndJS()
605 $this->inDocStylesArray = [];
606
607 if ($this->styleSheetFile) {
608 $this->pageRenderer->addCssFile($this->styleSheetFile);
609 }
610 if ($this->styleSheetFile2) {
611 $this->pageRenderer->addCssFile($this->styleSheetFile2);
612 }
613
614 if ($inDocStyles !== '') {
615 $this->pageRenderer->addCssInlineBlock('inDocStyles', $inDocStyles . LF . '/*###POSTCSSMARKER###*/');
616 }
617
618 if ($this->styleSheetFile_post) {
619 $this->pageRenderer->addCssFile($this->styleSheetFile_post);
620 }
621 }
622
623 /**
624 * Insert additional style sheet link
625 *
626 * @param string $key some key identifying the style sheet
627 * @param string $href uri to the style sheet file
628 * @param string $title value for the title attribute of the link element
629 * @param string $relation value for the rel attribute of the link element
630 */
631 public function addStyleSheet($key, $href, $title = '', $relation = 'stylesheet')
632 {
633 $this->pageRenderer->addCssFile($href, $relation, 'screen', $title);
634 }
635
636 /**
637 * Add all *.css files of the directory $path to the stylesheets
638 *
639 * @param string $path directory to add
640 */
641 public function addStyleSheetDirectory($path)
642 {
643 $path = GeneralUtility::getFileAbsFileName($path);
644 // Read all files in directory and sort them alphabetically
645 $cssFiles = GeneralUtility::getFilesInDir($path, 'css');
646 foreach ($cssFiles as $cssFile) {
647 $this->pageRenderer->addCssFile(PathUtility::getRelativePathTo($path) . $cssFile);
648 }
649 }
650
651 /**
652 * Insert post rendering document style into already rendered content
653 * This is needed for extobjbase
654 *
655 * @param string $content style-content to insert.
656 * @return string content with inserted styles
657 */
658 public function insertStylesAndJS($content)
659 {
660 $styles = LF . implode(LF, $this->inDocStylesArray);
661 $content = str_replace('/*###POSTCSSMARKER###*/', $styles, $content);
662
663 // Insert accumulated JS
664 $jscode = $this->JScode . LF . GeneralUtility::wrapJS(implode(LF, $this->JScodeArray));
665 $content = str_replace('<!--###POSTJSMARKER###-->', $jscode, $content);
666 return $content;
667 }
668
669 /**
670 * Returns an array of all stylesheet directories belonging to core and skins
671 *
672 * @return array Stylesheet directories
673 */
674 public function getSkinStylesheetDirectories()
675 {
676 $stylesheetDirectories = [];
677 // Stylesheets from skins
678 // merge default css directories ($this->stylesheetsSkin) with additional ones and include them
679 if (is_array($GLOBALS['TBE_STYLES']['skins'])) {
680 // loop over all registered skins
681 foreach ($GLOBALS['TBE_STYLES']['skins'] as $skinExtKey => $skin) {
682 $skinStylesheetDirs = $this->stylesheetsSkins;
683 // Skins can add custom stylesheetDirectories using
684 // $GLOBALS['TBE_STYLES']['skins'][$_EXTKEY]['stylesheetDirectories']
685 if (is_array($skin['stylesheetDirectories'])) {
686 $skinStylesheetDirs = array_merge($skinStylesheetDirs, $skin['stylesheetDirectories']);
687 }
688 // Add all registered directories
689 foreach ($skinStylesheetDirs as $stylesheetDir) {
690 // for EXT:myskin/stylesheets/ syntax
691 if (strpos($stylesheetDir, 'EXT:') === 0) {
692 list($extKey, $path) = explode('/', substr($stylesheetDir, 4), 2);
693 if (!empty($extKey) && ExtensionManagementUtility::isLoaded($extKey) && !empty($path)) {
694 $stylesheetDirectories[] = ExtensionManagementUtility::extPath($extKey) . $path;
695 }
696 } else {
697 // For relative paths
698 $stylesheetDirectories[] = ExtensionManagementUtility::extPath($skinExtKey) . $stylesheetDir;
699 }
700 }
701 }
702 }
703 return $stylesheetDirectories;
704 }
705
706 /**
707 * Returns generator meta tag
708 *
709 * @return string <meta> tag with name "generator
710 */
711 public function generator()
712 {
713 return 'TYPO3 CMS, ' . TYPO3_URL_GENERAL . ', &#169; Kasper Sk&#229;rh&#248;j ' . TYPO3_copyright_year . ', extensions are copyright of their respective owners.';
714 }
715
716 /**
717 * Returns X-UA-Compatible meta tag
718 * @deprecated
719 *
720 * @param string $content Content of the compatible tag (default: IE-8)
721 * @return string <meta http-equiv="X-UA-Compatible" content="???" />
722 */
723 public function xUaCompatible($content = 'IE=8')
724 {
725 trigger_error('Method DocumentTemplate->xUaCompatible is deprecated and will be removed with v10. Use pageRenderer->setMetaTag instead.', E_USER_DEPRECATED);
726 return '<meta http-equiv="X-UA-Compatible" content="' . $content . '" />';
727 }
728
729 /*****************************************
730 *
731 * OTHER ELEMENTS
732 * Tables, buttons, formatting dimmed/red strings
733 *
734 ******************************************/
735
736 /**
737 * Function to load a HTML template file with markers.
738 * When calling from own extension, use syntax getHtmlTemplate('EXT:extkey/template.html')
739 *
740 * @param string $filename tmpl name, usually in the typo3/template/ directory
741 * @return string HTML of template
742 */
743 public function getHtmlTemplate($filename)
744 {
745 // setting the name of the original HTML template
746 $this->moduleTemplateFilename = $filename;
747 if ($GLOBALS['TBE_STYLES']['htmlTemplates'][$filename]) {
748 $filename = $GLOBALS['TBE_STYLES']['htmlTemplates'][$filename];
749 }
750 $filename = GeneralUtility::getFileAbsFileName($filename);
751 return $filename !== '' ? file_get_contents($filename) : '';
752 }
753
754 /**
755 * Define the template for the module
756 *
757 * @param string $filename filename
758 */
759 public function setModuleTemplate($filename)
760 {
761 $this->moduleTemplate = $this->getHtmlTemplate($filename);
762 }
763
764 /**
765 * Put together the various elements for the module <body> using a static HTML
766 * template
767 *
768 * @param array $pageRecord Record of the current page, used for page path and info
769 * @param array $buttons HTML for all buttons
770 * @param array $markerArray HTML for all other markers
771 * @param array $subpartArray HTML for the subparts
772 * @return string Composite HTML
773 */
774 public function moduleBody($pageRecord = [], $buttons = [], $markerArray = [], $subpartArray = [])
775 {
776 // Get the HTML template for the module
777 $moduleBody = $this->templateService->getSubpart($this->moduleTemplate, '###FULLDOC###');
778 // Add CSS
779 $this->inDocStylesArray[] = 'html { overflow: hidden; }';
780 // Get the page path for the docheader
781 $markerArray['PAGEPATH'] = $this->getPagePath($pageRecord);
782 // Get the page info for the docheader
783 $markerArray['PAGEINFO'] = $this->getPageInfo($pageRecord);
784 // Get all the buttons for the docheader
785 $docHeaderButtons = $this->getDocHeaderButtons($buttons);
786 // Merge docheader buttons with the marker array
787 $markerArray = array_merge($markerArray, $docHeaderButtons);
788 // replacing subparts
789 foreach ($subpartArray as $marker => $content) {
790 $moduleBody = $this->templateService->substituteSubpart($moduleBody, $marker, $content);
791 }
792 // adding flash messages
793 if ($this->showFlashMessages) {
794 $flashMessages = $this->getFlashMessages();
795 if (!empty($flashMessages)) {
796 $markerArray['FLASHMESSAGES'] = $flashMessages;
797 // If there is no dedicated marker for the messages present
798 // then force them to appear before the content
799 if (strpos($moduleBody, '###FLASHMESSAGES###') === false) {
800 $moduleBody = str_replace('###CONTENT###', '###FLASHMESSAGES######CONTENT###', $moduleBody);
801 }
802 }
803 }
804 // Hook for adding more markers/content to the page, like the version selector
805 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['moduleBodyPostProcess'] ?? [] as $funcRef) {
806 $params = [
807 'moduleTemplateFilename' => &$this->moduleTemplateFilename,
808 'moduleTemplate' => &$this->moduleTemplate,
809 'moduleBody' => &$moduleBody,
810 'markers' => &$markerArray,
811 'parentObject' => &$this
812 ];
813 GeneralUtility::callUserFunction($funcRef, $params, $this);
814 }
815 // Replacing all markers with the finished markers and return the HTML content
816 return $this->templateService->substituteMarkerArray($moduleBody, $markerArray, '###|###');
817 }
818
819 /**
820 * Get the default rendered FlashMessages from queue
821 *
822 * @return string
823 */
824 public function getFlashMessages()
825 {
826 /** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
827 $flashMessageService = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessageService::class);
828 /** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
829 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
830 return $defaultFlashMessageQueue->renderFlashMessages();
831 }
832
833 /**
834 * Fill the button lists with the defined HTML
835 *
836 * @param array $buttons HTML for all buttons
837 * @return array Containing HTML for both buttonlists
838 */
839 protected function getDocHeaderButtons($buttons)
840 {
841 $markers = [];
842 // Fill buttons for left and right float
843 $floats = ['left', 'right'];
844 foreach ($floats as $key) {
845 // Get the template for each float
846 $buttonTemplate = $this->templateService->getSubpart($this->moduleTemplate, '###BUTTON_GROUPS_' . strtoupper($key) . '###');
847 // Fill the button markers in this float
848 $buttonTemplate = $this->templateService->substituteMarkerArray($buttonTemplate, $buttons, '###|###', true);
849 // getting the wrap for each group
850 $buttonWrap = $this->templateService->getSubpart($this->moduleTemplate, '###BUTTON_GROUP_WRAP###');
851 // looping through the groups (max 6) and remove the empty groups
852 for ($groupNumber = 1; $groupNumber < 6; $groupNumber++) {
853 $buttonMarker = '###BUTTON_GROUP' . $groupNumber . '###';
854 $buttonGroup = $this->templateService->getSubpart($buttonTemplate, $buttonMarker);
855 if (trim($buttonGroup)) {
856 if ($buttonWrap) {
857 $buttonGroup = $this->templateService->substituteMarker($buttonWrap, '###BUTTONS###', $buttonGroup);
858 }
859 $buttonTemplate = $this->templateService->substituteSubpart($buttonTemplate, $buttonMarker, trim($buttonGroup));
860 }
861 }
862 // Replace the marker with the template and remove all line breaks (for IE compat)
863 $markers['BUTTONLIST_' . strtoupper($key)] = str_replace(LF, '', $buttonTemplate);
864 }
865 // Hook for manipulating docHeaderButtons
866 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['docHeaderButtonsHook'] ?? [] as $funcRef) {
867 $params = [
868 'buttons' => $buttons,
869 'markers' => &$markers,
870 'pObj' => &$this
871 ];
872 GeneralUtility::callUserFunction($funcRef, $params, $this);
873 }
874 return $markers;
875 }
876
877 /**
878 * Generate the page path for docheader
879 *
880 * @param array $pageRecord Current page
881 * @return string Page path
882 */
883 protected function getPagePath($pageRecord)
884 {
885 // Is this a real page
886 if (is_array($pageRecord) && $pageRecord['uid']) {
887 $title = substr($pageRecord['_thePathFull'], 0, -1);
888 // Remove current page title
889 $pos = strrpos($title, $pageRecord['title']);
890 if ($pos !== false) {
891 $title = substr($title, 0, $pos);
892 }
893 } else {
894 $title = '';
895 }
896 // Setting the path of the page
897 $pagePath = htmlspecialchars($GLOBALS['LANG']->sL('LLL:EXT:core/Resources/Private/Language/locallang_core.xlf:labels.path')) . ': <span class="typo3-docheader-pagePath">';
898 // crop the title to title limit (or 50, if not defined)
899 $cropLength = empty($GLOBALS['BE_USER']->uc['titleLen']) ? 50 : $GLOBALS['BE_USER']->uc['titleLen'];
900 $croppedTitle = GeneralUtility::fixed_lgd_cs($title, -$cropLength);
901 if ($croppedTitle !== $title) {
902 $pagePath .= '<abbr title="' . htmlspecialchars($title) . '">' . htmlspecialchars($croppedTitle) . '</abbr>';
903 } else {
904 $pagePath .= htmlspecialchars($title);
905 }
906 $pagePath .= '</span>';
907 return $pagePath;
908 }
909
910 /**
911 * Setting page icon with context menu + uid for docheader
912 *
913 * @param array $pageRecord Current page
914 * @return string Page info
915 */
916 protected function getPageInfo($pageRecord)
917 {
918 // Add icon with context menu, etc:
919 // If there IS a real page
920 if (is_array($pageRecord) && $pageRecord['uid']) {
921 $alttext = BackendUtility::getRecordIconAltText($pageRecord, 'pages');
922 $iconImg = '<span title="' . htmlspecialchars($alttext) . '">' . $this->iconFactory->getIconForRecord('pages', $pageRecord, Icon::SIZE_SMALL)->render() . '</span>';
923 // Make Icon:
924 $theIcon = BackendUtility::wrapClickMenuOnIcon($iconImg, 'pages', $pageRecord['uid']);
925 $uid = $pageRecord['uid'];
926 $title = BackendUtility::getRecordTitle('pages', $pageRecord);
927 } else {
928 // On root-level of page tree
929 // Make Icon
930 $iconImg = '<span title="' . htmlspecialchars($GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename']) . '">' . $this->iconFactory->getIcon('apps-pagetree-root', Icon::SIZE_SMALL)->render() . '</span>';
931 if ($GLOBALS['BE_USER']->isAdmin()) {
932 $theIcon = BackendUtility::wrapClickMenuOnIcon($iconImg, 'pages');
933 } else {
934 $theIcon = $iconImg;
935 }
936 $uid = '0';
937 $title = $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'];
938 }
939 // Setting icon with context menu + uid
940 $pageInfo = $theIcon . '<strong>' . htmlspecialchars($title) . '&nbsp;[' . $uid . ']</strong>';
941 return $pageInfo;
942 }
943
944 /**
945 * Retrieves configured favicon for backend (with fallback)
946 *
947 * @return string
948 */
949 protected function getBackendFavicon()
950 {
951 $backendFavicon = GeneralUtility::makeInstance(ExtensionConfiguration::class)->get('backend', 'backendFavicon');
952 if (!empty($backendFavicon)) {
953 $path = $this->getUriForFileName($backendFavicon);
954 } else {
955 $path = ExtensionManagementUtility::extPath('backend') . 'Resources/Public/Icons/favicon.ico';
956 }
957 return PathUtility::getAbsoluteWebPath($path);
958 }
959
960 /**
961 * Returns the uri of a relative reference, resolves the "EXT:" prefix
962 * (way of referring to files inside extensions) and checks that the file is inside
963 * the project root of the TYPO3 installation
964 *
965 * @param string $filename The input filename/filepath to evaluate
966 * @return string Returns the filename of $filename if valid, otherwise blank string.
967 */
968 protected function getUriForFileName($filename)
969 {
970 if (strpos($filename, '://')) {
971 return $filename;
972 }
973 $urlPrefix = '';
974 if (strpos($filename, 'EXT:') === 0) {
975 $absoluteFilename = GeneralUtility::getFileAbsFileName($filename);
976 $filename = '';
977 if ($absoluteFilename !== '') {
978 $filename = PathUtility::getAbsoluteWebPath($absoluteFilename);
979 }
980 } elseif (strpos($filename, '/') !== 0) {
981 $urlPrefix = GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
982 }
983 return $urlPrefix . $filename;
984 }
985
986 /**
987 * @return BackendUserAuthentication|null
988 */
989 protected function getBackendUser()
990 {
991 return $GLOBALS['BE_USER'] ?? null;
992 }
993 }