[TASK] Migrate Toolbar ShortcutMenu JS to jQuery
[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 TYPO3\CMS\Backend\Utility\BackendUtility;
18 use TYPO3\CMS\Backend\Utility\IconUtility;
19 use TYPO3\CMS\Core\Html\HtmlParser;
20 use TYPO3\CMS\Core\Page\PageRenderer;
21 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
22 use TYPO3\CMS\Core\Utility\GeneralUtility;
23
24 /**
25 * TYPO3 Backend Template Class
26 *
27 * This class contains functions for starting and ending the HTML of backend modules
28 * It also contains methods for outputting sections of content.
29 * Further there are functions for making icons, links, setting form-field widths etc.
30 * Color scheme and stylesheet definitions are also available here.
31 * Finally this file includes the language class for TYPO3's backend.
32 *
33 * After this file $LANG and $TBE_TEMPLATE are global variables / instances of their respective classes.
34 * This file is typically included right after the init.php file,
35 * if language and layout is needed.
36 *
37 * Please refer to Inside TYPO3 for a discussion of how to use this API.
38 *
39 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
40 */
41 class DocumentTemplate {
42
43 // Vars you typically might want to/should set from outside after making instance of this class:
44 /**
45 * 'backPath' pointing back to the PATH_typo3
46 *
47 * @var string
48 */
49 public $backPath = '';
50
51 /**
52 * This can be set to the HTML-code for a formtag.
53 * Useful when you need a form to span the whole page; Inserted exactly after the body-tag.
54 *
55 * @var string
56 */
57 public $form = '';
58
59 /**
60 * Similar to $JScode (see below) but used as an associative array to prevent double inclusion of JS code.
61 * This is used to include certain external Javascript libraries before the inline JS code.
62 * <script>-Tags are not wrapped around automatically
63 *
64 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8, use pageRenderer directly
65 */
66 public $JScodeLibArray = array();
67
68 /**
69 * Additional header code (eg. a JavaScript section) could be accommulated in this var. It will be directly outputted in the header.
70 *
71 * @var string
72 */
73 public $JScode = '';
74
75 /**
76 * Additional header code for ExtJS. It will be included in document header and inserted in a Ext.onReady(function()
77 *
78 * @var string
79 */
80 public $extJScode = '';
81
82 /**
83 * 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.
84 *
85 * @var array
86 */
87 public $JScodeArray = array('jumpToUrl' => '
88 function jumpToUrl(URL) {
89 window.location.href = URL;
90 return false;
91 }
92 ');
93
94 /**
95 * 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.
96 *
97 * @var string
98 */
99 public $postCode = '';
100
101 /**
102 * Doc-type used in the header. Default is xhtml_trans. You can also set it to 'html_3', 'xhtml_strict' or 'xhtml_frames'.
103 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8, as it is HTML5
104 */
105 public $docType = '';
106
107 /**
108 * HTML template with markers for module
109 *
110 * @var string
111 */
112 public $moduleTemplate = '';
113
114 /**
115 * The base file (not overlaid by TBE_STYLES) for the current module, useful for hooks when finding out which modules is rendered currently
116 *
117 * @var string
118 */
119 protected $moduleTemplateFilename = '';
120
121 /**
122 * Script ID
123 *
124 * @var string
125 */
126 public $scriptID = '';
127
128 /**
129 * Id which can be set for the body tag. Default value is based on script ID
130 *
131 * @var string
132 */
133 public $bodyTagId = '';
134
135 /**
136 * You can add additional attributes to the body-tag through this variable.
137 *
138 * @var string
139 */
140 public $bodyTagAdditions = '';
141
142 /**
143 * Additional CSS styles which will be added to the <style> section in the header
144 *
145 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8, use the pageRenderer property for adding CSS styles
146 */
147 public $inDocStyles = '';
148
149 /**
150 * Additional CSS styles which will be added to the <style> section in the header
151 * used as array with associative keys to prevent double inclusion of CSS code
152 *
153 * @var array
154 */
155 public $inDocStylesArray = array();
156
157 /**
158 * Compensation for large documents (used in \TYPO3\CMS\Backend\Form\FormEngine)
159 *
160 * @var float
161 */
162 public $form_largeComp = 1.33;
163
164 /**
165 * If set, then a JavaScript section will be outputted in the bottom of page which will try and update the top.busy session expiry object.
166 *
167 * @var int
168 * @deprecated since TYPO3 CMS 7, will be removed in CMS 8
169 */
170 public $endJS = 1;
171
172 // TYPO3 Colorscheme.
173 // If you want to change this, please do so through a skin using the global var $GLOBALS['TBE_STYLES']
174
175 /**
176 * Light background color
177 *
178 * @deprecated since TYPO3 CMS 7, will be removed in CMS 8
179 */
180 public $bgColor = '#F7F3EF';
181
182 /**
183 * Steel-blue
184 *
185 * @deprecated since TYPO3 CMS 7, will be removed in CMS 8
186 */
187 public $bgColor2 = '#9BA1A8';
188
189 /**
190 * dok.color
191 *
192 * @deprecated since TYPO3 CMS 7, will be removed in CMS 8
193 */
194 public $bgColor3 = '#F6F2E6';
195
196 /**
197 * light tablerow background, brownish
198 *
199 * @deprecated since TYPO3 CMS 7, will be removed in CMS 8
200 */
201 public $bgColor4 = '#D9D5C9';
202
203 /**
204 * light tablerow background, greenish
205 *
206 * @deprecated since TYPO3 CMS 7, will be removed in CMS 8
207 */
208 public $bgColor5 = '#ABBBB4';
209
210 /**
211 * light tablerow background, yellowish, for section headers. Light.
212 *
213 * @deprecated since TYPO3 CMS 7, will be removed in CMS 8
214 */
215 public $bgColor6 = '#E7DBA8';
216
217 /**
218 * @deprecated since TYPO3 CMS 7, will be removed in CMS 8
219 */
220 public $hoverColor = '#254D7B';
221
222 /**
223 * Filename of stylesheet (relative to PATH_typo3)
224 *
225 * @var string
226 */
227 public $styleSheetFile = '';
228
229 /**
230 * Filename of stylesheet #2 - linked to right after the $this->styleSheetFile script (relative to PATH_typo3)
231 *
232 * @var string
233 */
234 public $styleSheetFile2 = '';
235
236 /**
237 * Filename of a post-stylesheet - included right after all inline styles.
238 *
239 * @var string
240 */
241 public $styleSheetFile_post = '';
242
243 /**
244 * Background image of page (relative to PATH_typo3)
245 *
246 * @var string
247 */
248 public $backGroundImage = '';
249
250 /**
251 * Inline css styling set from TBE_STYLES array
252 *
253 * @var string
254 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8, use inDocStylesArray['TBEstyle']
255 */
256 public $inDocStyles_TBEstyle = '';
257
258 /**
259 * Whether to use the X-UA-Compatible meta tag
260 *
261 * @var bool
262 */
263 protected $useCompatibilityTag = TRUE;
264
265 /**
266 * X-Ua-Compatible version output in meta tag
267 *
268 * @var string
269 */
270 protected $xUaCompatibilityVersion = 'IE=10';
271
272 // Skinning
273 /**
274 * stylesheets from core
275 *
276 * @var array
277 */
278 protected $stylesheetsCore = array(
279 'structure' => 'sysext/backend/Resources/Public/Css/structure/',
280 'visual' => 'sysext/backend/Resources/Public/Css/visual/',
281 'generatedSprites' => '../typo3temp/sprites/'
282 );
283
284 /**
285 * Include these CSS directories from skins by default
286 *
287 * @var array
288 */
289 protected $stylesheetsSkins = array(
290 'structure' => 'Resources/Public/Css/structure/',
291 'visual' => 'Resources/Public/Css/visual/'
292 );
293
294 /**
295 * JavaScript files loaded for every page in the Backend
296 *
297 * @var array
298 */
299 protected $jsFiles = array();
300
301 /**
302 * JavaScript files loaded for every page in the Backend, but explicitly excluded from concatenation (useful for libraries etc.)
303 *
304 * @var array
305 */
306 protected $jsFilesNoConcatenation = array(
307 'modernizr' => 'contrib/modernizr/modernizr.min.js'
308 );
309
310 /**
311 * Will output the parsetime of the scripts in milliseconds (for admin-users).
312 * Set this to FALSE when releasing TYPO3. Only for dev.
313 *
314 * @var bool
315 */
316 public $parseTimeFlag = FALSE;
317
318 /**
319 * internal character set, nowadays utf-8 for everything
320 *
321 * @var string
322 * @deprecated since TYPO3 CMS 7, will be removed in CMS 8, as it is always utf-8
323 */
324 protected $charset = 'utf-8';
325
326 /**
327 * Indicates if a <div>-output section is open
328 *
329 * @var int
330 * @internal
331 */
332 public $sectionFlag = 0;
333
334 /**
335 * (Default) Class for wrapping <DIV>-tag of page. Is set in class extensions.
336 *
337 * @var string
338 */
339 public $divClass = '';
340
341 /**
342 * @var string
343 */
344 public $pageHeaderBlock = '';
345
346 /**
347 * @var string
348 */
349 public $endOfPageJsBlock = '';
350
351 /**
352 * @var bool
353 */
354 public $hasDocheader = TRUE;
355
356 /**
357 * @var \TYPO3\CMS\Core\Page\PageRenderer
358 */
359 protected $pageRenderer;
360
361 /**
362 * Alternative template file
363 *
364 * @var string
365 */
366 protected $pageHeaderFooterTemplateFile = '';
367
368 /**
369 * @var bool
370 */
371 protected $extDirectStateProvider = FALSE;
372
373 /**
374 * Whether flashmessages should be rendered or not
375 *
376 * @var bool $showFlashMessages
377 */
378 public $showFlashMessages = TRUE;
379
380 const STATUS_ICON_ERROR = 3;
381 const STATUS_ICON_WARNING = 2;
382 const STATUS_ICON_NOTIFICATION = 1;
383 const STATUS_ICON_OK = -1;
384
385 /**
386 * Constructor
387 */
388 public function __construct() {
389 // Initializes the page rendering object:
390 $this->getPageRenderer();
391 // Setting default scriptID:
392 if (($temp_M = (string)GeneralUtility::_GET('M')) && $GLOBALS['TBE_MODULES']['_PATHS'][$temp_M]) {
393 $this->scriptID = preg_replace('/^.*\\/(sysext|ext)\\//', 'ext/', $GLOBALS['TBE_MODULES']['_PATHS'][$temp_M] . 'index.php');
394 } else {
395 $this->scriptID = preg_replace('/^.*\\/(sysext|ext)\\//', 'ext/', \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix(PATH_thisScript));
396 }
397 if (TYPO3_mainDir != 'typo3/' && substr($this->scriptID, 0, strlen(TYPO3_mainDir)) == TYPO3_mainDir) {
398 // This fixes if TYPO3_mainDir has been changed so the script ids are STILL "typo3/..."
399 $this->scriptID = 'typo3/' . substr($this->scriptID, strlen(TYPO3_mainDir));
400 }
401 $this->bodyTagId = preg_replace('/[^A-Za-z0-9-]/', '-', $this->scriptID);
402 // Individual configuration per script? If so, make a recursive merge of the arrays:
403 if (is_array($GLOBALS['TBE_STYLES']['scriptIDindex'][$this->scriptID])) {
404 // Make copy
405 $ovr = $GLOBALS['TBE_STYLES']['scriptIDindex'][$this->scriptID];
406 // merge styles.
407 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($GLOBALS['TBE_STYLES'], $ovr);
408 // Have to unset - otherwise the second instantiation will do it again!
409 unset($GLOBALS['TBE_STYLES']['scriptIDindex'][$this->scriptID]);
410 }
411 // Main Stylesheets:
412 if ($GLOBALS['TBE_STYLES']['stylesheet']) {
413 $this->styleSheetFile = $GLOBALS['TBE_STYLES']['stylesheet'];
414 }
415 if ($GLOBALS['TBE_STYLES']['stylesheet2']) {
416 $this->styleSheetFile2 = $GLOBALS['TBE_STYLES']['stylesheet2'];
417 }
418 if ($GLOBALS['TBE_STYLES']['styleSheetFile_post']) {
419 $this->styleSheetFile_post = $GLOBALS['TBE_STYLES']['styleSheetFile_post'];
420 }
421 if ($GLOBALS['TBE_STYLES']['inDocStyles_TBEstyle']) {
422 $this->inDocStylesArray['TBEstyle'] = $GLOBALS['TBE_STYLES']['inDocStyles_TBEstyle'];
423 }
424 // include all stylesheets
425 foreach ($this->getSkinStylesheetDirectories() as $stylesheetDirectory) {
426 $this->addStylesheetDirectory($stylesheetDirectory);
427 }
428 // Background image
429 if ($GLOBALS['TBE_STYLES']['background']) {
430 $this->backGroundImage = $GLOBALS['TBE_STYLES']['background'];
431 }
432 }
433
434 /**
435 * Gets instance of PageRenderer configured with the current language, file references and debug settings
436 *
437 * @return \TYPO3\CMS\Core\Page\PageRenderer
438 */
439 public function getPageRenderer() {
440 if (!isset($this->pageRenderer)) {
441 $this->pageRenderer = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Page\PageRenderer::class);
442 $this->pageRenderer->setLanguage($GLOBALS['LANG']->lang);
443 $this->pageRenderer->addCssLibrary($GLOBALS['BACK_PATH'] . 'contrib/normalize/normalize.css', 'stylesheet', 'all', '', TRUE, TRUE);
444 $this->pageRenderer->enableConcatenateFiles();
445 $this->pageRenderer->enableCompressCss();
446 $this->pageRenderer->enableCompressJavascript();
447 // Add all JavaScript files defined in $this->jsFiles to the PageRenderer
448 foreach ($this->jsFilesNoConcatenation as $file) {
449 $this->pageRenderer->addJsFile(
450 $GLOBALS['BACK_PATH'] . $file,
451 'text/javascript',
452 TRUE,
453 FALSE,
454 '',
455 TRUE
456 );
457 }
458 // Add all JavaScript files defined in $this->jsFiles to the PageRenderer
459 foreach ($this->jsFiles as $file) {
460 $this->pageRenderer->addJsFile($GLOBALS['BACK_PATH'] . $file);
461 }
462 }
463 if ((int)$GLOBALS['TYPO3_CONF_VARS']['BE']['debug'] === 1) {
464 $this->pageRenderer->enableDebugMode();
465 }
466 return $this->pageRenderer;
467 }
468
469 /**
470 * Sets inclusion of StateProvider
471 *
472 * @return void
473 */
474 public function setExtDirectStateProvider() {
475 $this->extDirectStateProvider = TRUE;
476 }
477
478 /*****************************************
479 *
480 * EVALUATION FUNCTIONS
481 * Various centralized processing
482 *
483 *****************************************/
484 /**
485 * Makes click menu link (context sensitive menu)
486 * Returns $str (possibly an <|img> tag/icon) wrapped in a link which will activate the context sensitive menu for the record ($table/$uid) or file ($table = file)
487 * The link will load the top frame with the parameter "&item" which is the table,uid and listFr arguments imploded by "|": rawurlencode($table.'|'.$uid.'|'.$listFr)
488 *
489 * @param string $str String to be wrapped in link, typ. image tag.
490 * @param string $table Table name/File path. If the icon is for a database record, enter the tablename from $GLOBALS['TCA']. If a file then enter the absolute filepath
491 * @param int $uid If icon is for database record this is the UID for the record from $table
492 * @param bool $listFr Tells the top frame script that the link is coming from a "list" frame which means a frame from within the backend content frame.
493 * @param string $addParams Additional GET parameters for the link to the ClickMenu AJAX request
494 * @param string $enDisItems Enable / Disable click menu items. Example: "+new,view" will display ONLY these two items (and any spacers in between), "new,view" will display all BUT these two items.
495 * @param bool $returnTagParameters If set, will return only the onclick JavaScript, not the whole link.
496 * @return string The link-wrapped input string.
497 */
498 public function wrapClickMenuOnIcon($content, $table, $uid = 0, $listFr = TRUE, $addParams = '', $enDisItems = '', $returnTagParameters = FALSE) {
499 $tagParameters = array(
500 'class' => 't3-js-clickmenutrigger',
501 'data-table' => $table,
502 'data-uid' => (int)$uid !== 0 ? (int)$uid : '',
503 'data-listframe' => $listFr,
504 'data-iteminfo' => str_replace('+', '%2B', $enDisItems),
505 'data-parameters' => $addParams,
506 );
507
508 if ($returnTagParameters) {
509 return $tagParameters;
510 } else {
511 return '<a href="#" ' . GeneralUtility::implodeAttributes($tagParameters) . '>' . $content . '</a>';
512 }
513 }
514
515 /**
516 * Makes link to page $id in frontend (view page)
517 * Returns an magnifier-glass icon which links to the frontend index.php document for viewing the page with id $id
518 * $id must be a page-uid
519 * If the BE_USER has access to Web>List then a link to that module is shown as well (with return-url)
520 *
521 * @param int $id The page id
522 * @param string $backPath The current "BACK_PATH" (the back relative to the typo3/ directory)
523 * @param string $addParams Additional parameters for the image tag(s)
524 * @return string HTML string with linked icon(s)
525 */
526 public function viewPageIcon($id, $backPath, $addParams = 'hspace="3"') {
527 // If access to Web>List for user, then link to that module.
528 $str = BackendUtility::getListViewLink(array(
529 'id' => $id,
530 'returnUrl' => GeneralUtility::getIndpEnv('REQUEST_URI')
531 ), $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.showList'));
532 // Make link to view page
533 $str .= '<a href="#" onclick="' . htmlspecialchars(BackendUtility::viewOnClick($id, $backPath, BackendUtility::BEgetRootLine($id))) . '">' . '<img' . IconUtility::skinImg($backPath, 'gfx/zoom.gif', 'width="12" height="12"') . ' title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.showPage', TRUE) . '"' . ($addParams ? ' ' . trim($addParams) : '') . ' hspace="3" alt="" />' . '</a>';
534 return $str;
535 }
536
537 /**
538 * Returns a URL with a command to TYPO3 Core Engine (tce_db.php)
539 * See description of the API elsewhere.
540 *
541 * @param string $params is a set of GET params to send to tce_db.php. Example: "&cmd[tt_content][123][move]=456" or "&data[tt_content][123][hidden]=1&data[tt_content][123][title]=Hello%20World
542 * @param string $redirectUrl Redirect URL if any other that \TYPO3\CMS\Core\Utility\GeneralUtility::getIndpEnv('REQUEST_URI') is wished
543 * @return string URL to tce_db.php + parameters (backpath is taken from $this->backPath)
544 * @see \TYPO3\CMS\Backend\Utility\BackendUtility::editOnClick()
545 */
546 public function issueCommand($params, $redirectUrl = '') {
547 $redirectUrl = $redirectUrl ? $redirectUrl : GeneralUtility::getIndpEnv('REQUEST_URI');
548 $commandUrl = $this->backPath . 'tce_db.php?' . $params . '&redirect=' . ($redirectUrl == -1 ? '\'+T3_THIS_LOCATION+\'' : rawurlencode($redirectUrl)) . '&vC=' . rawurlencode($GLOBALS['BE_USER']->veriCode()) . BackendUtility::getUrlToken('tceAction') . '&prErr=1&uPT=1';
549 return $commandUrl;
550 }
551
552 /**
553 * Makes the header (icon+title) for a page (or other record). Used in most modules under Web>*
554 * $table and $row must be a tablename/record from that table
555 * $path will be shown as alt-text for the icon.
556 * The title will be truncated to 45 chars.
557 *
558 * @param string $table Table name
559 * @param array $row Record row
560 * @param string $path Alt text
561 * @param bool $noViewPageIcon Set $noViewPageIcon TRUE if you don't want a magnifier-icon for viewing the page in the frontend
562 * @param array $tWrap is an array with indexes 0 and 1 each representing HTML-tags (start/end) which will wrap the title
563 * @param bool $enableClickMenu If TRUE, render click menu code around icon image
564 * @return string HTML content
565 */
566 public function getHeader($table, $row, $path, $noViewPageIcon = FALSE, $tWrap = array('', ''), $enableClickMenu = TRUE) {
567 $viewPage = '';
568 if (is_array($row) && $row['uid']) {
569 $iconImgTag = IconUtility::getSpriteIconForRecord($table, $row, array('title' => htmlspecialchars($path)));
570 $title = strip_tags(BackendUtility::getRecordTitle($table, $row));
571 $viewPage = $noViewPageIcon ? '' : $this->viewPageIcon($row['uid'], $this->backPath, '');
572 if ($table == 'pages') {
573 $path .= ' - ' . BackendUtility::titleAttribForPages($row, '', 0);
574 }
575 } else {
576 $iconImgTag = IconUtility::getSpriteIcon('apps-pagetree-page-domain', array('title' => htmlspecialchars($path)));
577 $title = $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'];
578 }
579
580 if ($enableClickMenu) {
581 $iconImgTag = $this->wrapClickMenuOnIcon($iconImgTag, $table, $row['uid']);
582 }
583
584 return '<span class="typo3-moduleHeader">' . $iconImgTag . $viewPage . $tWrap[0] . htmlspecialchars(GeneralUtility::fixed_lgd_cs($title, 45)) . $tWrap[1] . '</span>';
585 }
586
587 /**
588 * Like ->getHeader() but for files and folders
589 * Returns the icon with the path of the file/folder set in the alt/title attribute. Shows the name after the icon.
590 *
591 * @param \TYPO3\CMS\Core\Resource\ResourceInterface $resource
592 * @param array $tWrap is an array with indexes 0 and 1 each representing HTML-tags (start/end) which will wrap the title
593 * @param bool $enableClickMenu If TRUE, render click menu code around icon image
594 * @return string
595 */
596 public function getResourceHeader(\TYPO3\CMS\Core\Resource\ResourceInterface $resource, $tWrap = array('', ''), $enableClickMenu = TRUE) {
597 $path = $resource->getStorage()->getName() . $resource->getParentFolder()->getIdentifier();
598 $iconImgTag = IconUtility::getSpriteIconForResource($resource, array('title' => htmlspecialchars($path)));
599
600 if ($enableClickMenu && ($resource instanceof \TYPO3\CMS\Core\Resource\File)) {
601 $metaData = $resource->_getMetaData();
602 $iconImgTag = $this->wrapClickMenuOnIcon($iconImgTag, 'sys_file_metadata', $metaData['uid']);
603 }
604
605 return '<span class="typo3-moduleHeader">' . $iconImgTag . $tWrap[0] . htmlspecialchars(GeneralUtility::fixed_lgd_cs($resource->getName(), 45)) . $tWrap[1] . '</span>';
606 }
607
608 /**
609 * Returns a linked shortcut-icon which will call the shortcut frame and set a shortcut there back to the calling page/module
610 *
611 * @param string $gvList Is the list of GET variables to store (if any)
612 * @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
613 * @param string $modName Module name string
614 * @param string $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.
615 * @return string HTML content
616 */
617 public function makeShortcutIcon($gvList, $setList, $modName, $motherModName = '') {
618 $storeUrl = $this->makeShortcutUrl($gvList, $setList);
619 $pathInfo = parse_url(GeneralUtility::getIndpEnv('REQUEST_URI'));
620 // Add the module identifier automatically if typo3/mod.php is used:
621 if (preg_match('/typo3\\/mod\\.php$/', $pathInfo['path']) && isset($GLOBALS['TBE_MODULES']['_PATHS'][$modName])) {
622 $storeUrl = '&M=' . $modName . $storeUrl;
623 }
624 if ((int)$motherModName === 1) {
625 $mMN = '&motherModName=\'+top.currentModuleLoaded+\'';
626 } elseif ($motherModName) {
627 $mMN = '&motherModName=' . rawurlencode($motherModName);
628 } else {
629 $mMN = '';
630 }
631 $confirmationText = GeneralUtility::quoteJSvalue($GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.makeBookmark'));
632 $onClick = 'top.TYPO3.ShortcutMenu.createShortcut(\'' . rawurlencode($modName) . '\', ' . '\'' . rawurlencode(($pathInfo['path'] . '?' . $storeUrl)) . $mMN . '\', ' . $confirmationText . ');return false;';
633 return '<a href="#" onclick="' . htmlspecialchars($onClick) . '" title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.makeBookmark', TRUE) . '">' . IconUtility::getSpriteIcon('actions-system-shortcut-new') . '</a>';
634 }
635
636 /**
637 * MAKE url for storing
638 * Internal func
639 *
640 * @param string $gvList Is the list of GET variables to store (if any)
641 * @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
642 * @return string
643 * @access private
644 * @see makeShortcutIcon()
645 */
646 public function makeShortcutUrl($gvList, $setList) {
647 $GET = GeneralUtility::_GET();
648 $storeArray = array_merge(GeneralUtility::compileSelectedGetVarsFromArray($gvList, $GET), array('SET' => GeneralUtility::compileSelectedGetVarsFromArray($setList, (array)$GLOBALS['SOBE']->MOD_SETTINGS)));
649 $storeUrl = GeneralUtility::implodeArrayForUrl('', $storeArray);
650 return $storeUrl;
651 }
652
653 /**
654 * Returns <input> attributes to set the width of an text-type input field.
655 * For client browsers with no CSS support the cols/size attribute is returned.
656 * For CSS compliant browsers (recommended) a ' style="width: ...px;"' is returned.
657 *
658 * @param int $size A relative number which multiplied with approx. 10 will lead to the width in pixels
659 * @param bool $textarea A flag you can set for textareas - DEPRECATED as there is no difference any more between the two
660 * @param string $styleOverride A string which will be returned as attribute-value for style="" instead of the calculated width (if CSS is enabled)
661 * @return string Tag attributes for an <input> tag (regarding width)
662 */
663 public function formWidth($size = 48, $textarea = FALSE, $styleOverride = '') {
664 return ' style="' . ($styleOverride ?: 'width:' . ceil($size * 9.58) . 'px;') . '"';
665 }
666
667 /**
668 * This function is dedicated to textareas, which has the wrapping on/off option to observe.
669 * EXAMPLE:
670 * <textarea rows="10" wrap="off" '.$GLOBALS["TBE_TEMPLATE"]->formWidthText(48, "", "off").'>
671 * or
672 * <textarea rows="10" wrap="virtual" '.$GLOBALS["TBE_TEMPLATE"]->formWidthText(48, "", "virtual").'>
673 *
674 * @param int $size A relative number which multiplied with approx. 10 will lead to the width in pixels
675 * @param string $styleOverride A string which will be returned as attribute-value for style="" instead of the calculated width (if CSS is enabled)
676 * @param string $wrap Pass on the wrap-attribute value you use in your <textarea>! This will be used to make sure that some browsers will detect wrapping alright.
677 * @return string Tag attributes for an <input> tag (regarding width)
678 * @see formWidth()
679 * @deprecated since TYPO3 CMS 6.2, remove two versions later, as this is function is not needed anymore, use formWidth()
680 */
681 public function formWidthText($size = 48, $styleOverride = '', $wrap = '') {
682 GeneralUtility::logDeprecatedFunction();
683 return $this->formWidth($size, TRUE, $styleOverride);
684 }
685
686 /**
687 * Returns JavaScript variables setting the returnUrl and thisScript location for use by JavaScript on the page.
688 * Used in fx. db_list.php (Web>List)
689 *
690 * @param string $thisLocation URL to "this location" / current script
691 * @return string Urls are returned as JavaScript variables T3_RETURN_URL and T3_THIS_LOCATION
692 * @see typo3/db_list.php
693 */
694 public function redirectUrls($thisLocation = '') {
695 $thisLocation = $thisLocation ? $thisLocation : GeneralUtility::linkThisScript(array(
696 'CB' => '',
697 'SET' => '',
698 'cmd' => '',
699 'popViewId' => ''
700 ));
701 $out = '
702 var T3_RETURN_URL = \'' . str_replace('%20', '', rawurlencode(GeneralUtility::sanitizeLocalUrl(GeneralUtility::_GP('returnUrl')))) . '\';
703 var T3_THIS_LOCATION = \'' . str_replace('%20', '', rawurlencode($thisLocation)) . '\';
704 ';
705 return $out;
706 }
707
708 /**
709 * Returns a formatted string of $tstamp
710 * Uses $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'] and $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'] to format date and time
711 *
712 * @param int $tstamp UNIX timestamp, seconds since 1970
713 * @param int $type How much data to show: $type = 1: hhmm, $type = 10: ddmmmyy
714 * @return string Formatted timestamp
715 * @deprecated since TYPO3 CMS 7, will be removed in TYPO3 CMS 8, use the corresponding methods in BackendUtility
716 */
717 public function formatTime($tstamp, $type) {
718 GeneralUtility::logDeprecatedFunction();
719 $dateStr = '';
720 switch ($type) {
721 case 1:
722 $dateStr = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $tstamp);
723 break;
724 case 10:
725 $dateStr = date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'], $tstamp);
726 break;
727 }
728 return $dateStr;
729 }
730
731 /**
732 * Returns script parsetime IF ->parseTimeFlag is set and user is "admin"
733 * Automatically outputted in page end
734 *
735 * @return string HTML formated with <p>-tags
736 */
737 public function parseTime() {
738 if ($this->parseTimeFlag && $GLOBALS['BE_USER']->isAdmin()) {
739 return '<p>(ParseTime: ' . (GeneralUtility::milliseconds() - $GLOBALS['PARSETIME_START']) . ' ms</p>
740 <p>REQUEST_URI-length: ' . strlen(GeneralUtility::getIndpEnv('REQUEST_URI')) . ')</p>';
741 }
742 }
743
744 /**
745 * Defines whether to use the X-UA-Compatible meta tag.
746 *
747 * @param bool $useCompatibilityTag Whether to use the tag
748 * @return void
749 */
750 public function useCompatibilityTag($useCompatibilityTag = TRUE) {
751 $this->useCompatibilityTag = (bool)$useCompatibilityTag;
752 }
753
754 /*****************************************
755 *
756 * PAGE BUILDING FUNCTIONS.
757 * Use this to build the HTML of your backend modules
758 *
759 *****************************************/
760 /**
761 * Returns page start
762 * This includes the proper header with charset, title, meta tag and beginning body-tag.
763 *
764 * @param string $title HTML Page title for the header
765 * @param bool $includeCsh flag for including CSH
766 * @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)
767 * @see endPage()
768 */
769 public function startPage($title, $includeCsh = TRUE) {
770 // hook pre start page
771 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['preStartPageHook'])) {
772 $preStartPageHook = &$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['preStartPageHook'];
773 if (is_array($preStartPageHook)) {
774 $hookParameters = array(
775 'title' => &$title
776 );
777 foreach ($preStartPageHook as $hookFunction) {
778 GeneralUtility::callUserFunction($hookFunction, $hookParameters, $this);
779 }
780 }
781 }
782 $this->pageRenderer->backPath = $this->backPath;
783 // alternative template for Header and Footer
784 if ($this->pageHeaderFooterTemplateFile) {
785 $file = GeneralUtility::getFileAbsFileName($this->pageHeaderFooterTemplateFile, TRUE);
786 if ($file) {
787 $this->pageRenderer->setTemplateFile($file);
788 }
789 }
790
791
792
793 // Disable rendering of XHTML tags
794 $this->pageRenderer->setRenderXhtml(FALSE);
795
796 $this->pageRenderer->setHtmlTag('<html>');
797 // This loads the tabulator-in-textarea feature. It automatically modifies
798 // every textarea which is found.
799 if (!$GLOBALS['BE_USER']->uc['disableTabInTextarea']) {
800 $this->pageRenderer->addJsFile($this->backPath . 'sysext/backend/Resources/Public/JavaScript/tab.js');
801 }
802 // Include the JS for the Context Sensitive Help
803 if ($includeCsh) {
804 $this->loadCshJavascript();
805 }
806
807 $headerStart = '<!DOCTYPE html>';
808 $this->pageRenderer->setXmlPrologAndDocType($headerStart);
809 $this->pageRenderer->setHeadTag('<head>' . LF . '<!-- TYPO3 Script ID: ' . htmlspecialchars($this->scriptID) . ' -->');
810 header('Content-Type:text/html;charset=utf-8');
811 $this->pageRenderer->setCharSet('utf-8');
812 $this->pageRenderer->addMetaTag($this->generator());
813 $this->pageRenderer->addMetaTag('<meta name="robots" content="noindex,follow" />');
814 $this->pageRenderer->setFavIcon($this->getBackendFavicon());
815 if ($this->useCompatibilityTag) {
816 $this->pageRenderer->addMetaTag($this->xUaCompatible($this->xUaCompatibilityVersion));
817 }
818 $this->pageRenderer->setTitle($title);
819 // add docstyles
820 $this->docStyle();
821 if ($this->extDirectStateProvider) {
822 $this->pageRenderer->addJsFile($this->backPath . 'sysext/backend/Resources/Public/JavaScript/ExtDirect.StateProvider.js');
823 }
824 // Add jsCode for overriding the console with a debug panel connection
825 $this->pageRenderer->addJsInlineCode('consoleOverrideWithDebugPanel', 'if (typeof top.Ext === "object") {
826 top.Ext.onReady(function() {
827 if (typeof console === "undefined") {
828 if (top && top.TYPO3 && top.TYPO3.Backend && top.TYPO3.Backend.DebugConsole) {
829 console = top.TYPO3.Backend.DebugConsole;
830 } else {
831 console = {
832 log: Ext.log,
833 info: Ext.log,
834 warn: Ext.log,
835 error: Ext.log
836 };
837 }
838 }
839 });
840 }
841 ', FALSE);
842 $this->pageRenderer->addHeaderData($this->JScode);
843 foreach ($this->JScodeArray as $name => $code) {
844 $this->pageRenderer->addJsInlineCode($name, $code, FALSE);
845 }
846 if (count($this->JScodeLibArray)) {
847 GeneralUtility::deprecationLog('DocumentTemplate->JScodeLibArray is deprecated since TYPO3 CMS 7. Use the functionality within pageRenderer directly');
848 foreach ($this->JScodeLibArray as $library) {
849 $this->pageRenderer->addHeaderData($library);
850 }
851 }
852 if ($this->extJScode) {
853 $this->pageRenderer->addExtOnReadyCode($this->extJScode);
854 }
855
856 // Load jquery and twbs JS libraries on every backend request
857 $this->pageRenderer->loadJquery();
858 // Note: please do not reference "twbs" outside of the TYPO3 Core (not in your own extensions)
859 // as this is preliminary as long as twbs does not support AMD modules
860 // this logic will be changed once twbs 4 is included
861 $this->pageRenderer->addJsFile($this->backPath . 'contrib/twbs/bootstrap.min.js');
862
863 // hook for additional headerData
864 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['preHeaderRenderHook'])) {
865 $preHeaderRenderHook = &$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['preHeaderRenderHook'];
866 if (is_array($preHeaderRenderHook)) {
867 $hookParameters = array(
868 'pageRenderer' => &$this->pageRenderer
869 );
870 foreach ($preHeaderRenderHook as $hookFunction) {
871 GeneralUtility::callUserFunction($hookFunction, $hookParameters, $this);
872 }
873 }
874 }
875 // Construct page header.
876 $str = $this->pageRenderer->render(PageRenderer::PART_HEADER);
877 $this->JScode = ($this->extJScode = '');
878 $this->JScodeArray = array();
879 $this->endOfPageJsBlock = $this->pageRenderer->render(PageRenderer::PART_FOOTER);
880 $str .= $this->docBodyTagBegin() . ($this->divClass ? '
881
882 <!-- Wrapping DIV-section for whole page BEGIN -->
883 <div class="' . $this->divClass . '">
884 ' : '') . trim($this->form);
885 return $str;
886 }
887
888 /**
889 * Returns page end; This includes finishing form, div, body and html tags.
890 *
891 * @return string The HTML end of a page
892 * @see startPage()
893 */
894 public function endPage() {
895 $str = $this->sectionEnd() . $this->postCode . $this->wrapScriptTags(BackendUtility::getUpdateSignalCode()) . $this->parseTime() . ($this->form ? '
896 </form>' : '');
897 // If something is in buffer like debug, put it to end of page
898 if (ob_get_contents()) {
899 $str .= ob_get_clean();
900 if (!headers_sent()) {
901 header('Content-Encoding: None');
902 }
903 }
904 $str .= ($this->divClass ? '
905
906 <!-- Wrapping DIV-section for whole page END -->
907 </div>' : '') . $this->endOfPageJsBlock;
908
909 // Logging: Can't find better place to put it:
910 if (TYPO3_DLOG) {
911 GeneralUtility::devLog('END of BACKEND session', 'TYPO3\\CMS\\Backend\\Template\\DocumentTemplate', 0, array('_FLUSH' => TRUE));
912 }
913 return $str;
914 }
915
916 /**
917 * Shortcut for render the complete page of a module
918 *
919 * @param string $title page title
920 * @param string $content page content
921 * @param bool $includeCsh flag for including csh code
922 * @return string complete page
923 */
924 public function render($title, $content, $includeCsh = TRUE) {
925 $pageContent = $this->startPage($title, $includeCsh);
926 $pageContent .= $content;
927 $pageContent .= $this->endPage();
928 return $this->insertStylesAndJS($pageContent);
929 }
930
931 /**
932 * Returns the header-bar in the top of most backend modules
933 * Closes section if open.
934 *
935 * @param string $text The text string for the header
936 * @return string HTML content
937 */
938 public function header($text) {
939 $str = '
940
941 <!-- MAIN Header in page top -->
942 <h1>' . htmlspecialchars($text) . '</h1>
943 ';
944 return $this->sectionEnd() . $str;
945 }
946
947 /**
948 * Begins an output section and sets header and content
949 *
950 * @param string $label The header
951 * @param string $text The HTML-content
952 * @param bool $nostrtoupper A flag that will prevent the header from being converted to uppercase
953 * @param bool $sH Defines the type of header (if set, "<h3>" rather than the default "h4")
954 * @param int $type The number of an icon to show with the header (see the icon-function). -1,1,2,3
955 * @param bool $allowHTMLinHeader If set, HTML tags are allowed in $label (otherwise this value is by default htmlspecialchars()'ed)
956 * @return string HTML content
957 * @see icons(), sectionHeader()
958 */
959 public function section($label, $text, $nostrtoupper = FALSE, $sH = FALSE, $type = 0, $allowHTMLinHeader = FALSE) {
960 $str = '';
961 // Setting header
962 if ($label) {
963 if (!$allowHTMLinHeader) {
964 $label = htmlspecialchars($label);
965 }
966 $str .= $this->sectionHeader($this->icons($type) . $label, $sH, $nostrtoupper ? '' : ' class="uppercase"');
967 }
968 // Setting content
969 $str .= '
970
971 <!-- Section content -->
972 ' . $text;
973 return $this->sectionBegin() . $str;
974 }
975
976 /**
977 * Inserts a divider image
978 * Ends a section (if open) before inserting the image
979 *
980 * @param int $dist The margin-top/-bottom of the <hr> ruler.
981 * @return string HTML content
982 */
983 public function divider($dist) {
984 $dist = (int)$dist;
985 $str = '
986
987 <!-- DIVIDER -->
988 <hr style="margin-top: ' . $dist . 'px; margin-bottom: ' . $dist . 'px;" />
989 ';
990 return $this->sectionEnd() . $str;
991 }
992
993 /**
994 * Returns a blank <div>-section with a height
995 *
996 * @param int $dist Padding-top for the div-section (should be margin-top but konqueror (3.1) doesn't like it :-(
997 * @return string HTML content
998 */
999 public function spacer($dist) {
1000 if ($dist > 0) {
1001 return '
1002
1003 <!-- Spacer element -->
1004 <div style="padding-top: ' . (int)$dist . 'px;"></div>
1005 ';
1006 }
1007 }
1008
1009 /**
1010 * Make a section header.
1011 * Begins a section if not already open.
1012 *
1013 * @param string $label The label between the <h3> or <h4> tags. (Allows HTML)
1014 * @param bool $sH If set, <h3> is used, otherwise <h4>
1015 * @param string $addAttrib Additional attributes to h-tag, eg. ' class=""'
1016 * @return string HTML content
1017 */
1018 public function sectionHeader($label, $sH = FALSE, $addAttrib = '') {
1019 $tag = $sH ? 'h2' : 'h3';
1020 if ($addAttrib && $addAttrib[0] !== ' ') {
1021 $addAttrib = ' ' . $addAttrib;
1022 }
1023 $str = '
1024
1025 <!-- Section header -->
1026 <' . $tag . $addAttrib . '>' . $label . '</' . $tag . '>
1027 ';
1028 return $this->sectionBegin() . $str;
1029 }
1030
1031 /**
1032 * Begins an output section.
1033 * Returns the <div>-begin tag AND sets the ->sectionFlag TRUE (if the ->sectionFlag is not already set!)
1034 * 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!
1035 *
1036 * @return string HTML content
1037 */
1038 public function sectionBegin() {
1039 if (!$this->sectionFlag) {
1040 $this->sectionFlag = 1;
1041 $str = '
1042
1043 <!-- ***********************
1044 Begin output section.
1045 *********************** -->
1046 <div>
1047 ';
1048 return $str;
1049 } else {
1050 return '';
1051 }
1052 }
1053
1054 /**
1055 * Ends and output section
1056 * Returns the </div>-end tag AND clears the ->sectionFlag (but does so only IF the sectionFlag is set - that is a section is 'open')
1057 * See sectionBegin() also.
1058 *
1059 * @return string HTML content
1060 */
1061 public function sectionEnd() {
1062 if ($this->sectionFlag) {
1063 $this->sectionFlag = 0;
1064 return '
1065 </div>
1066 <!-- *********************
1067 End output section.
1068 ********************* -->
1069 ';
1070 } else {
1071 return '';
1072 }
1073 }
1074
1075 /**
1076 * If a form-tag is defined in ->form then and end-tag for that <form> element is outputted
1077 * Further a JavaScript section is outputted which will update the top.busy session-expiry object (unless $this->endJS is set to FALSE)
1078 *
1079 * @return string HTML content (<script> tag section)
1080 * @deprecated since TYPO3 CMS 7, will be removed in CMS 8, nothing there to output anymore
1081 */
1082 public function endPageJS() {
1083 return '';
1084 }
1085
1086 /**
1087 * Creates the bodyTag.
1088 * You can add to the bodyTag by $this->bodyTagAdditions
1089 *
1090 * @return string HTML body tag
1091 */
1092 public function docBodyTagBegin() {
1093 return '<body ' . trim(($this->bodyTagAdditions . ($this->bodyTagId ? ' id="' . $this->bodyTagId . '"' : ''))) . '>';
1094 }
1095
1096 /**
1097 * Outputting document style
1098 *
1099 * @return string HTML style section/link tags
1100 */
1101 public function docStyle() {
1102 // Request background image:
1103 if ($this->backGroundImage) {
1104 $this->inDocStylesArray[] = ' BODY { background-image: url(' . $this->backPath . $this->backGroundImage . '); }';
1105 }
1106 // Implode it all:
1107 $inDocStyles = implode(LF, $this->inDocStylesArray);
1108
1109 // Reset styles so they won't be added again in insertStylesAndJS()
1110 $this->inDocStylesArray = array();
1111
1112 if ($this->styleSheetFile) {
1113 $this->pageRenderer->addCssFile($this->backPath . $this->styleSheetFile);
1114 }
1115 if ($this->styleSheetFile2) {
1116 $this->pageRenderer->addCssFile($this->backPath . $this->styleSheetFile2);
1117 }
1118 $this->pageRenderer->addCssInlineBlock('inDocStyles', $inDocStyles . LF . '/*###POSTCSSMARKER###*/');
1119 if ($this->styleSheetFile_post) {
1120 $this->pageRenderer->addCssFile($this->backPath . $this->styleSheetFile_post);
1121 }
1122 }
1123
1124 /**
1125 * Insert additional style sheet link
1126 *
1127 * @param string $key some key identifying the style sheet
1128 * @param string $href uri to the style sheet file
1129 * @param string $title value for the title attribute of the link element
1130 * @param string $relation value for the rel attribute of the link element
1131 * @return void
1132 */
1133 public function addStyleSheet($key, $href, $title = '', $relation = 'stylesheet') {
1134 if (strpos($href, '://') !== FALSE || $href[0] === '/') {
1135 $file = $href;
1136 } else {
1137 $file = $this->backPath . $href;
1138 }
1139 $this->pageRenderer->addCssFile($file, $relation, 'screen', $title);
1140 }
1141
1142 /**
1143 * Add all *.css files of the directory $path to the stylesheets
1144 *
1145 * @param string $path directory to add
1146 * @return void
1147 */
1148 public function addStyleSheetDirectory($path) {
1149 // Calculation needed, when TYPO3 source is used via a symlink
1150 // absolute path to the stylesheets
1151 $filePath = dirname(GeneralUtility::getIndpEnv('SCRIPT_FILENAME')) . '/' . $GLOBALS['BACK_PATH'] . $path;
1152 // Clean the path
1153 $resolvedPath = GeneralUtility::resolveBackPath($filePath);
1154 // Read all files in directory and sort them alphabetically
1155 $files = GeneralUtility::getFilesInDir($resolvedPath, 'css', FALSE, 1);
1156 foreach ($files as $file) {
1157 $this->pageRenderer->addCssFile($GLOBALS['BACK_PATH'] . $path . $file, 'stylesheet', 'all');
1158 }
1159 }
1160
1161 /**
1162 * Insert post rendering document style into already rendered content
1163 * This is needed for extobjbase
1164 *
1165 * @param string $content style-content to insert.
1166 * @return string content with inserted styles
1167 */
1168 public function insertStylesAndJS($content) {
1169 $styles = LF . implode(LF, $this->inDocStylesArray);
1170 $content = str_replace('/*###POSTCSSMARKER###*/', $styles, $content);
1171
1172 // Insert accumulated JS
1173 $jscode = $this->JScode . LF . $this->wrapScriptTags(implode(LF, $this->JScodeArray));
1174 $content = str_replace('<!--###POSTJSMARKER###-->', $jscode, $content);
1175 return $content;
1176 }
1177
1178 /**
1179 * Returns an array of all stylesheet directories belonging to core and skins
1180 *
1181 * @return array Stylesheet directories
1182 */
1183 public function getSkinStylesheetDirectories() {
1184 $stylesheetDirectories = array();
1185 // Add default core stylesheets
1186 foreach ($this->stylesheetsCore as $stylesheetDir) {
1187 $stylesheetDirectories[] = $stylesheetDir;
1188 }
1189 // Stylesheets from skins
1190 // merge default css directories ($this->stylesheetsSkin) with additional ones and include them
1191 if (is_array($GLOBALS['TBE_STYLES']['skins'])) {
1192 // loop over all registered skins
1193 foreach ($GLOBALS['TBE_STYLES']['skins'] as $skinExtKey => $skin) {
1194 $skinStylesheetDirs = $this->stylesheetsSkins;
1195 // Skins can add custom stylesheetDirectories using
1196 // $GLOBALS['TBE_STYLES']['skins'][$_EXTKEY]['stylesheetDirectories']
1197 if (is_array($skin['stylesheetDirectories'])) {
1198 $skinStylesheetDirs = array_merge($skinStylesheetDirs, $skin['stylesheetDirectories']);
1199 }
1200 // Add all registered directories
1201 foreach ($skinStylesheetDirs as $stylesheetDir) {
1202 // for EXT:myskin/stylesheets/ syntax
1203 if (substr($stylesheetDir, 0, 4) === 'EXT:') {
1204 list($extKey, $path) = explode('/', substr($stylesheetDir, 4), 2);
1205 if (!empty($extKey) && ExtensionManagementUtility::isLoaded($extKey) && !empty($path)) {
1206 $stylesheetDirectories[] = ExtensionManagementUtility::extRelPath($extKey) . $path;
1207 }
1208 } else {
1209 // For relative paths
1210 $stylesheetDirectories[] = ExtensionManagementUtility::extRelPath($skinExtKey) . $stylesheetDir;
1211 }
1212 }
1213 }
1214 }
1215 return $stylesheetDirectories;
1216 }
1217
1218 /**
1219 * Returns generator meta tag
1220 *
1221 * @return string <meta> tag with name "generator
1222 */
1223 public function generator() {
1224 $str = 'TYPO3 ' . TYPO3_branch . ', ' . TYPO3_URL_GENERAL . ', &#169; Kasper Sk&#229;rh&#248;j ' . TYPO3_copyright_year . ', extensions are copyright of their respective owners.';
1225 return '<meta name="generator" content="' . $str . '" />';
1226 }
1227
1228 /**
1229 * Returns X-UA-Compatible meta tag
1230 *
1231 * @param string $content Content of the compatible tag (default: IE-8)
1232 * @return string <meta http-equiv="X-UA-Compatible" content="???" />
1233 */
1234 public function xUaCompatible($content = 'IE=8') {
1235 return '<meta http-equiv="X-UA-Compatible" content="' . $content . '" />';
1236 }
1237
1238 /*****************************************
1239 *
1240 * OTHER ELEMENTS
1241 * Tables, buttons, formatting dimmed/red strings
1242 *
1243 ******************************************/
1244 /**
1245 * Returns an image-tag with an 18x16 icon of the following types:
1246 *
1247 * $type:
1248 * -1: OK icon (Check-mark)
1249 * 1: Notice (Speach-bubble)
1250 * 2: Warning (Yellow triangle)
1251 * 3: Fatal error (Red stop sign)
1252 *
1253 * @param int $type See description
1254 * @param string $styleAttribValue Value for style attribute
1255 * @return string HTML image tag (if applicable)
1256 */
1257 public function icons($type, $styleAttribValue = '') {
1258 switch ($type) {
1259 case self::STATUS_ICON_ERROR:
1260 $icon = 'status-dialog-error';
1261 break;
1262 case self::STATUS_ICON_WARNING:
1263 $icon = 'status-dialog-warning';
1264 break;
1265 case self::STATUS_ICON_NOTIFICATION:
1266 $icon = 'status-dialog-notification';
1267 break;
1268 case self::STATUS_ICON_OK:
1269 $icon = 'status-dialog-ok';
1270 break;
1271 default:
1272 // Do nothing
1273 }
1274 if ($icon) {
1275 return IconUtility::getSpriteIcon($icon);
1276 }
1277 }
1278
1279 /**
1280 * Returns an <input> button with the $onClick action and $label
1281 *
1282 * @param string $onClick The value of the onclick attribute of the input tag (submit type)
1283 * @param string $label The label for the button (which will be htmlspecialchar'ed)
1284 * @return string A <input> tag of the type "submit
1285 */
1286 public function t3Button($onClick, $label) {
1287 $button = '<input type="submit" onclick="' . htmlspecialchars($onClick) . '; return false;" value="' . htmlspecialchars($label) . '" />';
1288 return $button;
1289 }
1290
1291 /**
1292 * Dimmed-fontwrap. Returns the string wrapped in a <span>-tag defining the color to be gray/dimmed
1293 *
1294 * @param string $string Input string
1295 * @return string Output string
1296 */
1297 public function dfw($string) {
1298 return '<span class="typo3-dimmed">' . $string . '</span>';
1299 }
1300
1301 /**
1302 * red-fontwrap. Returns the string wrapped in a <span>-tag defining the color to be red
1303 *
1304 * @param string $string Input string
1305 * @return string Output string
1306 */
1307 public function rfw($string) {
1308 return '<span class="typo3-red">' . $string . '</span>';
1309 }
1310
1311 /**
1312 * Returns string wrapped in CDATA "tags" for XML / XHTML (wrap content of <script> and <style> sections in those!)
1313 *
1314 * @param string $string Input string
1315 * @return string Output string
1316 */
1317 public function wrapInCData($string) {
1318 $string = '/*<![CDATA[*/' . $string . '/*]]>*/';
1319 return $string;
1320 }
1321
1322 /**
1323 * Wraps the input string in script tags.
1324 * Automatic re-identing of the JS code is done by using the first line as ident reference.
1325 * This is nice for identing JS code with PHP code on the same level.
1326 *
1327 * @param string $string Input string
1328 * @param bool $linebreak Wrap script element in linebreaks? Default is TRUE.
1329 * @return string Output string
1330 */
1331 public function wrapScriptTags($string, $linebreak = TRUE) {
1332 if (trim($string)) {
1333 // <script wrapped in nl?
1334 $cr = $linebreak ? LF : '';
1335 // Remove nl from the beginning
1336 $string = preg_replace('/^\\n+/', '', $string);
1337 // Re-ident to one tab using the first line as reference
1338 $match = array();
1339 if (preg_match('/^(\\t+)/', $string, $match)) {
1340 $string = str_replace($match[1], TAB, $string);
1341 }
1342 $string = $cr . '<script type="text/javascript">
1343 /*<![CDATA[*/
1344 ' . $string . '
1345 /*]]>*/
1346 </script>' . $cr;
1347 }
1348 return trim($string);
1349 }
1350
1351 // These vars defines the layout for the table produced by the table() function.
1352 // You can override these values from outside if you like.
1353 public $tableLayout = array(
1354 'defRow' => array(
1355 'defCol' => array('<td valign="top">', '</td>')
1356 )
1357 );
1358
1359 public $table_TR = '<tr>';
1360
1361 public $table_TABLE = '<table border="0" cellspacing="0" cellpadding="0" class="typo3-dblist" id="typo3-tmpltable">';
1362
1363 /**
1364 * Returns a table based on the input $data
1365 *
1366 * @param array $data Multidim array with first levels = rows, second levels = cells
1367 * @param array $layout If set, then this provides an alternative layout array instead of $this->tableLayout
1368 * @return string The HTML table.
1369 * @internal
1370 */
1371 public function table($data, $layout = NULL) {
1372 $result = '';
1373 if (is_array($data)) {
1374 $tableLayout = is_array($layout) ? $layout : $this->tableLayout;
1375 $rowCount = 0;
1376 foreach ($data as $tableRow) {
1377 if ($rowCount % 2) {
1378 $layout = is_array($tableLayout['defRowOdd']) ? $tableLayout['defRowOdd'] : $tableLayout['defRow'];
1379 } else {
1380 $layout = is_array($tableLayout['defRowEven']) ? $tableLayout['defRowEven'] : $tableLayout['defRow'];
1381 }
1382 $rowLayout = is_array($tableLayout[$rowCount]) ? $tableLayout[$rowCount] : $layout;
1383 $rowResult = '';
1384 if (is_array($tableRow)) {
1385 $cellCount = 0;
1386 foreach ($tableRow as $tableCell) {
1387 $cellWrap = is_array($layout[$cellCount]) ? $layout[$cellCount] : $layout['defCol'];
1388 $cellWrap = is_array($rowLayout['defCol']) ? $rowLayout['defCol'] : $cellWrap;
1389 $cellWrap = is_array($rowLayout[$cellCount]) ? $rowLayout[$cellCount] : $cellWrap;
1390 $rowResult .= $cellWrap[0] . $tableCell . $cellWrap[1];
1391 $cellCount++;
1392 }
1393 }
1394 $rowWrap = is_array($layout['tr']) ? $layout['tr'] : array($this->table_TR, '</tr>');
1395 $rowWrap = is_array($rowLayout['tr']) ? $rowLayout['tr'] : $rowWrap;
1396 $result .= $rowWrap[0] . $rowResult . $rowWrap[1];
1397 $rowCount++;
1398 }
1399 $tableWrap = is_array($tableLayout['table']) ? $tableLayout['table'] : array($this->table_TABLE, '</table>');
1400 $result = $tableWrap[0] . $result . $tableWrap[1];
1401 }
1402 return $result;
1403 }
1404
1405 /**
1406 * Constructs a table with content from the $arr1, $arr2 and $arr3.
1407 *
1408 * @param array $arr1 Menu elements on first level
1409 * @param array $arr2 Secondary items
1410 * @param array $arr3 Third-level items
1411 * @return string HTML content, <table>...</table>
1412 * @deprecated since TYPO3 CMS 7, will be removed in CMS 8
1413 */
1414 public function menuTable($arr1, $arr2 = array(), $arr3 = array()) {
1415 GeneralUtility::logDeprecatedFunction();
1416 $rows = max(array(count($arr1), count($arr2), count($arr3)));
1417 $menu = '
1418 <table border="0" cellpadding="0" cellspacing="0" id="typo3-tablemenu">';
1419 for ($a = 0; $a < $rows; $a++) {
1420 $menu .= '<tr>';
1421 $cls = array();
1422 $valign = 'middle';
1423 $cls[] = '<td valign="' . $valign . '">' . $arr1[$a][0] . '</td><td>' . $arr1[$a][1] . '</td>';
1424 if (count($arr2)) {
1425 $cls[] = '<td valign="' . $valign . '">' . $arr2[$a][0] . '</td><td>' . $arr2[$a][1] . '</td>';
1426 if (count($arr3)) {
1427 $cls[] = '<td valign="' . $valign . '">' . $arr3[$a][0] . '</td><td>' . $arr3[$a][1] . '</td>';
1428 }
1429 }
1430 $menu .= implode($cls, '<td>&nbsp;&nbsp;</td>');
1431 $menu .= '</tr>';
1432 }
1433 $menu .= '
1434 </table>
1435 ';
1436 return $menu;
1437 }
1438
1439 /**
1440 * Returns a one-row/two-celled table with $content and $menu side by side.
1441 * The table is a 100% width table and each cell is aligned left / right
1442 *
1443 * @param string $content Content cell content (left)
1444 * @param string $menu Menu cell content (right)
1445 * @return string HTML output
1446 */
1447 public function funcMenu($content, $menu) {
1448 return '
1449 <table border="0" cellpadding="0" cellspacing="0" width="100%" id="typo3-funcmenu">
1450 <tr>
1451 <td valign="top" nowrap="nowrap">' . $content . '</td>
1452 <td valign="top" align="right" nowrap="nowrap">' . $menu . '</td>
1453 </tr>
1454 </table>';
1455 }
1456
1457 /**
1458 * Includes a javascript library that exists in the core /typo3/ directory. The
1459 * backpath is automatically applied
1460 *
1461 * @param string $lib: Library name. Call it with the full path like "contrib/prototype/prototype.js" to load it
1462 * @return void
1463 */
1464 public function loadJavascriptLib($lib) {
1465 $this->pageRenderer->addJsFile($this->backPath . $lib);
1466 }
1467
1468 /**
1469 * Includes the necessary Javascript function for the clickmenu (context sensitive menus) in the document
1470 *
1471 * @return void
1472 */
1473 public function getContextMenuCode() {
1474 $this->pageRenderer->loadJquery();
1475 $this->pageRenderer->loadRequireJsModule('TYPO3/CMS/Backend/ClickMenu');
1476 }
1477
1478 /**
1479 * Includes the necessary javascript file (tree.js) for use on pages which have the
1480 * drag and drop functionality (usually pages and folder display trees)
1481 *
1482 * @param string $table indicator of which table the drag and drop function should work on (pages or folders)
1483 * @return void
1484 */
1485 public function getDragDropCode($table) {
1486 $this->getContextMenuCode();
1487 $this->pageRenderer->loadPrototype();
1488 $this->loadJavascriptLib('sysext/backend/Resources/Public/JavaScript/common.js');
1489 $this->loadJavascriptLib('js/tree.js');
1490 // Setting prefs for drag & drop
1491 $this->JScodeArray['dragdrop'] = '
1492 DragDrop.backPath = "' . GeneralUtility::shortMD5('|' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']) . '";
1493 DragDrop.table = "' . $table . '";
1494 ';
1495 }
1496
1497 /**
1498 * This loads everything needed for the Context Sensitive Help (CSH)
1499 *
1500 * @return void
1501 */
1502 protected function loadCshJavascript() {
1503 $this->pageRenderer->loadExtJS();
1504 $this->pageRenderer->addJsFile($this->backPath . 'sysext/backend/Resources/Public/JavaScript/contexthelp.js');
1505 $this->pageRenderer->addExtDirectCode();
1506 }
1507
1508 /**
1509 * Creates a tab menu from an array definition
1510 *
1511 * Returns a tab menu for a module
1512 * Requires the JS function jumpToUrl() to be available
1513 *
1514 * @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=...
1515 * @param string $elementName it the form elements name, probably something like "SET[...]
1516 * @param string $currentValue is the value to be selected currently.
1517 * @param array $menuItems is an array with the menu items for the selector box
1518 * @param string $script is the script to send the &id to, if empty it's automatically found
1519 * @param string $addparams is additional parameters to pass to the script.
1520 * @return string HTML code for tab menu
1521 */
1522 public function getTabMenu($mainParams, $elementName, $currentValue, $menuItems, $script = '', $addparams = '') {
1523 $content = '';
1524 if (is_array($menuItems)) {
1525 if (!is_array($mainParams)) {
1526 $mainParams = array('id' => $mainParams);
1527 }
1528 $mainParams = GeneralUtility::implodeArrayForUrl('', $mainParams);
1529 if (!$script) {
1530 $script = basename(PATH_thisScript);
1531 }
1532 $menuDef = array();
1533 foreach ($menuItems as $value => $label) {
1534 $menuDef[$value]['isActive'] = (string)$currentValue === (string)$value;
1535 $menuDef[$value]['label'] = htmlspecialchars($label, ENT_COMPAT, 'UTF-8', FALSE);
1536 $menuDef[$value]['url'] = $script . '?' . $mainParams . $addparams . '&' . $elementName . '=' . $value;
1537 }
1538 $content = $this->getTabMenuRaw($menuDef);
1539 }
1540 return $content;
1541 }
1542
1543 /**
1544 * Creates the HTML content for the tab menu
1545 *
1546 * @param array $menuItems Menu items for tabs
1547 * @return string Table HTML
1548 * @access private
1549 */
1550 public function getTabMenuRaw($menuItems) {
1551 if (!is_array($menuItems)) {
1552 return '';
1553 }
1554
1555 $options = '';
1556 foreach ($menuItems as $id => $def) {
1557 $class = $def['isActive'] ? 'active' : '';
1558 $label = $def['label'];
1559 $url = htmlspecialchars($def['url']);
1560 $params = $def['addParams'];
1561
1562 $options .= '<li class="' . $class . '">' .
1563 '<a href="' . $url . '" ' . $params . '>' . $label . '</a>' .
1564 '</li>';
1565 }
1566
1567 return '<ul class="nav nav-tabs" role="tablist">' .
1568 $options .
1569 '</ul>';
1570
1571 }
1572
1573 /**
1574 * Creates a DYNAMIC tab-menu where the tabs are switched between with DHTML.
1575 * Should work in MSIE, Mozilla, Opera and Konqueror. On Konqueror I did find a serious problem: <textarea> fields loose their content when you switch tabs!
1576 *
1577 * @param array $menuItems Numeric array where each entry is an array in itself with associative keys: "label" contains the label for the TAB, "content" contains the HTML content that goes into the div-layer of the tabs content. "description" contains description text to be shown in the layer. "linkTitle" is short text for the title attribute of the tab-menu link (mouse-over text of tab). "stateIcon" indicates a standard status icon (see ->icon(), values: -1, 1, 2, 3). "icon" is an image tag placed before the text.
1578 * @param string $identString Identification string. This should be unique for every instance of a dynamic menu!
1579 * @param int $toggle If "1", then enabling one tab does not hide the others - they simply toggles each sheet on/off. This makes most sense together with the $foldout option. If "-1" then it acts normally where only one tab can be active at a time BUT you can click a tab and it will close so you have no active tabs.
1580 * @param bool $foldout If set, the tabs are rendered as headers instead over each sheet. Effectively this means there is no tab menu, but rather a foldout/foldin menu. Make sure to set $toggle as well for this option.
1581 * @param bool $noWrap Deprecated - delivered by CSS
1582 * @param bool $fullWidth If set, the tabs will span the full width of their position
1583 * @param int $defaultTabIndex Default tab to open (for toggle <=0). Value corresponds to integer-array index + 1 (index zero is "1", index "1" is 2 etc.). A value of zero (or something non-existing) will result in no default tab open.
1584 * @param int $tabBehaviour If set to '1' empty tabs will be remove, If set to '2' empty tabs will be disabled
1585 * @return string JavaScript section for the HTML header.
1586 */
1587 public function getDynTabMenu($menuItems, $identString, $toggle = 0, $foldout = FALSE, $noWrap = TRUE, $fullWidth = FALSE, $defaultTabIndex = 1, $tabBehaviour = 2) {
1588 // Load the static code, if not already done with the function below
1589 $this->loadJavascriptLib('sysext/backend/Resources/Public/JavaScript/tabmenu.js');
1590 $content = '';
1591 if (is_array($menuItems)) {
1592 // Init:
1593 $options = array(array());
1594 $divs = array();
1595 $JSinit = array();
1596 $id = $this->getDynTabMenuId($identString);
1597
1598 // Traverse menu items
1599 $c = 0;
1600 $tabRows = 0;
1601 $titleLenCount = 0;
1602 foreach ($menuItems as $index => $def) {
1603 // Need to add one so checking for first index in JavaScript
1604 // is different than if it is not set at all.
1605 $index += 1;
1606 // Switch to next tab row if needed
1607 if (!$foldout && ($def['newline'] === TRUE && $titleLenCount > 0)) {
1608 $titleLenCount = 0;
1609 $tabRows++;
1610 $options[$tabRows] = array();
1611 }
1612 if ($toggle == 1) {
1613 $onclick = 'DTM_toggle("' . $id . '","' . $index . '"); return false;';
1614 } else {
1615 $onclick = 'DTM_activate("' . $id . '","' . $index . '", ' . ($toggle < 0 ? 1 : 0) . '); return false;';
1616 }
1617 $isEmpty = trim($def['content']) === '' && trim($def['icon']) === '';
1618 // "Removes" empty tabs
1619 if ($isEmpty && $tabBehaviour == 1) {
1620 continue;
1621 }
1622 $requiredIcon = '<img name="' . $id . '-' . $index . '-REQ" src="' . $GLOBALS['BACK_PATH'] . 'gfx/clear.gif" class="t3-TCEforms-reqTabImg" alt="" />';
1623 if (!$foldout) {
1624 // Create TAB cell:
1625 $options[$tabRows][] = '
1626 <li class="' . ($isEmpty ? 'disabled' : '') . '" id="' . $id . '-' . $index . '-MENU">' . ($isEmpty ? '' : '<a href="#" onclick="' . htmlspecialchars($onclick) . '"' . ($def['linkTitle'] ? ' title="' . htmlspecialchars($def['linkTitle']) . '"' : '') . '>') . $def['icon'] . ($def['label'] ? htmlspecialchars($def['label']) : '&nbsp;') . $requiredIcon . $this->icons($def['stateIcon'], 'margin-left: 10px;') . ($isEmpty ? '' : '</a>') . '</li>';
1627 $titleLenCount += strlen($def['label']);
1628 } else {
1629 // Create DIV layer for content:
1630 $divs[] = '
1631 <div class="' . ($isEmpty ? 'disabled' : '') . '" id="' . $id . '-' . $index . '-MENU">' . ($isEmpty ? '' : '<a href="#" onclick="' . htmlspecialchars($onclick) . '"' . ($def['linkTitle'] ? ' title="' . htmlspecialchars($def['linkTitle']) . '"' : '') . '>') . $def['icon'] . ($def['label'] ? htmlspecialchars($def['label']) : '&nbsp;') . $requiredIcon . ($isEmpty ? '' : '</a>') . '</div>';
1632 }
1633 // Create DIV layer for content:
1634 $divs[] = '
1635 <div style="display: none;" id="' . $id . '-' . $index . '-DIV" class="c-tablayer">' . ($def['description'] ? '<p class="c-descr">' . nl2br(htmlspecialchars($def['description'])) . '</p>' : '') . $def['content'] . '</div>';
1636 // Create initialization string:
1637 $JSinit[] = '
1638 DTM_array["' . $id . '"][' . $c . '] = "' . $id . '-' . $index . '";
1639 ';
1640 // If not empty and we have the toggle option on, check if the tab needs to be expanded
1641 if ($toggle == 1 && !$isEmpty) {
1642 $JSinit[] = '
1643 if (top.DTM_currentTabs["' . $id . '-' . $index . '"]) { DTM_toggle("' . $id . '","' . $index . '",1); }
1644 ';
1645 }
1646 $c++;
1647 }
1648 // Render menu:
1649 if (count($options)) {
1650 // Tab menu is compiled:
1651 if (!$foldout) {
1652 $tabContent = '';
1653 for ($a = 0; $a <= $tabRows; $a++) {
1654 $tabContent .= '
1655
1656 <!-- Tab menu -->
1657 <ul class="nav nav-tabs" role="tablist">
1658 ' . implode('', $options[$a]) . '
1659 </ul>';
1660 }
1661 $content .= '<div class="typo3-dyntabmenu-tabs">' . $tabContent . '</div>';
1662 }
1663 // Div layers are added:
1664 $content .= '
1665 <!-- Div layers for tab menu: -->
1666 <div class="typo3-dyntabmenu-divs' . ($foldout ? '-foldout' : '') . '">
1667 ' . implode('', $divs) . '</div>';
1668 // Java Script section added:
1669 $content .= '
1670 <!-- Initialization JavaScript for the menu -->
1671 <script type="text/javascript">
1672 DTM_array["' . $id . '"] = new Array();
1673 ' . implode('', $JSinit) . '
1674 ' . ($toggle <= 0 ? 'DTM_activate("' . $id . '", top.DTM_currentTabs["' . $id . '"]?top.DTM_currentTabs["' . $id . '"]:' . (int)$defaultTabIndex . ', 0);' : '') . '
1675 </script>
1676
1677 ';
1678 }
1679 }
1680 return $content;
1681 }
1682
1683 /**
1684 * Creates the id for dynTabMenus.
1685 *
1686 * @param string $identString Identification string. This should be unique for every instance of a dynamic menu!
1687 * @return string The id with a short MD5 of $identString and prefixed "DTM-", like "DTM-2e8791854a
1688 */
1689 public function getDynTabMenuId($identString) {
1690 $id = 'DTM-' . GeneralUtility::shortMD5($identString);
1691 return $id;
1692 }
1693
1694 /**
1695 * Creates the version selector for the page id inputted.
1696 * Requires the core version management extension, "version" to be loaded.
1697 *
1698 * @param int $id Page id to create selector for.
1699 * @param bool $noAction If set, there will be no button for swapping page.
1700 * @return string
1701 */
1702 public function getVersionSelector($id, $noAction = FALSE) {
1703 if (
1704 ExtensionManagementUtility::isLoaded('version') &&
1705 !ExtensionManagementUtility::isLoaded('workspaces')
1706 ) {
1707 $versionGuiObj = GeneralUtility::makeInstance(\TYPO3\CMS\Version\View\VersionView::class);
1708 return $versionGuiObj->getVersionSelector($id, $noAction);
1709 }
1710 }
1711
1712 /**
1713 * Function to load a HTML template file with markers.
1714 * When calling from own extension, use syntax getHtmlTemplate('EXT:extkey/template.html')
1715 *
1716 * @param string $filename tmpl name, usually in the typo3/template/ directory
1717 * @return string HTML of template
1718 */
1719 public function getHtmlTemplate($filename) {
1720 // setting the name of the original HTML template
1721 $this->moduleTemplateFilename = $filename;
1722 if ($GLOBALS['TBE_STYLES']['htmlTemplates'][$filename]) {
1723 $filename = $GLOBALS['TBE_STYLES']['htmlTemplates'][$filename];
1724 }
1725 if (GeneralUtility::isFirstPartOfStr($filename, 'EXT:')) {
1726 $filename = GeneralUtility::getFileAbsFileName($filename, TRUE, TRUE);
1727 } elseif (!GeneralUtility::isAbsPath($filename)) {
1728 $filename = GeneralUtility::resolveBackPath($this->backPath . $filename);
1729 } elseif (!GeneralUtility::isAllowedAbsPath($filename)) {
1730 $filename = '';
1731 }
1732 $htmlTemplate = '';
1733 if ($filename !== '') {
1734 $htmlTemplate = GeneralUtility::getUrl($filename);
1735 }
1736 return $htmlTemplate;
1737 }
1738
1739 /**
1740 * Define the template for the module
1741 *
1742 * @param string $filename filename
1743 * @return void
1744 */
1745 public function setModuleTemplate($filename) {
1746 $this->moduleTemplate = $this->getHtmlTemplate($filename);
1747 }
1748
1749 /**
1750 * Put together the various elements for the module <body> using a static HTML
1751 * template
1752 *
1753 * @param array $pageRecord Record of the current page, used for page path and info
1754 * @param array $buttons HTML for all buttons
1755 * @param array $markerArray HTML for all other markers
1756 * @param array $subpartArray HTML for the subparts
1757 * @return string Composite HTML
1758 */
1759 public function moduleBody($pageRecord = array(), $buttons = array(), $markerArray = array(), $subpartArray = array()) {
1760 // Get the HTML template for the module
1761 $moduleBody = HtmlParser::getSubpart($this->moduleTemplate, '###FULLDOC###');
1762 // Add CSS
1763 $this->inDocStylesArray[] = 'html { overflow: hidden; }';
1764 // Get the page path for the docheader
1765 $markerArray['PAGEPATH'] = $this->getPagePath($pageRecord);
1766 // Get the page info for the docheader
1767 $markerArray['PAGEINFO'] = $this->getPageInfo($pageRecord);
1768 // Get all the buttons for the docheader
1769 $docHeaderButtons = $this->getDocHeaderButtons($buttons);
1770 // Merge docheader buttons with the marker array
1771 $markerArray = array_merge($markerArray, $docHeaderButtons);
1772 // replacing subparts
1773 foreach ($subpartArray as $marker => $content) {
1774 $moduleBody = HtmlParser::substituteSubpart($moduleBody, $marker, $content);
1775 }
1776 // adding flash messages
1777 if ($this->showFlashMessages) {
1778 $flashMessages = $this->getFlashMessages();
1779 if (!empty($flashMessages)) {
1780 $markerArray['FLASHMESSAGES'] = $flashMessages;
1781 // If there is no dedicated marker for the messages present
1782 // then force them to appear before the content
1783 if (strpos($moduleBody, '###FLASHMESSAGES###') === FALSE) {
1784 $moduleBody = str_replace('###CONTENT###', '###FLASHMESSAGES######CONTENT###', $moduleBody);
1785 }
1786 }
1787 }
1788 // Hook for adding more markers/content to the page, like the version selector
1789 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['moduleBodyPostProcess'])) {
1790 $params = array(
1791 'moduleTemplateFilename' => &$this->moduleTemplateFilename,
1792 'moduleTemplate' => &$this->moduleTemplate,
1793 'moduleBody' => &$moduleBody,
1794 'markers' => &$markerArray,
1795 'parentObject' => &$this
1796 );
1797 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['moduleBodyPostProcess'] as $funcRef) {
1798 GeneralUtility::callUserFunction($funcRef, $params, $this);
1799 }
1800 }
1801 // Replacing all markers with the finished markers and return the HTML content
1802 return HtmlParser::substituteMarkerArray($moduleBody, $markerArray, '###|###');
1803 }
1804
1805 /**
1806 * Get the default rendered FlashMessages from queue
1807 *
1808 * @return string
1809 */
1810 public function getFlashMessages() {
1811 /** @var $flashMessageService \TYPO3\CMS\Core\Messaging\FlashMessageService */
1812 $flashMessageService = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Messaging\FlashMessageService::class);
1813 /** @var $defaultFlashMessageQueue \TYPO3\CMS\Core\Messaging\FlashMessageQueue */
1814 $defaultFlashMessageQueue = $flashMessageService->getMessageQueueByIdentifier();
1815 $flashMessages = $defaultFlashMessageQueue->renderFlashMessages();
1816 if (!empty($flashMessages)) {
1817 $flashMessages = '<div id="typo3-messages">' . $flashMessages . '</div>';
1818 }
1819 return $flashMessages;
1820 }
1821
1822 /**
1823 * Renders the FlashMessages from queue and returns them as AJAX.
1824 *
1825 * @param array $params Always empty.
1826 * @param \TYPO3\CMS\Core\Http\AjaxRequestHandler $ajaxObj The AjaxRequestHandler object used to return content and set content types
1827 * @return void
1828 */
1829 public function renderFlashMessages(array $params, \TYPO3\CMS\Core\Http\AjaxRequestHandler $ajaxObj) {
1830 $ajaxObj->addContent('result', $this->getFlashMessages());
1831 $ajaxObj->setContentFormat('html');
1832 }
1833
1834 /**
1835 * Fill the button lists with the defined HTML
1836 *
1837 * @param array $buttons HTML for all buttons
1838 * @return array Containing HTML for both buttonlists
1839 */
1840 protected function getDocHeaderButtons($buttons) {
1841 $markers = array();
1842 // Fill buttons for left and right float
1843 $floats = array('left', 'right');
1844 foreach ($floats as $key) {
1845 // Get the template for each float
1846 $buttonTemplate = HtmlParser::getSubpart($this->moduleTemplate, '###BUTTON_GROUPS_' . strtoupper($key) . '###');
1847 // Fill the button markers in this float
1848 $buttonTemplate = HtmlParser::substituteMarkerArray($buttonTemplate, $buttons, '###|###', TRUE);
1849 // getting the wrap for each group
1850 $buttonWrap = HtmlParser::getSubpart($this->moduleTemplate, '###BUTTON_GROUP_WRAP###');
1851 // looping through the groups (max 6) and remove the empty groups
1852 for ($groupNumber = 1; $groupNumber < 6; $groupNumber++) {
1853 $buttonMarker = '###BUTTON_GROUP' . $groupNumber . '###';
1854 $buttonGroup = HtmlParser::getSubpart($buttonTemplate, $buttonMarker);
1855 if (trim($buttonGroup)) {
1856 if ($buttonWrap) {
1857 $buttonGroup = HtmlParser::substituteMarker($buttonWrap, '###BUTTONS###', $buttonGroup);
1858 }
1859 $buttonTemplate = HtmlParser::substituteSubpart($buttonTemplate, $buttonMarker, trim($buttonGroup));
1860 }
1861 }
1862 // Replace the marker with the template and remove all line breaks (for IE compat)
1863 $markers['BUTTONLIST_' . strtoupper($key)] = str_replace(LF, '', $buttonTemplate);
1864 }
1865 // Hook for manipulating docHeaderButtons
1866 if (isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['docHeaderButtonsHook'])) {
1867 $params = array(
1868 'buttons' => $buttons,
1869 'markers' => &$markers,
1870 'pObj' => &$this
1871 );
1872 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['typo3/template.php']['docHeaderButtonsHook'] as $funcRef) {
1873 GeneralUtility::callUserFunction($funcRef, $params, $this);
1874 }
1875 }
1876 return $markers;
1877 }
1878
1879 /**
1880 * Generate the page path for docheader
1881 *
1882 * @param array $pageRecord Current page
1883 * @return string Page path
1884 */
1885 protected function getPagePath($pageRecord) {
1886 // Is this a real page
1887 if (is_array($pageRecord) && $pageRecord['uid']) {
1888 $title = substr($pageRecord['_thePathFull'], 0, -1);
1889 // Remove current page title
1890 $pos = strrpos($title, '/');
1891 if ($pos !== FALSE) {
1892 $title = substr($title, 0, $pos) . '/';
1893 }
1894 } else {
1895 $title = '';
1896 }
1897 // Setting the path of the page
1898 $pagePath = $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.path', TRUE) . ': <span class="typo3-docheader-pagePath">';
1899 // crop the title to title limit (or 50, if not defined)
1900 $cropLength = empty($GLOBALS['BE_USER']->uc['titleLen']) ? 50 : $GLOBALS['BE_USER']->uc['titleLen'];
1901 $croppedTitle = GeneralUtility::fixed_lgd_cs($title, -$cropLength);
1902 if ($croppedTitle !== $title) {
1903 $pagePath .= '<abbr title="' . htmlspecialchars($title) . '">' . htmlspecialchars($croppedTitle) . '</abbr>';
1904 } else {
1905 $pagePath .= htmlspecialchars($title);
1906 }
1907 $pagePath .= '</span>';
1908 return $pagePath;
1909 }
1910
1911 /**
1912 * Setting page icon with clickmenu + uid for docheader
1913 *
1914 * @param array $pageRecord Current page
1915 * @return string Page info
1916 */
1917 protected function getPageInfo($pageRecord) {
1918 // Add icon with clickmenu, etc:
1919 // If there IS a real page
1920 if (is_array($pageRecord) && $pageRecord['uid']) {
1921 $alttext = BackendUtility::getRecordIconAltText($pageRecord, 'pages');
1922 $iconImg = IconUtility::getSpriteIconForRecord('pages', $pageRecord, array('title' => $alttext));
1923 // Make Icon:
1924 $theIcon = $GLOBALS['SOBE']->doc->wrapClickMenuOnIcon($iconImg, 'pages', $pageRecord['uid']);
1925 $uid = $pageRecord['uid'];
1926 $title = BackendUtility::getRecordTitle('pages', $pageRecord);
1927 } else {
1928 // On root-level of page tree
1929 // Make Icon
1930 $iconImg = IconUtility::getSpriteIcon('apps-pagetree-root', array('title' => htmlspecialchars($GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'])));
1931 if ($GLOBALS['BE_USER']->user['admin']) {
1932 $theIcon = $GLOBALS['SOBE']->doc->wrapClickMenuOnIcon($iconImg, 'pages', 0);
1933 } else {
1934 $theIcon = $iconImg;
1935 }
1936 $uid = '0';
1937 $title = $GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'];
1938 }
1939 // Setting icon with clickmenu + uid
1940 $pageInfo = $theIcon . '<strong>' . htmlspecialchars($title) . '&nbsp;[' . $uid . ']</strong>';
1941 return $pageInfo;
1942 }
1943
1944 /**
1945 * Makes a collapseable section. See reports module for an example
1946 *
1947 * @param string $title
1948 * @param string $html
1949 * @param string $id
1950 * @param string $saveStatePointer
1951 * @return string
1952 */
1953 public function collapseableSection($title, $html, $id, $saveStatePointer = '') {
1954 $hasSave = $saveStatePointer ? TRUE : FALSE;
1955 $collapsedStyle = ($collapsedClass = '');
1956 if ($hasSave) {
1957 /** @var $settings \TYPO3\CMS\Backend\User\ExtDirect\BackendUserSettingsDataProvider */
1958 $settings = GeneralUtility::makeInstance(\TYPO3\CMS\Backend\User\ExtDirect\BackendUserSettingsDataProvider::class);
1959 $value = $settings->get($saveStatePointer . '.' . $id);
1960 if ($value) {
1961 $collapsedStyle = ' style="display: none"';
1962 $collapsedClass = ' collapsed';
1963 } else {
1964 $collapsedStyle = '';
1965 $collapsedClass = ' expanded';
1966 }
1967 }
1968 $this->pageRenderer->loadExtJS();
1969 $this->pageRenderer->addExtOnReadyCode('
1970 Ext.select("h2.section-header").each(function(element){
1971 element.on("click", function(event, tag) {
1972 var state = 0,
1973 el = Ext.fly(tag),
1974 div = el.next("div"),
1975 saveKey = el.getAttribute("rel");
1976 if (el.hasClass("collapsed")) {
1977 el.removeClass("collapsed").addClass("expanded");
1978 div.slideIn("t", {
1979 easing: "easeIn",
1980 duration: .5
1981 });
1982 } else {
1983 el.removeClass("expanded").addClass("collapsed");
1984 div.slideOut("t", {
1985 easing: "easeOut",
1986 duration: .5,
1987 remove: false,
1988 useDisplay: true
1989 });
1990 state = 1;
1991 }
1992 if (saveKey) {
1993 try {
1994 top.TYPO3.BackendUserSettings.ExtDirect.set(saveKey + "." + tag.id, state, function(response) {});
1995 } catch(e) {}
1996 }
1997 });
1998 });
1999 ');
2000 return '
2001 <h2 id="' . $id . '" class="section-header' . $collapsedClass . '" rel="' . $saveStatePointer . '"> ' . $title . '</h2>
2002 <div' . $collapsedStyle . '>' . $html . '</div>
2003 ';
2004 }
2005
2006 /**
2007 * Retrieves configured favicon for backend (with fallback)
2008 *
2009 * @return string
2010 */
2011 protected function getBackendFavicon() {
2012 return IconUtility::skinImg($this->backPath, 'gfx/favicon.ico', '', 1);
2013 }
2014 }