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