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