[!!!][TASK] Remove more deprecated miscellaneous functions and options
[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
27 /**
28 * TYPO3 Backend Template Class
29 *
30 * This class contains functions for starting and ending the HTML of backend modules
31 * It also contains methods for outputting sections of content.
32 * Further there are functions for making icons, links, setting form-field widths etc.
33 * Color scheme and stylesheet definitions are also available here.
34 * Finally this file includes the language class for TYPO3's backend.
35 *
36 * After this file $LANG and $TBE_TEMPLATE are global variables / instances of their respective classes.
37 *
38 * Please refer to Inside TYPO3 for a discussion of how to use this API.
39 */
40 class DocumentTemplate
41 {
42 // Vars you typically might want to/should set from outside after making instance of this class:
43 /**
44 * This can be set to the HTML-code for a formtag.
45 * Useful when you need a form to span the whole page; Inserted exactly after the body-tag.
46 *
47 * @var string
48 */
49 public $form = '';
50
51 /**
52 * Additional header code (eg. a JavaScript section) could be accommulated in this var. It will be directly outputted in the header.
53 *
54 * @var string
55 */
56 public $JScode = '';
57
58 /**
59 * Additional header code for ExtJS. It will be included in document header and inserted in a Ext.onReady(function()
60 *
61 * @var string
62 */
63 public $extJScode = '';
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 = array('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 = array();
126
127 /**
128 * Compensation for large documents (used in \TYPO3\CMS\Backend\Form\FormEngine)
129 *
130 * @var float
131 */
132 public $form_largeComp = 1.33;
133
134 /**
135 * Filename of stylesheet (relative to PATH_typo3)
136 *
137 * @var string
138 */
139 public $styleSheetFile = '';
140
141 /**
142 * Filename of stylesheet #2 - linked to right after the $this->styleSheetFile script (relative to PATH_typo3)
143 *
144 * @var string
145 */
146 public $styleSheetFile2 = '';
147
148 /**
149 * Filename of a post-stylesheet - included right after all inline styles.
150 *
151 * @var string
152 */
153 public $styleSheetFile_post = '';
154
155 /**
156 * Whether to use the X-UA-Compatible meta tag
157 *
158 * @var bool
159 */
160 protected $useCompatibilityTag = true;
161
162 /**
163 * X-Ua-Compatible version output in meta tag
164 *
165 * @var string
166 */
167 protected $xUaCompatibilityVersion = 'IE=edge';
168
169 // Skinning
170 /**
171 * Include these CSS directories from skins by default
172 *
173 * @var array
174 */
175 protected $stylesheetsSkins = array(
176 'structure' => 'Resources/Public/Css/structure/',
177 'visual' => 'Resources/Public/Css/visual/'
178 );
179
180 /**
181 * JavaScript files loaded for every page in the Backend
182 *
183 * @var array
184 */
185 protected $jsFiles = array();
186
187 /**
188 * JavaScript files loaded for every page in the Backend, but explicitly excluded from concatenation (useful for libraries etc.)
189 *
190 * @var array
191 */
192 protected $jsFilesNoConcatenation = array();
193
194 /**
195 * Indicates if a <div>-output section is open
196 *
197 * @var int
198 * @internal
199 */
200 public $sectionFlag = 0;
201
202 /**
203 * (Default) Class for wrapping <DIV>-tag of page. Is set in class extensions.
204 *
205 * @var string
206 */
207 public $divClass = '';
208
209 /**
210 * @var string
211 */
212 public $pageHeaderBlock = '';
213
214 /**
215 * @var string
216 */
217 public $endOfPageJsBlock = '';
218
219 /**
220 * @var bool
221 */
222 public $hasDocheader = true;
223
224 /**
225 * @var PageRenderer
226 */
227 protected $pageRenderer = null;
228
229 /**
230 * Alternative template file
231 *
232 * @var string
233 */
234 protected $pageHeaderFooterTemplateFile = '';
235
236 /**
237 * @var bool
238 */
239 protected $extDirectStateProvider = false;
240
241 /**
242 * Whether flashmessages should be rendered or not
243 *
244 * @var bool $showFlashMessages
245 */
246 public $showFlashMessages = true;
247
248 /**
249 * @var IconFactory
250 */
251 protected $iconFactory;
252
253 /**
254 * @var MarkerBasedTemplateService
255 */
256 protected $templateService;
257
258 const STATUS_ICON_ERROR = 3;
259 const STATUS_ICON_WARNING = 2;
260 const STATUS_ICON_NOTIFICATION = 1;
261 const STATUS_ICON_OK = -1;
262
263 /**
264 * Constructor
265 */
266 public function __construct()
267 {
268 // Initializes the page rendering object:
269 $this->initPageRenderer();
270
271 // load Legacy CSS Support
272 $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/LegacyCssClasses');
273 $this->iconFactory = GeneralUtility::makeInstance(IconFactory::class);
274
275 // initialize Marker Support
276 $this->templateService = GeneralUtility::makeInstance(MarkerBasedTemplateService::class);
277
278 // Setting default scriptID:
279 $this->scriptID = GeneralUtility::_GET('M') !== null ? GeneralUtility::_GET('M') : GeneralUtility::_GET('route');
280 $this->bodyTagId = preg_replace('/[^A-Za-z0-9-]/', '-', $this->scriptID);
281 // Individual configuration per script? If so, make a recursive merge of the arrays:
282 if (is_array($GLOBALS['TBE_STYLES']['scriptIDindex'][$this->scriptID])) {
283 // Make copy
284 $ovr = $GLOBALS['TBE_STYLES']['scriptIDindex'][$this->scriptID];
285 // merge styles.
286 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($GLOBALS['TBE_STYLES'], $ovr);
287 // Have to unset - otherwise the second instantiation will do it again!
288 unset($GLOBALS['TBE_STYLES']['scriptIDindex'][$this->scriptID]);
289 }
290 // Main Stylesheets:
291 if ($GLOBALS['TBE_STYLES']['stylesheet']) {
292 $this->styleSheetFile = $GLOBALS['TBE_STYLES']['stylesheet'];
293 }
294 if ($GLOBALS['TBE_STYLES']['stylesheet2']) {
295 $this->styleSheetFile2 = $GLOBALS['TBE_STYLES']['stylesheet2'];
296 }
297 if ($GLOBALS['TBE_STYLES']['styleSheetFile_post']) {
298 $this->styleSheetFile_post = $GLOBALS['TBE_STYLES']['styleSheetFile_post'];
299 }
300 if ($GLOBALS['TBE_STYLES']['inDocStyles_TBEstyle']) {
301 $this->inDocStylesArray['TBEstyle'] = $GLOBALS['TBE_STYLES']['inDocStyles_TBEstyle'];
302 }
303 // include all stylesheets
304 foreach ($this->getSkinStylesheetDirectories() as $stylesheetDirectory) {
305 $this->addStylesheetDirectory($stylesheetDirectory);
306 }
307 }
308
309 /**
310 * Initializes the page renderer object
311 */
312 protected function initPageRenderer()
313 {
314 if ($this->pageRenderer !== null) {
315 return;
316 }
317 $this->pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
318 $this->pageRenderer->setLanguage($GLOBALS['LANG']->lang);
319 $this->pageRenderer->enableConcatenateFiles();
320 $this->pageRenderer->enableCompressCss();
321 $this->pageRenderer->enableCompressJavascript();
322 // Add all JavaScript files defined in $this->jsFiles to the PageRenderer
323 foreach ($this->jsFilesNoConcatenation as $file) {
324 $this->pageRenderer->addJsFile(
325 $file,
326 'text/javascript',
327 true,
328 false,
329 '',
330 true
331 );
332 }
333 // Add all JavaScript files defined in $this->jsFiles to the PageRenderer
334 foreach ($this->jsFiles as $file) {
335 $this->pageRenderer->addJsFile($file);
336 }
337 if ((int)$GLOBALS['TYPO3_CONF_VARS']['BE']['debug'] === 1) {
338 $this->pageRenderer->enableDebugMode();
339 }
340 }
341
342 /**
343 * Sets inclusion of StateProvider
344 *
345 * @return void
346 */
347 public function setExtDirectStateProvider()
348 {
349 $this->extDirectStateProvider = true;
350 }
351
352 /*****************************************
353 *
354 * EVALUATION FUNCTIONS
355 * Various centralized processing
356 *
357 *****************************************/
358
359 /**
360 * Makes link to page $id in frontend (view page)
361 * Returns an icon which links to the frontend index.php document for viewing the page with id $id
362 * $id must be a page-uid
363 * If the BE_USER has access to Web>List then a link to that module is shown as well (with return-url)
364 *
365 * @param int $id The page id
366 * @return string HTML string with linked icon(s)
367 */
368 public function viewPageIcon($id)
369 {
370 // If access to Web>List for user, then link to that module.
371 $str = BackendUtility::getListViewLink(array(
372 'id' => $id,
373 'returnUrl' => GeneralUtility::getIndpEnv('REQUEST_URI')
374 ), $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.showList'));
375 // Make link to view page
376 $str .= '<a href="#" onclick="' . htmlspecialchars(BackendUtility::viewOnClick($id, '', BackendUtility::BEgetRootLine($id))) . '" title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.showPage', true) . '">' . $this->iconFactory->getIcon('actions-document-view', Icon::SIZE_SMALL)->render() . '</a>';
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 $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.makeBookmark', true) . '">' .
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, true);
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('sysext/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('sysext/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 GeneralUtility::logDeprecatedFunction();
830 if ($this->sectionFlag) {
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 // Calculation needed, when TYPO3 source is used via a symlink
906 // absolute path to the stylesheets
907 $filePath = GeneralUtility::getFileAbsFileName($path, false, true);
908 // Clean the path
909 $resolvedPath = GeneralUtility::resolveBackPath($filePath);
910 // Read all files in directory and sort them alphabetically
911 $files = GeneralUtility::getFilesInDir($resolvedPath, 'css', false, 1);
912 foreach ($files as $file) {
913 $this->pageRenderer->addCssFile($path . $file, 'stylesheet', 'all');
914 }
915 }
916
917 /**
918 * Insert post rendering document style into already rendered content
919 * This is needed for extobjbase
920 *
921 * @param string $content style-content to insert.
922 * @return string content with inserted styles
923 */
924 public function insertStylesAndJS($content)
925 {
926 $styles = LF . implode(LF, $this->inDocStylesArray);
927 $content = str_replace('/*###POSTCSSMARKER###*/', $styles, $content);
928
929 // Insert accumulated JS
930 $jscode = $this->JScode . LF . $this->wrapScriptTags(implode(LF, $this->JScodeArray));
931 $content = str_replace('<!--###POSTJSMARKER###-->', $jscode, $content);
932 return $content;
933 }
934
935 /**
936 * Returns an array of all stylesheet directories belonging to core and skins
937 *
938 * @return array Stylesheet directories
939 */
940 public function getSkinStylesheetDirectories()
941 {
942 $stylesheetDirectories = array();
943 // Stylesheets from skins
944 // merge default css directories ($this->stylesheetsSkin) with additional ones and include them
945 if (is_array($GLOBALS['TBE_STYLES']['skins'])) {
946 // loop over all registered skins
947 foreach ($GLOBALS['TBE_STYLES']['skins'] as $skinExtKey => $skin) {
948 $skinStylesheetDirs = $this->stylesheetsSkins;
949 // Skins can add custom stylesheetDirectories using
950 // $GLOBALS['TBE_STYLES']['skins'][$_EXTKEY]['stylesheetDirectories']
951 if (is_array($skin['stylesheetDirectories'])) {
952 $skinStylesheetDirs = array_merge($skinStylesheetDirs, $skin['stylesheetDirectories']);
953 }
954 // Add all registered directories
955 foreach ($skinStylesheetDirs as $stylesheetDir) {
956 // for EXT:myskin/stylesheets/ syntax
957 if (substr($stylesheetDir, 0, 4) === 'EXT:') {
958 list($extKey, $path) = explode('/', substr($stylesheetDir, 4), 2);
959 if (!empty($extKey) && ExtensionManagementUtility::isLoaded($extKey) && !empty($path)) {
960 $stylesheetDirectories[] = ExtensionManagementUtility::extRelPath($extKey) . $path;
961 }
962 } else {
963 // For relative paths
964 $stylesheetDirectories[] = ExtensionManagementUtility::extRelPath($skinExtKey) . $stylesheetDir;
965 }
966 }
967 }
968 }
969 return $stylesheetDirectories;
970 }
971
972 /**
973 * Returns generator meta tag
974 *
975 * @return string <meta> tag with name "generator
976 */
977 public function generator()
978 {
979 $str = 'TYPO3 CMS, ' . TYPO3_URL_GENERAL . ', &#169; Kasper Sk&#229;rh&#248;j ' . TYPO3_copyright_year . ', extensions are copyright of their respective owners.';
980 return '<meta name="generator" content="' . $str . '" />';
981 }
982
983 /**
984 * Returns X-UA-Compatible meta tag
985 *
986 * @param string $content Content of the compatible tag (default: IE-8)
987 * @return string <meta http-equiv="X-UA-Compatible" content="???" />
988 */
989 public function xUaCompatible($content = 'IE=8')
990 {
991 return '<meta http-equiv="X-UA-Compatible" content="' . $content . '" />';
992 }
993
994 /*****************************************
995 *
996 * OTHER ELEMENTS
997 * Tables, buttons, formatting dimmed/red strings
998 *
999 ******************************************/
1000 /**
1001 * Returns an image-tag with an 18x16 icon of the following types:
1002 *
1003 * $type:
1004 * -1: OK icon (Check-mark)
1005 * 1: Notice (Speach-bubble)
1006 * 2: Warning (Yellow triangle)
1007 * 3: Fatal error (Red stop sign)
1008 *
1009 * @param int $type See description
1010 * @param string $styleAttribValue Value for style attribute
1011 * @return string HTML image tag (if applicable)
1012 */
1013 public function icons($type, $styleAttribValue = '')
1014 {
1015 switch ($type) {
1016 case self::STATUS_ICON_ERROR:
1017 $icon = 'status-dialog-error';
1018 break;
1019 case self::STATUS_ICON_WARNING:
1020 $icon = 'status-dialog-warning';
1021 break;
1022 case self::STATUS_ICON_NOTIFICATION:
1023 $icon = 'status-dialog-notification';
1024 break;
1025 case self::STATUS_ICON_OK:
1026 $icon = 'status-dialog-ok';
1027 break;
1028 default:
1029 // Do nothing
1030 }
1031 if ($icon) {
1032 return $this->iconFactory->getIcon($icon, Icon::SIZE_SMALL)->render();
1033 }
1034 }
1035
1036 /**
1037 * Returns an <input> button with the $onClick action and $label
1038 *
1039 * @param string $onClick The value of the onclick attribute of the input tag (submit type)
1040 * @param string $label The label for the button (which will be htmlspecialchar'ed)
1041 * @return string A <input> tag of the type "submit
1042 */
1043 public function t3Button($onClick, $label)
1044 {
1045 $button = '<input class="btn btn-default" type="submit" onclick="' . htmlspecialchars($onClick) . '; return false;" value="' . htmlspecialchars($label) . '" />';
1046 return $button;
1047 }
1048
1049 /**
1050 * Returns string wrapped in CDATA "tags" for XML / XHTML (wrap content of <script> and <style> sections in those!)
1051 *
1052 * @param string $string Input string
1053 * @return string Output string
1054 */
1055 public function wrapInCData($string)
1056 {
1057 $string = '/*<![CDATA[*/' . $string . '/*]]>*/';
1058 return $string;
1059 }
1060
1061 /**
1062 * Wraps the input string in script tags.
1063 * Automatic re-identing of the JS code is done by using the first line as ident reference.
1064 * This is nice for identing JS code with PHP code on the same level.
1065 *
1066 * @param string $string Input string
1067 * @param bool $linebreak Wrap script element in linebreaks? Default is TRUE.
1068 * @return string Output string
1069 */
1070 public function wrapScriptTags($string, $linebreak = true)
1071 {
1072 if (trim($string)) {
1073 // <script wrapped in nl?
1074 $cr = $linebreak ? LF : '';
1075 // Remove nl from the beginning
1076 $string = ltrim($string, LF);
1077 // Re-ident to one tab using the first line as reference
1078 if ($string[0] === TAB) {
1079 $string = TAB . ltrim($string, TAB);
1080 }
1081 $string = $cr . '<script type="text/javascript">
1082 /*<![CDATA[*/
1083 ' . $string . '
1084 /*]]>*/
1085 </script>' . $cr;
1086 }
1087 return trim($string);
1088 }
1089
1090 // These vars defines the layout for the table produced by the table() function.
1091 // You can override these values from outside if you like.
1092 public $tableLayout = array(
1093 'defRow' => array(
1094 'defCol' => array('<td valign="top">', '</td>')
1095 )
1096 );
1097
1098 public $table_TR = '<tr>';
1099
1100 public $table_TABLE = '<table border="0" cellspacing="0" cellpadding="0" class="typo3-dblist" id="typo3-tmpltable">';
1101
1102 /**
1103 * Returns a one-row/two-celled table with $content and $menu side by side.
1104 * The table is a 100% width table and each cell is aligned left / right
1105 *
1106 * @param string $content Content cell content (left)
1107 * @param string $menu Menu cell content (right)
1108 * @return string HTML output
1109 */
1110 public function funcMenu($content, $menu)
1111 {
1112 return '
1113 <table border="0" cellpadding="0" cellspacing="0" width="100%" id="typo3-funcmenu">
1114 <tr>
1115 <td valign="top" nowrap="nowrap">' . $content . '</td>
1116 <td valign="top" align="right" nowrap="nowrap">' . $menu . '</td>
1117 </tr>
1118 </table>';
1119 }
1120
1121 /**
1122 * Includes a javascript library that exists in the core /typo3/ directory
1123 *
1124 * @param string $lib: Library name. Call it with the full path like "sysext/core/Resources/Public/JavaScript/QueryGenerator.js" to load it
1125 * @return void
1126 */
1127 public function loadJavascriptLib($lib)
1128 {
1129 // @todo: maybe we can remove this one as well
1130 $this->pageRenderer->addJsFile($lib);
1131 }
1132
1133 /**
1134 * Includes the necessary Javascript function for the clickmenu (context sensitive menus) in the document
1135 *
1136 * @return void
1137 */
1138 public function getContextMenuCode()
1139 {
1140 $this->pageRenderer->loadJquery();
1141 $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/ClickMenu');
1142 }
1143
1144 /**
1145 * Includes the necessary javascript file for use on pages which have the
1146 * drag and drop functionality (legacy folder tree)
1147 *
1148 * @param string $table indicator of which table the drag and drop function should work on (pages or folders)
1149 * @param string $additionalJavaScriptCode adds more code to the additional javascript code
1150 * @return void
1151 */
1152 public function getDragDropCode($table, $additionalJavaScriptCode = '')
1153 {
1154 $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/LegacyTree', 'function() {
1155 DragDrop.table = "' . $table . '";
1156 ' . $additionalJavaScriptCode . '
1157 }');
1158 }
1159
1160 /**
1161 * Creates a tab menu from an array definition
1162 *
1163 * Returns a tab menu for a module
1164 * Requires the JS function jumpToUrl() to be available
1165 *
1166 * @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=...
1167 * @param string $elementName it the form elements name, probably something like "SET[...]
1168 * @param string $currentValue is the value to be selected currently.
1169 * @param array $menuItems is an array with the menu items for the selector box
1170 * @param string $script is the script to send the &id to, if empty it's automatically found
1171 * @param string $addparams is additional parameters to pass to the script.
1172 * @return string HTML code for tab menu
1173 */
1174 public function getTabMenu($mainParams, $elementName, $currentValue, $menuItems, $script = '', $addparams = '')
1175 {
1176 $content = '';
1177 if (is_array($menuItems)) {
1178 if (!is_array($mainParams)) {
1179 $mainParams = array('id' => $mainParams);
1180 }
1181 $mainParams = GeneralUtility::implodeArrayForUrl('', $mainParams);
1182 if (!$script) {
1183 $script = basename(PATH_thisScript);
1184 }
1185 $menuDef = array();
1186 foreach ($menuItems as $value => $label) {
1187 $menuDef[$value]['isActive'] = (string)$currentValue === (string)$value;
1188 $menuDef[$value]['label'] = htmlspecialchars($label, ENT_COMPAT, 'UTF-8', false);
1189 $menuDef[$value]['url'] = $script . '?' . $mainParams . $addparams . '&' . $elementName . '=' . $value;
1190 }
1191 $content = $this->getTabMenuRaw($menuDef);
1192 }
1193 return $content;
1194 }
1195
1196 /**
1197 * Creates the HTML content for the tab menu
1198 *
1199 * @param array $menuItems Menu items for tabs
1200 * @return string Table HTML
1201 * @access private
1202 */
1203 public function getTabMenuRaw($menuItems)
1204 {
1205 if (!is_array($menuItems)) {
1206 return '';
1207 }
1208
1209 $options = '';
1210 foreach ($menuItems as $id => $def) {
1211 $class = $def['isActive'] ? 'active' : '';
1212 $label = $def['label'];
1213 $url = htmlspecialchars($def['url']);
1214 $params = $def['addParams'];
1215
1216 $options .= '<li class="' . $class . '">' .
1217 '<a href="' . $url . '" ' . $params . '>' . $label . '</a>' .
1218 '</li>';
1219 }
1220
1221 return '<ul class="nav nav-tabs" role="tablist">' .
1222 $options .
1223 '</ul>';
1224 }
1225
1226 /**
1227 * Creates the version selector for the page id inputted.
1228 * Requires the core version management extension, "version" to be loaded.
1229 *
1230 * @param int $id Page id to create selector for.
1231 * @param bool $noAction If set, there will be no button for swapping page.
1232 * @return string
1233 */
1234 public function getVersionSelector($id, $noAction = false)
1235 {
1236 if (
1237 ExtensionManagementUtility::isLoaded('version') &&
1238 !ExtensionManagementUtility::isLoaded('workspaces')
1239 ) {
1240 $versionGuiObj = GeneralUtility::makeInstance(\TYPO3\CMS\Version\View\VersionView::class);
1241 return $versionGuiObj->getVersionSelector($id, $noAction);
1242 }
1243 }
1244
1245 /**
1246 * Function to load a HTML template file with markers.
1247 * When calling from own extension, use syntax getHtmlTemplate('EXT:extkey/template.html')
1248 *
1249 * @param string $filename tmpl name, usually in the typo3/template/ directory
1250 * @return string HTML of template
1251 */
1252 public function getHtmlTemplate($filename)
1253 {
1254 // setting the name of the original HTML template
1255 $this->moduleTemplateFilename = $filename;
1256 if ($GLOBALS['TBE_STYLES']['htmlTemplates'][$filename]) {
1257 $filename = $GLOBALS['TBE_STYLES']['htmlTemplates'][$filename];
1258 }
1259 if (GeneralUtility::isFirstPartOfStr($filename, 'EXT:')) {
1260 $filename = GeneralUtility::getFileAbsFileName($filename, true, true);
1261 } elseif (!GeneralUtility::isAbsPath($filename)) {
1262 $filename = GeneralUtility::resolveBackPath($filename);
1263 } elseif (!GeneralUtility::isAllowedAbsPath($filename)) {
1264 $filename = '';
1265 }
1266 $htmlTemplate = '';
1267 if ($filename !== '') {
1268 $htmlTemplate = GeneralUtility::getUrl($filename);
1269 }
1270 return $htmlTemplate;
1271 }
1272
1273 /**
1274 * Define the template for the module
1275 *
1276 * @param string $filename filename
1277 * @return void
1278 */
1279 public function setModuleTemplate($filename)
1280 {
1281 $this->moduleTemplate = $this->getHtmlTemplate($filename);
1282 }
1283
1284 /**
1285 * Put together the various elements for the module <body> using a static HTML
1286 * template
1287 *
1288 * @param array $pageRecord Record of the current page, used for page path and info
1289 * @param array $buttons HTML for all buttons
1290 * @param array $markerArray HTML for all other markers
1291 * @param array $subpartArray HTML for the subparts
1292 * @return string Composite HTML
1293 */
1294 public function moduleBody($pageRecord = array(), $buttons = array(), $markerArray = array(), $subpartArray = array())
1295 {
1296 // Get the HTML template for the module
1297 $moduleBody = $this->templateService->getSubpart($this->moduleTemplate, '###FULLDOC###');
1298 // Add CSS
1299 $this->inDocStylesArray[] = 'html { overflow: hidden; }';
1300 // Get the page path for the docheader
1301 $markerArray['PAGEPATH'] = $this->getPagePath($pageRecord);
1302 // Get the page info for the docheader
1303 $markerArray['PAGEINFO'] = $this->getPageInfo($pageRecord);
1304 // Get all the buttons for the docheader
1305 $docHeaderButtons = $this->getDocHeaderButtons($buttons);
1306 // Merge docheader buttons with the marker array
1307 $markerArray = array_merge($markerArray, $docHeaderButtons);
1308 // replacing subparts
1309 foreach ($subpartArray as $marker => $content) {
1310 $moduleBody = $this->templateService->substituteSubpart($moduleBody, $marker, $content);
1311 }
1312 // adding flash messages
1313 if ($this->showFlashMessages) {
1314 $flashMessages = $this->getFlashMessages();
1315 if (!empty($flashMessages)) {
1316 $markerArray['FLASHMESSAGES'] = $flashMessages;
1317 // If there is no dedicated marker for the messages present
1318 // then force them to appear before the content
1319 if (strpos($moduleBody, '###FLASHMESSAGES###') === false) {
1320 $moduleBody = str_replace('###CONTENT###', '###FLASHMESSAGES######CONTENT###', $moduleBody);
1321 }
1322 }
1323 }
1324 // Hook for adding more markers/content to the page, like the version selector
1325 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['moduleBodyPostProcess'])) {
1326 $params = array(
1327 'moduleTemplateFilename' => &$this->moduleTemplateFilename,
1328 'moduleTemplate' => &$this->moduleTemplate,
1329 'moduleBody' => &$moduleBody,
1330 'markers' => &$markerArray,
1331 'parentObject' => &$this
1332 );
1333 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['moduleBodyPostProcess'] as $funcRef) {
1334 GeneralUtility::callUserFunction($funcRef, $params, $this);
1335 }
1336 }
1337 // Replacing all markers with the finished markers and return the HTML content
1338 return $this->templateService->substituteMarkerArray($moduleBody, $markerArray, '###|###');
1339 }
1340
1341 /**
1342 * Get the default rendered FlashMessages from queue
1343 *
1344 * @return string
1345 */
1346 public function getFlashMessages()
1347 {
1348 /** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
1349 $flashMessageService = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessageService::class);
1350 /** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
1351 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
1352 return $defaultFlashMessageQueue->renderFlashMessages();
1353 }
1354
1355 /**
1356 * Renders the FlashMessages from queue and returns them as AJAX.
1357 *
1358 * @param ServerRequestInterface $request
1359 * @param ResponseInterface $response
1360 * @return ResponseInterface
1361 */
1362 public function renderQueuedFlashMessages(ServerRequestInterface $request, ResponseInterface $response)
1363 {
1364 /** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
1365 $flashMessageService = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessageService::class);
1366 /** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
1367 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
1368 $flashMessages = $defaultFlashMessageQueue->getAllMessagesAndFlush();
1369
1370 $messages = [];
1371 foreach ($flashMessages as $flashMessage) {
1372 $messages[] = [
1373 'title' => $flashMessage->getTitle(),
1374 'message' => $flashMessage->getMessage(),
1375 'severity' => $flashMessage->getSeverity()
1376 ];
1377 }
1378
1379 $response->getBody()->write(json_encode($messages));
1380 return $response;
1381 }
1382
1383 /**
1384 * Fill the button lists with the defined HTML
1385 *
1386 * @param array $buttons HTML for all buttons
1387 * @return array Containing HTML for both buttonlists
1388 */
1389 protected function getDocHeaderButtons($buttons)
1390 {
1391 $markers = array();
1392 // Fill buttons for left and right float
1393 $floats = array('left', 'right');
1394 foreach ($floats as $key) {
1395 // Get the template for each float
1396 $buttonTemplate = $this->templateService->getSubpart($this->moduleTemplate, '###BUTTON_GROUPS_' . strtoupper($key) . '###');
1397 // Fill the button markers in this float
1398 $buttonTemplate = $this->templateService->substituteMarkerArray($buttonTemplate, $buttons, '###|###', true);
1399 // getting the wrap for each group
1400 $buttonWrap = $this->templateService->getSubpart($this->moduleTemplate, '###BUTTON_GROUP_WRAP###');
1401 // looping through the groups (max 6) and remove the empty groups
1402 for ($groupNumber = 1; $groupNumber < 6; $groupNumber++) {
1403 $buttonMarker = '###BUTTON_GROUP' . $groupNumber . '###';
1404 $buttonGroup = $this->templateService->getSubpart($buttonTemplate, $buttonMarker);
1405 if (trim($buttonGroup)) {
1406 if ($buttonWrap) {
1407 $buttonGroup = $this->templateService->substituteMarker($buttonWrap, '###BUTTONS###', $buttonGroup);
1408 }
1409 $buttonTemplate = $this->templateService->substituteSubpart($buttonTemplate, $buttonMarker, trim($buttonGroup));
1410 }
1411 }
1412 // Replace the marker with the template and remove all line breaks (for IE compat)
1413 $markers['BUTTONLIST_' . strtoupper($key)] = str_replace(LF, '', $buttonTemplate);
1414 }
1415 // Hook for manipulating docHeaderButtons
1416 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['docHeaderButtonsHook'])) {
1417 $params = array(
1418 'buttons' => $buttons,
1419 'markers' => &$markers,
1420 'pObj' => &$this
1421 );
1422 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['docHeaderButtonsHook'] as $funcRef) {
1423 GeneralUtility::callUserFunction($funcRef, $params, $this);
1424 }
1425 }
1426 return $markers;
1427 }
1428
1429 /**
1430 * Generate the page path for docheader
1431 *
1432 * @param array $pageRecord Current page
1433 * @return string Page path
1434 */
1435 protected function getPagePath($pageRecord)
1436 {
1437 // Is this a real page
1438 if (is_array($pageRecord) && $pageRecord['uid']) {
1439 $title = substr($pageRecord['_thePathFull'], 0, -1);
1440 // Remove current page title
1441 $pos = strrpos($title, $pageRecord['title']);
1442 if ($pos !== false) {
1443 $title = substr($title, 0, $pos);
1444 }
1445 } else {
1446 $title = '';
1447 }
1448 // Setting the path of the page
1449 $pagePath = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.path', true) . ': <span class="typo3-docheader-pagePath">';
1450 // crop the title to title limit (or 50, if not defined)
1451 $cropLength = empty($GLOBALS['BE_USER']->uc['titleLen']) ? 50 : $GLOBALS['BE_USER']->uc['titleLen'];
1452 $croppedTitle = GeneralUtility::fixed_lgd_cs($title, -$cropLength);
1453 if ($croppedTitle !== $title) {
1454 $pagePath .= '<abbr title="' . htmlspecialchars($title) . '">' . htmlspecialchars($croppedTitle) . '</abbr>';
1455 } else {
1456 $pagePath .= htmlspecialchars($title);
1457 }
1458 $pagePath .= '</span>';
1459 return $pagePath;
1460 }
1461
1462 /**
1463 * Setting page icon with clickmenu + uid for docheader
1464 *
1465 * @param array $pageRecord Current page
1466 * @return string Page info
1467 */
1468 protected function getPageInfo($pageRecord)
1469 {
1470 // Add icon with clickmenu, etc:
1471 // If there IS a real page
1472 if (is_array($pageRecord) && $pageRecord['uid']) {
1473 $alttext = BackendUtility::getRecordIconAltText($pageRecord, 'pages');
1474 $iconImg = '<span title="' . htmlspecialchars($alttext) . '">' . $this->iconFactory->getIconForRecord('pages', $pageRecord, Icon::SIZE_SMALL)->render() . '</span>';
1475 // Make Icon:
1476 $theIcon = BackendUtility::wrapClickMenuOnIcon($iconImg, 'pages', $pageRecord['uid']);
1477 $uid = $pageRecord['uid'];
1478 $title = BackendUtility::getRecordTitle('pages', $pageRecord);
1479 } else {
1480 // On root-level of page tree
1481 // Make Icon
1482 $iconImg = '<span title="' . htmlspecialchars($GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename']) . '">' . $this->iconFactory->getIcon('apps-pagetree-root', Icon::SIZE_SMALL)->render() . '</span>';
1483 if ($GLOBALS['BE_USER']->user['admin']) {
1484 $theIcon = BackendUtility::wrapClickMenuOnIcon($iconImg, 'pages', 0);
1485 } else {
1486 $theIcon = $iconImg;
1487 }
1488 $uid = '0';
1489 $title = $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'];
1490 }
1491 // Setting icon with clickmenu + uid
1492 $pageInfo = $theIcon . '<strong>' . htmlspecialchars($title) . '&nbsp;[' . $uid . ']</strong>';
1493 return $pageInfo;
1494 }
1495
1496 /**
1497 * Retrieves configured favicon for backend (with fallback)
1498 *
1499 * @return string
1500 */
1501 protected function getBackendFavicon()
1502 {
1503 return $GLOBALS['TBE_STYLES']['favicon'] ?: 'sysext/backend/Resources/Public/Icons/favicon.ico';
1504 }
1505 }