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