b1acc136e343c9bba7d0389b2fc161787307cbe6
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / TypoScript / TemplateService.php
1 <?php
2 namespace TYPO3\CMS\Core\TypoScript;
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\Core\Utility\ExtensionManagementUtility;
18 use TYPO3\CMS\Core\Utility\GeneralUtility;
19
20 /**
21 * Template object that is responsible for generating the TypoScript template based on template records.
22 *
23 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
24 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
25 * @see \TYPO3\CMS\Core\Configuration\TypoScript\ConditionMatching\AbstractConditionMatcher
26 */
27 class TemplateService {
28
29 // Debugging, analysis:
30 // If set, the global tt-timeobject is used to log the performance.
31 /**
32 * @todo Define visibility
33 */
34 public $tt_track = 1;
35
36 // If set, the template is always rendered. Used from Admin Panel.
37 /**
38 * @todo Define visibility
39 */
40 public $forceTemplateParsing = 0;
41
42 // Backend Analysis modules settings:
43 // This array is passed on to matchObj by generateConfig(). If it holds elements, they are used for matching instead. See commment at the match-class. Used for backend modules only. Never frontend!
44 /**
45 * @todo Define visibility
46 */
47 public $matchAlternative = array();
48
49 // If set, the match-class matches everything! Used for backend modules only. Never frontend!
50 /**
51 * @todo Define visibility
52 */
53 public $matchAll = 0;
54
55 /**
56 * @todo Define visibility
57 */
58 public $backend_info = 0;
59
60 // Externally set breakpoints (used by Backend Modules)
61 /**
62 * @todo Define visibility
63 */
64 public $ext_constants_BRP = 0;
65
66 /**
67 * @todo Define visibility
68 */
69 public $ext_config_BRP = 0;
70
71 /**
72 * @todo Define visibility
73 */
74 public $ext_regLinenumbers = FALSE;
75
76 /**
77 * @todo Define visibility
78 */
79 public $ext_regComments = FALSE;
80
81 // Constants:
82 /**
83 * @todo Define visibility
84 */
85 public $tempPath = 'typo3temp/';
86
87 // Set Internally:
88 // This MUST be initialized by the init() function
89 /**
90 * @todo Define visibility
91 */
92 public $whereClause = '';
93
94 /**
95 * @todo Define visibility
96 */
97 public $debug = 0;
98
99 // This is the only paths (relative!!) that are allowed for resources in TypoScript. Should all be appended with '/'. You can extend these by the global array TYPO3_CONF_VARS. See init() function.
100 /**
101 * @todo Define visibility
102 */
103 public $allowedPaths = array();
104
105 // See init(); Set if preview of some kind is enabled.
106 /**
107 * @todo Define visibility
108 */
109 public $simulationHiddenOrTime = 0;
110
111 // Set, if the TypoScript template structure is loaded and OK, see ->start()
112 /**
113 * @todo Define visibility
114 */
115 public $loaded = 0;
116
117 /**
118 * @var array Contains TypoScript setup part after parsing
119 */
120 public $setup = array();
121
122 /**
123 * @todo Define visibility
124 */
125 public $flatSetup = array();
126
127 // For fetching TypoScript code from template hierarchy before parsing it. Each array contains code field values from template records/files:
128 // Setup field
129 /**
130 * @todo Define visibility
131 */
132 public $config = array();
133
134 // Constant field
135 /**
136 * @todo Define visibility
137 */
138 public $constants = array();
139
140 /**
141 * Holds the include paths of the templates (empty if from database)
142 * @var array
143 */
144 protected $templateIncludePaths = array();
145
146 // For Template Analyser in backend
147 /**
148 * @todo Define visibility
149 */
150 public $hierarchyInfo = array();
151
152 // For Template Analyser in backend (setup content only)
153 /**
154 * @todo Define visibility
155 */
156 public $hierarchyInfoToRoot = array();
157
158 // Next-level flag (see runThroughTemplates())
159 /**
160 * @todo Define visibility
161 */
162 public $nextLevel = 0;
163
164 // The Page UID of the root page
165 /**
166 * @todo Define visibility
167 */
168 public $rootId;
169
170 // The rootline from current page to the root page
171 /**
172 * @todo Define visibility
173 */
174 public $rootLine;
175
176 // Rootline all the way to the root. Set but runThroughTemplates
177 /**
178 * @todo Define visibility
179 */
180 public $absoluteRootLine;
181
182 // A pointer to the last entry in the rootline where a template was found.
183 /**
184 * @todo Define visibility
185 */
186 public $outermostRootlineIndexWithTemplate = 0;
187
188 // Array of arrays with title/uid of templates in hierarchy
189 /**
190 * @todo Define visibility
191 */
192 public $rowSum;
193
194 // The current site title field.
195 /**
196 * @todo Define visibility
197 */
198 public $sitetitle = '';
199
200 // Tracking all conditions found during parsing of TypoScript. Used for the "all" key in currentPageData
201 /**
202 * @todo Define visibility
203 */
204 public $sections;
205
206 // Tracking all matching conditions found
207 /**
208 * @todo Define visibility
209 */
210 public $sectionsMatch;
211
212 /**
213 * Used by Backend only (Typoscript Template Analyzer)
214 *
215 * @todo Define visibility
216 */
217 public $clearList_const = array();
218
219 /**
220 * Used by Backend only (Typoscript Template Analyzer)
221 *
222 * @todo Define visibility
223 */
224 public $clearList_setup = array();
225
226 /**
227 * @todo Define visibility
228 */
229 public $parserErrors = array();
230
231 /**
232 * @todo Define visibility
233 */
234 public $setup_constants = array();
235
236 // Other:
237 // Used by getFileName for caching of references to file resources
238 /**
239 * @todo Define visibility
240 */
241 public $fileCache = array();
242
243 // Keys are frame names and values are type-values, which must be used to refer correctly to the content of the frames.
244 /**
245 * @todo Define visibility
246 */
247 public $frames = array();
248
249 // Contains mapping of Page id numbers to MP variables.
250 /**
251 * @todo Define visibility
252 */
253 public $MPmap = '';
254
255 /**
256 * Indicator that extension statics are processed.
257 *
258 * These files are considered if either a root template
259 * has been processed or the $processExtensionStatics
260 * property has been set to TRUE.
261 *
262 * @var boolean
263 */
264 protected $extensionStaticsProcessed = FALSE;
265
266 /**
267 * Trigger value, to ensure that extension statics are processed.
268 *
269 * @var boolean
270 */
271 protected $processExtensionStatics = FALSE;
272
273 /**
274 * Set to TRUE after the default TypoScript was added during parsing.
275 * This prevents double inclusion of the same TypoScript code.
276 *
277 * @see addDefaultTypoScript()
278 * @var boolean
279 */
280 protected $isDefaultTypoScriptAdded = FALSE;
281
282 /**
283 * Set to TRUE after $this->config and $this->constants have processed all <INCLUDE_TYPOSCRIPT:> instructions.
284 *
285 * This prevents double processing of INCLUDES.
286 *
287 * @see processIncludes()
288 * @var boolean
289 */
290 protected $processIncludesHasBeenRun = FALSE;
291
292 /**
293 * @return boolean
294 */
295 public function getProcessExtensionStatics() {
296 return $this->processExtensionStatics;
297 }
298
299 /**
300 * @param boolean $processExtensionStatics
301 */
302 public function setProcessExtensionStatics($processExtensionStatics) {
303 $this->processExtensionStatics = (bool) $processExtensionStatics;
304 }
305
306 /**
307 * Initialize
308 * MUST be called directly after creating a new template-object
309 *
310 * @return void
311 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::initTemplate()
312 * @todo Define visibility
313 */
314 public function init() {
315 // $this->whereClause is used only to select templates from sys_template.
316 // $GLOBALS['SIM_ACCESS_TIME'] is used so that we're able to simulate a later time as a test...
317 $this->whereClause = 'AND deleted=0 ';
318 if (!$GLOBALS['TSFE']->showHiddenRecords) {
319 $this->whereClause .= 'AND hidden=0 ';
320 }
321 if ($GLOBALS['TSFE']->showHiddenRecords || $GLOBALS['SIM_ACCESS_TIME'] != $GLOBALS['ACCESS_TIME']) {
322 // Set the simulation flag, if simulation is detected!
323 $this->simulationHiddenOrTime = 1;
324 }
325 $this->whereClause .= 'AND (starttime<=' . $GLOBALS['SIM_ACCESS_TIME'] . ') AND (endtime=0 OR endtime>' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
326 // Sets the paths from where TypoScript resources are allowed to be used:
327 $this->allowedPaths = array(
328 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'],
329 // fileadmin/ path
330 'uploads/',
331 'typo3temp/',
332 TYPO3_mainDir . 'ext/',
333 TYPO3_mainDir . 'sysext/',
334 TYPO3_mainDir . 'contrib/',
335 'typo3conf/ext/'
336 );
337 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['addAllowedPaths']) {
338 $pathArr = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['addAllowedPaths'], TRUE);
339 foreach ($pathArr as $p) {
340 // Once checked for path, but as this may run from typo3/mod/web/ts/ dir, that'll not work!! So the paths ar uncritically included here.
341 $this->allowedPaths[] = $p;
342 }
343 }
344 }
345
346 /**
347 * Fetches the "currentPageData" array from cache
348 *
349 * NOTE about currentPageData:
350 * It holds information about the TypoScript conditions along with the list
351 * of template uid's which is used on the page. In the getFromCache function
352 * in TSFE, currentPageData is used to evaluate if there is a template and
353 * if the matching conditions are alright. Unfortunately this does not take
354 * into account if the templates in the rowSum of currentPageData has
355 * changed composition, eg. due to hidden fields or start/end time. So if a
356 * template is hidden or times out, it'll not be discovered unless the page
357 * is regenerated - at least the this->start function must be called,
358 * because this will make a new portion of data in currentPageData string.
359 *
360 * @return array Returns the unmatched array $currentPageData if found cached in "cache_pagesection". Otherwise FALSE is returned which means that the array must be generated and stored in the cache
361 */
362 public function getCurrentPageData() {
363 return GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Cache\\CacheManager')->getCache('cache_pagesection')->get((int)$GLOBALS['TSFE']->id . '_' . GeneralUtility::md5int($GLOBALS['TSFE']->MP));
364 }
365
366 /**
367 * Fetches data about which TypoScript-matches there are at this page. Then it performs a matchingtest.
368 *
369 * @param array $cc An array with three keys, "all", "rowSum" and "rootLine" - all coming from the "currentPageData" array
370 * @return array The input array but with a new key added, "match" which contains the items from the "all" key which when passed to tslib_matchCondition returned TRUE.
371 * @todo Define visibility
372 */
373 public function matching($cc) {
374 if (is_array($cc['all'])) {
375 /** @var $matchObj \TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher */
376 $matchObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Configuration\\TypoScript\\ConditionMatching\\ConditionMatcher');
377 $matchObj->setRootline((array) $cc['rootLine']);
378 foreach ($cc['all'] as $key => $pre) {
379 if ($matchObj->match($pre)) {
380 $sectionsMatch[$key] = $pre;
381 }
382 }
383 $cc['match'] = $sectionsMatch;
384 }
385 return $cc;
386 }
387
388 /**
389 * This is all about fetching the right TypoScript template structure. If it's not cached then it must be generated and cached!
390 * The method traverses the rootline structure from out to in, fetches the hierarchy of template records and based on this either finds the cached TypoScript template structure or parses the template and caches it for next time.
391 * Sets $this->setup to the parsed TypoScript template array
392 *
393 * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
394 * @return void
395 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getConfigArray()
396 * @todo Define visibility
397 */
398 public function start($theRootLine) {
399 if (is_array($theRootLine)) {
400 $setupData = '';
401 $hash = '';
402 // Flag that indicates that the existing data in cache_pagesection
403 // could be used (this is the case if $TSFE->all is set, and the
404 // rowSum still matches). Based on this we decide if cache_pagesection
405 // needs to be updated...
406 $isCached = FALSE;
407 $this->runThroughTemplates($theRootLine);
408 if ($GLOBALS['TSFE']->all) {
409 $cc = $GLOBALS['TSFE']->all;
410 // The two rowSums must NOT be different from each other - which they will be if start/endtime or hidden has changed!
411 if (serialize($this->rowSum) !== serialize($cc['rowSum'])) {
412 unset($cc);
413 } else {
414 // If $TSFE->all contains valid data, we don't need to update cache_pagesection (because this data was fetched from there already)
415 if (serialize($this->rootLine) === serialize($cc['rootLine'])) {
416 $isCached = TRUE;
417 }
418 // When the data is serialized below (ROWSUM hash), it must not contain the rootline by concept. So this must be removed (and added again later)...
419 unset($cc['rootLine']);
420 }
421 }
422 // This is about getting the hash string which is used to fetch the cached TypoScript template.
423 // If there was some cached currentPageData ($cc) then that's good (it gives us the hash).
424 if (is_array($cc)) {
425 // If currentPageData was actually there, we match the result (if this wasn't done already in $TSFE->getFromCache()...)
426 if (!$cc['match']) {
427 // TODO: check if this can ever be the case - otherwise remove
428 $cc = $this->matching($cc);
429 ksort($cc);
430 }
431 $hash = md5(serialize($cc));
432 } else {
433 // If currentPageData was not there, we first find $rowSum (freshly generated). After that we try to see, if it is stored with a list of all conditions. If so we match the result.
434 $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
435 $result = \TYPO3\CMS\Frontend\Page\PageRepository::getHash($rowSumHash);
436 if (is_array($result)) {
437 $cc = array();
438 $cc['all'] = $result;
439 $cc['rowSum'] = $this->rowSum;
440 $cc = $this->matching($cc);
441 ksort($cc);
442 $hash = md5(serialize($cc));
443 }
444 }
445 if ($hash) {
446 // Get TypoScript setup array
447 $setupData = \TYPO3\CMS\Frontend\Page\PageRepository::getHash($hash);
448 }
449 if (is_array($setupData) && !$this->forceTemplateParsing) {
450 // If TypoScript setup structure was cached we unserialize it here:
451 $this->setup = $setupData;
452 if ($this->tt_track) {
453 $GLOBALS['TT']->setTSLogMessage('Using cached TS template data');
454 }
455 } else {
456 if ($this->tt_track) {
457 $GLOBALS['TT']->setTSLogMessage('Not using any cached TS data');
458 }
459
460 // Make configuration
461 $this->generateConfig();
462 // This stores the template hash thing
463 $cc = array();
464 // All sections in the template at this point is found
465 $cc['all'] = $this->sections;
466 // The line of templates is collected
467 $cc['rowSum'] = $this->rowSum;
468 $cc = $this->matching($cc);
469 ksort($cc);
470 $hash = md5(serialize($cc));
471 // This stores the data.
472 \TYPO3\CMS\Frontend\Page\PageRepository::storeHash($hash, $this->setup, 'TS_TEMPLATE');
473 if ($this->tt_track) {
474 $GLOBALS['TT']->setTSlogMessage('TS template size, serialized: ' . strlen(serialize($this->setup)) . ' bytes');
475 }
476 $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
477 \TYPO3\CMS\Frontend\Page\PageRepository::storeHash($rowSumHash, $cc['all'], 'TMPL_CONDITIONS_ALL');
478 }
479 // Add rootLine
480 $cc['rootLine'] = $this->rootLine;
481 ksort($cc);
482 // Make global and save
483 $GLOBALS['TSFE']->all = $cc;
484 // Matching must be executed for every request, so this must never be part of the pagesection cache!
485 unset($cc['match']);
486 if (!$isCached && !$this->simulationHiddenOrTime && !$GLOBALS['TSFE']->no_cache) {
487 // Only save the data if we're not simulating by hidden/starttime/endtime
488 $mpvarHash = GeneralUtility::md5int($GLOBALS['TSFE']->MP);
489 /** @var $pageSectionCache \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface */
490 $pageSectionCache = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Cache\\CacheManager')->getCache('cache_pagesection');
491 $pageSectionCache->set((int)$GLOBALS['TSFE']->id . '_' . $mpvarHash, $cc, array(
492 'pageId_' . (int)$GLOBALS['TSFE']->id,
493 'mpvarHash_' . $mpvarHash
494 ));
495 }
496 // If everything OK.
497 if ($this->rootId && $this->rootLine && $this->setup) {
498 $this->loaded = 1;
499 }
500 }
501 }
502
503 /*******************************************************************
504 *
505 * Fetching TypoScript code text for the Template Hierarchy
506 *
507 *******************************************************************/
508 /**
509 * Traverses the rootLine from the root and out. For each page it checks if there is a template record. If there is a template record, $this->processTemplate() is called.
510 * Resets and affects internal variables like $this->constants, $this->config and $this->rowSum
511 * Also creates $this->rootLine which is a root line stopping at the root template (contrary to $GLOBALS['TSFE']->rootLine which goes all the way to the root of the tree
512 *
513 * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
514 * @param integer $start_template_uid Set specific template record UID to select; this is only for debugging/development/analysis use in backend modules like "Web > Template". For parsing TypoScript templates in the frontend it should be 0 (zero)
515 * @return void
516 * @see start()
517 * @todo Define visibility
518 */
519 public function runThroughTemplates($theRootLine, $start_template_uid = 0) {
520 $this->constants = array();
521 $this->config = array();
522 $this->rowSum = array();
523 $this->hierarchyInfoToRoot = array();
524 $this->absoluteRootLine = $theRootLine;
525 $this->isDefaultTyposcriptAdded = FALSE;
526
527 reset($this->absoluteRootLine);
528 $c = count($this->absoluteRootLine);
529 for ($a = 0; $a < $c; $a++) {
530 // If some template loaded before has set a template-id for the next level, then load this template first!
531 if ($this->nextLevel) {
532 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_template', 'uid=' . (int)$this->nextLevel . ' ' . $this->whereClause);
533 $this->nextLevel = 0;
534 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
535 $this->versionOL($row);
536 if (is_array($row)) {
537 $this->processTemplate($row, 'sys_' . $row['uid'], $this->absoluteRootLine[$a]['uid'], 'sys_' . $row['uid']);
538 $this->outermostRootlineIndexWithTemplate = $a;
539 }
540 }
541 $GLOBALS['TYPO3_DB']->sql_free_result($res);
542 }
543 $addC = '';
544 // If first loop AND there is set an alternative template uid, use that
545 if ($a == $c - 1 && $start_template_uid) {
546 $addC = ' AND uid=' . (int)$start_template_uid;
547 }
548 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_template', 'pid=' . (int)$this->absoluteRootLine[$a]['uid'] . $addC . ' ' . $this->whereClause, '', 'sorting', 1);
549 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
550 $this->versionOL($row);
551 if (is_array($row)) {
552 $this->processTemplate($row, 'sys_' . $row['uid'], $this->absoluteRootLine[$a]['uid'], 'sys_' . $row['uid']);
553 $this->outermostRootlineIndexWithTemplate = $a;
554 }
555 }
556 $GLOBALS['TYPO3_DB']->sql_free_result($res);
557 $this->rootLine[] = $this->absoluteRootLine[$a];
558 }
559
560 // Process extension static files if not done yet, but explicitly requested
561 if (!$this->extensionStaticsProcessed && $this->processExtensionStatics) {
562 $this->addExtensionStatics('sys_0', 'sys_0', 0, array());
563 }
564
565 // Add the global default TypoScript from the TYPO3_CONF_VARS
566 $this->addDefaultTypoScript();
567
568 $this->processIncludes();
569 }
570
571 /**
572 * Checks if the template ($row) has some included templates and after including them it fills the arrays with the setup
573 * Builds up $this->rowSum
574 *
575 * @param array $row A full TypoScript template record (sys_template/static_template/forged "dummy" record made from static template file)
576 * @param string $idList A list of already processed template ids including the current; The list is on the form "[prefix]_[uid]" where [prefix] is "sys" for "sys_template" records, "static" for "static_template" records and "ext_" for static include files (from extensions). The list is used to check that the recursive inclusion of templates does not go into circles: Simply it is used to NOT include a template record/file which has already BEEN included somewhere in the recursion.
577 * @param array $pid The PID of the input template record
578 * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
579 * @param string $templateParent Parent template id (during recursive call); Same syntax as $idList ids, eg. "sys_123
580 * @param string $includePath Specifies the path from which the template was included (used with static_includes)
581 * @return void
582 * @see runThroughTemplates()
583 * @todo Define visibility
584 */
585 public function processTemplate($row, $idList, $pid, $templateID = '', $templateParent = '', $includePath = '') {
586 // Adding basic template record information to rowSum array
587 $this->rowSum[] = array($row['uid'], $row['title'], $row['tstamp']);
588 // Processing "Clear"-flags
589 if ($row['clear']) {
590 $clConst = $row['clear'] & 1;
591 $clConf = $row['clear'] & 2;
592 if ($clConst) {
593 $this->constants = array();
594 $this->clearList_const = array();
595 }
596 if ($clConf) {
597 $this->config = array();
598 $this->hierarchyInfoToRoot = array();
599 $this->clearList_setup = array();
600 }
601 }
602 // Include static records (static_template) or files (from extensions) (#1/2)
603 // NORMAL inclusion, The EXACT same code is found below the basedOn inclusion!!!
604 if (!$row['includeStaticAfterBasedOn']) {
605 $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
606 }
607 // Include "Based On" sys_templates:
608 // 'basedOn' is a list of templates to include
609 if (trim($row['basedOn'])) {
610 // Manually you can put this value in the field and then the based_on ID will be taken from the $_GET var defined by '=....'.
611 // Example: If $row['basedOn'] is 'EXTERNAL_BASED_ON_TEMPLATE_ID=based_on_uid', then the global var, based_on_uid - given by the URL like '&based_on_uid=999' - is included instead!
612 // This feature allows us a hack to test/demonstrate various included templates on the same set of content bearing pages. Used by the "freesite" extension.
613 $basedOn_hackFeature = explode('=', $row['basedOn']);
614 if ($basedOn_hackFeature[0] == 'EXTERNAL_BASED_ON_TEMPLATE_ID' && $basedOn_hackFeature[1]) {
615 $id = (int)GeneralUtility::_GET($basedOn_hackFeature[1]);
616 // If $id is not allready included ...
617 if ($id && !GeneralUtility::inList($idList, ('sys_' . $id))) {
618 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_template', 'uid=' . $id . ' ' . $this->whereClause);
619 // there was a template, then we fetch that
620 if ($subrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
621 $this->versionOL($subrow);
622 if (is_array($subrow)) {
623 $this->processTemplate($subrow, $idList . ',sys_' . $id, $pid, 'sys_' . $id, $templateID);
624 }
625 }
626 $GLOBALS['TYPO3_DB']->sql_free_result($res);
627 }
628 } else {
629 // Normal Operation, which is to include the "based-on" sys_templates,
630 // if they are not already included, and maintaining the sorting of the templates
631 $basedOnIds = GeneralUtility::intExplode(',', $row['basedOn']);
632 // skip template if it's already included
633 foreach ($basedOnIds as $key => $basedOnId) {
634 if (GeneralUtility::inList($idList, 'sys_' . $basedOnId)) {
635 unset($basedOnIds[$key]);
636 }
637 }
638 $subTemplates = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('*', 'sys_template', 'uid IN (' . implode(',', $basedOnIds) . ') ' . $this->whereClause, '', '', '', 'uid');
639 // Traversing list again to ensure the sorting of the templates
640 foreach ($basedOnIds as $id) {
641 if (is_array($subTemplates[$id])) {
642 $this->versionOL($subTemplates[$id]);
643 $this->processTemplate($subTemplates[$id], $idList . ',sys_' . $id, $pid, 'sys_' . $id, $templateID);
644 }
645 }
646 }
647 }
648 // Include static records (static_template) or files (from extensions) (#2/2)
649 if ($row['includeStaticAfterBasedOn']) {
650 $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
651 }
652 // Creating hierarchy information; Used by backend analysis tools
653 $this->hierarchyInfo[] = ($this->hierarchyInfoToRoot[] = array(
654 'root' => trim($row['root']),
655 'next' => $row['nextLevel'],
656 'clConst' => $clConst,
657 'clConf' => $clConf,
658 'templateID' => $templateID,
659 'templateParent' => $templateParent,
660 'title' => $row['title'],
661 'uid' => $row['uid'],
662 'pid' => $row['pid'],
663 'configLines' => substr_count($row['config'], LF) + 1
664 ));
665 // Adding the content of the fields constants (Constants) and config (Setup)
666 $this->constants[] = $row['constants'];
667 $this->config[] = $row['config'];
668 $this->templateIncludePaths[] = $includePath;
669 // For backend analysis (Template Analyser) provide the order of added constants/config template IDs
670 $this->clearList_const[] = $templateID;
671 $this->clearList_setup[] = $templateID;
672 if (trim($row['sitetitle'])) {
673 $this->sitetitle = $row['sitetitle'];
674 }
675 // If the template record is a Rootlevel record, set the flag and clear the template rootLine (so it starts over from this point)
676 if (trim($row['root'])) {
677 $this->rootId = $pid;
678 $this->rootLine = array();
679 }
680 // If a template is set to be active on the next level set this internal value to point to this UID. (See runThroughTemplates())
681 if ($row['nextLevel']) {
682 $this->nextLevel = $row['nextLevel'];
683 } else {
684 $this->nextLevel = 0;
685 }
686 }
687
688 /**
689 * This function can be used to update the data of the current rootLine
690 * e.g. when a different language is used.
691 *
692 * This function must not be used if there are different pages in the
693 * rootline as before!
694 *
695 * @param array $fullRootLine Array containing the FULL rootline (up to the TYPO3 root)
696 * @return void
697 * @throws \RuntimeException If the given $fullRootLine does not contain all pages that are in the current template rootline
698 */
699 public function updateRootlineData($fullRootLine) {
700 if (!is_array($this->rootLine) || count($this->rootLine) === 0) {
701 return;
702 }
703
704 $fullRootLineByUid = array();
705 foreach ($fullRootLine as $rootLineData) {
706 $fullRootLineByUid[$rootLineData['uid']] = $rootLineData;
707 }
708
709 foreach ($this->rootLine as $level => $dataArray) {
710 $currentUid = $dataArray['uid'];
711
712 if (!array_key_exists($currentUid, $fullRootLineByUid)) {
713 throw new \RuntimeException(sprintf('The full rootLine does not contain data for the page with the uid %d that is contained in the template rootline.', $currentUid), 1370419654);
714 }
715
716 $this->rootLine[$level] = $fullRootLineByUid[$currentUid];
717 }
718 }
719
720 /**
721 * Includes static template records (from static_template table, loaded through a hook) and static template files (from extensions) for the input template record row.
722 *
723 * @param string $idList A list of already processed template ids including the current; The list is on the form "[prefix]_[uid]" where [prefix] is "sys" for "sys_template" records, "static" for "static_template" records and "ext_" for static include files (from extensions). The list is used to check that the recursive inclusion of templates does not go into circles: Simply it is used to NOT include a template record/file which has already BEEN included somewhere in the recursion.
724 * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
725 * @param array $pid The PID of the input template record
726 * @param array $row A full TypoScript template record
727 * @return void
728 * @see processTemplate()
729 * @todo Define visibility
730 */
731 public function includeStaticTypoScriptSources($idList, $templateID, $pid, $row) {
732 // Static Template Records (static_template): include_static is a list of static templates to include
733 // Call function for link rendering:
734 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSources'])) {
735 $_params = array(
736 'idList' => &$idList,
737 'templateId' => &$templateID,
738 'pid' => &$pid,
739 'row' => &$row
740 );
741 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSources'] as $_funcRef) {
742 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
743 }
744 }
745 // If "Include before all static templates if root-flag is set" is set:
746 if ($row['static_file_mode'] == 3 && substr($templateID, 0, 4) == 'sys_' && $row['root']) {
747 $this->addExtensionStatics($idList, $templateID, $pid, $row);
748 }
749 // Static Template Files (Text files from extensions): include_static_file is a list of static files to include (from extensions)
750 if (trim($row['include_static_file'])) {
751 $include_static_fileArr = GeneralUtility::trimExplode(',', $row['include_static_file'], TRUE);
752 // Traversing list
753 foreach ($include_static_fileArr as $ISF_file) {
754 if (substr($ISF_file, 0, 4) == 'EXT:') {
755 list($ISF_extKey, $ISF_localPath) = explode('/', substr($ISF_file, 4), 2);
756 if ((string)$ISF_extKey !== '' && \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::isLoaded($ISF_extKey) && (string)$ISF_localPath !== '') {
757 $ISF_localPath = rtrim($ISF_localPath, '/') . '/';
758 $ISF_filePath = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath($ISF_extKey) . $ISF_localPath;
759 if (@is_dir($ISF_filePath)) {
760 $mExtKey = str_replace('_', '', $ISF_extKey . '/' . $ISF_localPath);
761 $subrow = array(
762 'constants' => @file_exists(($ISF_filePath . 'constants.txt')) ? GeneralUtility::getUrl($ISF_filePath . 'constants.txt') : '',
763 'config' => @file_exists(($ISF_filePath . 'setup.txt')) ? GeneralUtility::getUrl($ISF_filePath . 'setup.txt') : '',
764 'include_static' => @file_exists(($ISF_filePath . 'include_static.txt')) ? implode(',', array_unique(GeneralUtility::intExplode(',', GeneralUtility::getUrl($ISF_filePath . 'include_static.txt')))) : '',
765 'include_static_file' => @file_exists(($ISF_filePath . 'include_static_file.txt')) ? implode(',', array_unique(explode(',', GeneralUtility::getUrl($ISF_filePath . 'include_static_file.txt')))) : '',
766 'title' => $ISF_file,
767 'uid' => $mExtKey
768 );
769 $subrow = $this->prependStaticExtra($subrow);
770 $this->processTemplate($subrow, $idList . ',ext_' . $mExtKey, $pid, 'ext_' . $mExtKey, $templateID, $ISF_filePath);
771 }
772 }
773 }
774 }
775 }
776 // If "Default (include before if root flag is set)" is set OR
777 // "Always include before this template record" AND root-flag are set
778 if ($row['static_file_mode'] == 1 || $row['static_file_mode'] == 0 && substr($templateID, 0, 4) == 'sys_' && $row['root']) {
779 $this->addExtensionStatics($idList, $templateID, $pid, $row);
780 }
781 // Include Static Template Records after all other TypoScript has been included.
782 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSourcesAtEnd'])) {
783 $_params = array(
784 'idList' => &$idList,
785 'templateId' => &$templateID,
786 'pid' => &$pid,
787 'row' => &$row
788 );
789 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSourcesAtEnd'] as $_funcRef) {
790 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
791 }
792 }
793 }
794
795 /**
796 * Adds the default TypoScript files for extensions if any.
797 *
798 * @param string $idList A list of already processed template ids including the current; The list is on the form "[prefix]_[uid]" where [prefix] is "sys" for "sys_template" records, "static" for "static_template" records and "ext_" for static include files (from extensions). The list is used to check that the recursive inclusion of templates does not go into circles: Simply it is used to NOT include a template record/file which has already BEEN included somewhere in the recursion.
799 * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
800 * @param array $pid The PID of the input template record
801 * @param array $row A full TypoScript template record
802 * @return void
803 * @access private
804 * @see includeStaticTypoScriptSources()
805 * @todo Define visibility
806 */
807 public function addExtensionStatics($idList, $templateID, $pid, $row) {
808 $this->extensionStaticsProcessed = TRUE;
809
810 // @TODO: Change to use new API
811 foreach ($GLOBALS['TYPO3_LOADED_EXT'] as $extKey => $files) {
812 if ((is_array($files) || $files instanceof \ArrayAccess) && ($files['ext_typoscript_constants.txt'] || $files['ext_typoscript_setup.txt'])) {
813 $mExtKey = str_replace('_', '', $extKey);
814 $subrow = array(
815 'constants' => $files['ext_typoscript_constants.txt'] ? GeneralUtility::getUrl($files['ext_typoscript_constants.txt']) : '',
816 'config' => $files['ext_typoscript_setup.txt'] ? GeneralUtility::getUrl($files['ext_typoscript_setup.txt']) : '',
817 'title' => $extKey,
818 'uid' => $mExtKey
819 );
820 $subrow = $this->prependStaticExtra($subrow);
821 $extPath = ExtensionManagementUtility::extPath($extKey);
822 $this->processTemplate($subrow, $idList . ',ext_' . $mExtKey, $pid, 'ext_' . $mExtKey, $templateID, $extPath);
823 }
824 }
825 }
826
827 /**
828 * Appends (not prepends) additional TypoScript code to static template records/files as set in TYPO3_CONF_VARS
829 * For DB records the "uid" value is the integer of the "static_template" record.
830 * For files the "uid" value is the extension key but with any underscores removed. Possibly with a path if its a static file selected in the template record
831 *
832 * @param array $subrow Static template record/file
833 * @return array Returns the input array where the values for keys "config" and "constants" may have been modified with prepended code.
834 * @access private
835 * @see addExtensionStatics(), includeStaticTypoScriptSources()
836 * @todo Define visibility
837 */
838 public function prependStaticExtra($subrow) {
839 // the identifier can be "43" if coming from "static template" extension or a path like "cssstyledcontent/static/"
840 $identifier = $subrow['uid'];
841 $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.'][$identifier];
842 $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.'][$identifier];
843 // if this is a template of type "default content rendering", also see if other extensions have added their TypoScript that should be included after the content definitions
844 if (in_array($identifier, $GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'], TRUE)) {
845 $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.']['defaultContentRendering'];
846 $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.']['defaultContentRendering'];
847 }
848 return $subrow;
849 }
850
851 /**
852 * Creating versioning overlay of a sys_template record.
853 * This will use either frontend or backend overlay functionality depending on environment.
854 *
855 * @param array $row Row to overlay (passed by reference)
856 * @return void
857 * @todo Define visibility
858 */
859 public function versionOL(&$row) {
860 // Distinguish frontend and backend call:
861 // To do the fronted call a full frontend is required, just checking for
862 // TYPO3_MODE === 'FE' is not enough. This could otherwise lead to fatals in
863 // eId scripts that run in frontend scope, but do not have a full blown frontend.
864 if (is_object($GLOBALS['TSFE']) === TRUE && property_exists($GLOBALS['TSFE'], 'sys_page') === TRUE && method_exists($GLOBALS['TSFE']->sys_page, 'versionOL') === TRUE) {
865 // Frontend
866 $GLOBALS['TSFE']->sys_page->versionOL('sys_template', $row);
867 } else {
868 // Backend
869 \TYPO3\CMS\Backend\Utility\BackendUtility::workspaceOL('sys_template', $row);
870 }
871 }
872
873 /*******************************************************************
874 *
875 * Parsing TypoScript code text from Template Records into PHP array
876 *
877 *******************************************************************/
878 /**
879 * Generates the configuration array by replacing constants and parsing the whole thing.
880 * Depends on $this->config and $this->constants to be set prior to this! (done by processTemplate/runThroughTemplates)
881 *
882 * @return void
883 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser, start()
884 * @todo Define visibility
885 */
886 public function generateConfig() {
887 // Add default TS for all code types
888 $this->addDefaultTypoScript();
889
890 // Parse the TypoScript code text for include-instructions!
891 $this->processIncludes();
892 // These vars are also set lateron...
893 $this->setup['sitetitle'] = $this->sitetitle;
894 // ****************************
895 // Parse TypoScript Constants
896 // ****************************
897 // Initialize parser and match-condition classes:
898 /** @var $constants \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser */
899 $constants = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\TypoScript\\Parser\\TypoScriptParser');
900 $constants->breakPointLN = (int)$this->ext_constants_BRP;
901 $constants->setup = $this->mergeConstantsFromPageTSconfig(array());
902 /** @var $matchObj \TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher */
903 $matchObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Frontend\\Configuration\\TypoScript\\ConditionMatching\\ConditionMatcher');
904 $matchObj->setSimulateMatchConditions($this->matchAlternative);
905 $matchObj->setSimulateMatchResult((bool) $this->matchAll);
906 // Traverse constants text fields and parse them
907 foreach ($this->constants as $str) {
908 $constants->parse($str, $matchObj);
909 }
910 // Read out parse errors if any
911 $this->parserErrors['constants'] = $constants->errors;
912 // Then flatten the structure from a multi-dim array to a single dim array with all constants listed as key/value pairs (ready for substitution)
913 $this->flatSetup = array();
914 $this->flattenSetup($constants->setup, '', '');
915 // ***********************************************
916 // Parse TypoScript Setup (here called "config")
917 // ***********************************************
918 // Initialize parser and match-condition classes:
919 /** @var $config \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser */
920 $config = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\TypoScript\\Parser\\TypoScriptParser');
921 $config->breakPointLN = (int)$this->ext_config_BRP;
922 $config->regLinenumbers = $this->ext_regLinenumbers;
923 $config->regComments = $this->ext_regComments;
924 $config->setup = $this->setup;
925 // Transfer information about conditions found in "Constants" and which of them returned TRUE.
926 $config->sections = $constants->sections;
927 $config->sectionsMatch = $constants->sectionsMatch;
928 // Traverse setup text fields and concatenate them into one, single string separated by a [GLOBAL] condition
929 $all = '';
930 foreach ($this->config as $str) {
931 $all .= '
932 [GLOBAL]
933 ' . $str;
934 }
935 // Substitute constants in the Setup code:
936 if ($this->tt_track) {
937 $GLOBALS['TT']->push('Substitute Constants (' . count($this->flatSetup) . ')');
938 }
939 $all = $this->substituteConstants($all);
940 if ($this->tt_track) {
941 $GLOBALS['TT']->pull();
942 }
943 // Searching for possible unsubstituted constants left (only for information)
944 if (strstr($all, '{$')) {
945 $theConstList = array();
946 $findConst = explode('{$', $all);
947 array_shift($findConst);
948 foreach ($findConst as $constVal) {
949 $constLen = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange(strcspn($constVal, '}'), 0, 50);
950 $theConstList[] = '{$' . substr($constVal, 0, ($constLen + 1));
951 }
952 if ($this->tt_track) {
953 $GLOBALS['TT']->setTSlogMessage(implode(', ', $theConstList) . ': Constants may remain un-substituted!!', 2);
954 }
955 }
956 // Logging the textual size of the TypoScript Setup field text with all constants substituted:
957 if ($this->tt_track) {
958 $GLOBALS['TT']->setTSlogMessage('TypoScript template size as textfile: ' . strlen($all) . ' bytes');
959 }
960 // Finally parse the Setup field TypoScript code (where constants are now substituted)
961 $config->parse($all, $matchObj);
962 // Read out parse errors if any
963 $this->parserErrors['config'] = $config->errors;
964 // Transfer the TypoScript array from the parser object to the internal $this->setup array:
965 $this->setup = $config->setup;
966 if ($this->backend_info) {
967 // Used for backend purposes only
968 $this->setup_constants = $constants->setup;
969 }
970 // ****************************************************************
971 // Final processing of the $this->setup TypoScript Template array
972 // Basically: This is unsetting/setting of certain reserved keys.
973 // ****************************************************************
974 // These vars are allready set after 'processTemplate', but because $config->setup overrides them (in the line above!), we set them again. They are not changed compared to the value they had in the top of the page!
975 unset($this->setup['sitetitle']);
976 unset($this->setup['sitetitle.']);
977 $this->setup['sitetitle'] = $this->sitetitle;
978 // Unsetting some vars...
979 unset($this->setup['types.']);
980 unset($this->setup['types']);
981 if (is_array($this->setup)) {
982 foreach ($this->setup as $key => $value) {
983 if ($value == 'PAGE') {
984 // Set the typeNum of the current page object:
985 if (isset($this->setup[$key . '.']['typeNum'])) {
986 $typeNum = $this->setup[$key . '.']['typeNum'];
987 $this->setup['types.'][$typeNum] = $key;
988 } elseif (!isset($this->setup['types.'][0]) || !$this->setup['types.'][0]) {
989 $this->setup['types.'][0] = $key;
990 }
991 }
992 }
993 }
994 unset($this->setup['temp.']);
995 unset($constants);
996 // Storing the conditions found/matched information:
997 $this->sections = $config->sections;
998 $this->sectionsMatch = $config->sectionsMatch;
999 }
1000
1001 /**
1002 * Searching TypoScript code text (for constants and config (Setup))
1003 * for include instructions and does the inclusion of external TypoScript files
1004 * if needed.
1005 *
1006 * @return void
1007 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser, generateConfig()
1008 */
1009 public function processIncludes() {
1010 if ($this->processIncludesHasBeenRun) {
1011 return;
1012 }
1013
1014 $paths = $this->templateIncludePaths;
1015 $files = array();
1016 foreach ($this->constants as &$value) {
1017 $includeData = \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines($value, 1, TRUE, array_shift($paths));
1018 $files = array_merge($files, $includeData['files']);
1019 $value = $includeData['typoscript'];
1020 }
1021 unset($value);
1022 $paths = $this->templateIncludePaths;
1023 foreach ($this->config as &$value) {
1024 $includeData = \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines($value, 1, TRUE, array_shift($paths));
1025 $files = array_merge($files, $includeData['files']);
1026 $value = $includeData['typoscript'];
1027 }
1028 unset($value);
1029
1030 if (!empty($files)) {
1031 $files = array_unique($files);
1032 foreach ($files as $file) {
1033 $this->rowSum[] = array($file, filemtime($file));
1034 }
1035 }
1036
1037 $this->processIncludesHasBeenRun = TRUE;
1038 }
1039
1040 /**
1041 * Loads Page TSconfig until the outermost template record and parses the configuration - if TSFE.constants object path is found it is merged with the default data in here!
1042 *
1043 * @param array $constArray Constants array, default input.
1044 * @return array Constants array, modified
1045 * @todo Apply caching to the parsed Page TSconfig. This is done in the other similar functions for both frontend and backend. However, since this functions works for BOTH frontend and backend we will have to either write our own local caching function or (more likely) detect if we are in FE or BE and use caching functions accordingly. Not having caching affects mostly the backend modules inside the "Template" module since the overhead in the frontend is only seen when TypoScript templates are parsed anyways (after which point they are cached anyways...)
1046 * @todo Define visibility
1047 */
1048 public function mergeConstantsFromPageTSconfig($constArray) {
1049 $TSdataArray = array();
1050 // Setting default configuration:
1051 $TSdataArray[] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];
1052 for ($a = 0; $a <= $this->outermostRootlineIndexWithTemplate; $a++) {
1053 $TSdataArray[] = $this->absoluteRootLine[$a]['TSconfig'];
1054 }
1055 // Parsing the user TS (or getting from cache)
1056 $TSdataArray = \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser::checkIncludeLines_array($TSdataArray);
1057 $userTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
1058 /** @var $parseObj \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser */
1059 $parseObj = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\TypoScript\\Parser\\TypoScriptParser');
1060 $parseObj->parse($userTS);
1061 if (is_array($parseObj->setup['TSFE.']['constants.'])) {
1062 \TYPO3\CMS\Core\Utility\ArrayUtility::mergeRecursiveWithOverrule($constArray, $parseObj->setup['TSFE.']['constants.']);
1063 }
1064 return $constArray;
1065 }
1066
1067 /**
1068 * This flattens a hierarchical TypoScript array to $this->flatSetup
1069 *
1070 * @param array $setupArray TypoScript array
1071 * @param string $prefix Prefix to the object path. Used for recursive calls to this function.
1072 * @return void
1073 * @see generateConfig()
1074 * @todo Define visibility
1075 */
1076 public function flattenSetup($setupArray, $prefix) {
1077 if (is_array($setupArray)) {
1078 foreach ($setupArray as $key => $val) {
1079 if ($prefix || substr($key, 0, 16) != 'TSConstantEditor') {
1080 // We don't want 'TSConstantEditor' in the flattend setup on the first level (190201)
1081 if (is_array($val)) {
1082 $this->flattenSetup($val, $prefix . $key);
1083 } else {
1084 $this->flatSetup[$prefix . $key] = $val;
1085 }
1086 }
1087 }
1088 }
1089 }
1090
1091 /**
1092 * Substitutes the constants from $this->flatSetup in the text string $all
1093 *
1094 * @param string $all TypoScript code text string
1095 * @return string The processed string with all constants found in $this->flatSetup as key/value pairs substituted.
1096 * @see generateConfig(), flattenSetup()
1097 * @todo Define visibility
1098 */
1099 public function substituteConstants($all) {
1100 if ($this->tt_track) {
1101 $GLOBALS['TT']->setTSlogMessage('Constants to substitute: ' . count($this->flatSetup));
1102 }
1103 $noChange = FALSE;
1104 // Recursive substitution of constants (up to 10 nested levels)
1105 for ($i = 0; $i < 10 && !$noChange; $i++) {
1106 $old_all = $all;
1107 $all = preg_replace_callback('/\\{\\$(.[^}]*)\\}/', array($this, 'substituteConstantsCallBack'), $all);
1108 if ($old_all == $all) {
1109 $noChange = TRUE;
1110 }
1111 }
1112 return $all;
1113 }
1114
1115 /**
1116 * Call back method for preg_replace_callback in substituteConstants
1117 *
1118 * @param array $matches Regular expression matches
1119 * @return string Replacement
1120 * @see substituteConstants()
1121 * @todo Define visibility
1122 */
1123 public function substituteConstantsCallBack($matches) {
1124 // Replace {$CONST} if found in $this->flatSetup, else leave unchanged
1125 return isset($this->flatSetup[$matches[1]]) && !is_array($this->flatSetup[$matches[1]]) ? $this->flatSetup[$matches[1]] : $matches[0];
1126 }
1127
1128 /*******************************************************************
1129 *
1130 * Various API functions, used from elsewhere in the frontend classes
1131 *
1132 *******************************************************************/
1133 /**
1134 * Implementation of the "optionSplit" feature in TypoScript (used eg. for MENU objects)
1135 * What it does is to split the incoming TypoScript array so that the values are exploded by certain strings ("||" and "|*|") and each part distributed into individual TypoScript arrays with a similar structure, but individualized values.
1136 * The concept is known as "optionSplit" and is rather advanced to handle but quite powerful, in particular for creating menus in TYPO3.
1137 *
1138 * @param array $conf A TypoScript array
1139 * @param integer $splitCount The number of items for which to generated individual TypoScript arrays
1140 * @return array The individualized TypoScript array.
1141 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::IMGTEXT(), \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::procesItemStates()
1142 * @todo Define visibility
1143 */
1144 public function splitConfArray($conf, $splitCount) {
1145 // Initialize variables:
1146 $splitCount = (int)$splitCount;
1147 $conf2 = array();
1148 if ($splitCount && is_array($conf)) {
1149 // Initialize output to carry at least the keys:
1150 for ($aKey = 0; $aKey < $splitCount; $aKey++) {
1151 $conf2[$aKey] = array();
1152 }
1153 // Recursive processing of array keys:
1154 foreach ($conf as $cKey => $val) {
1155 if (is_array($val)) {
1156 $tempConf = $this->splitConfArray($val, $splitCount);
1157 foreach ($tempConf as $aKey => $val) {
1158 $conf2[$aKey][$cKey] = $val;
1159 }
1160 } else {
1161 // Splitting of all values on this level of the TypoScript object tree:
1162 if (!strstr($val, '|*|') && !strstr($val, '||')) {
1163 for ($aKey = 0; $aKey < $splitCount; $aKey++) {
1164 $conf2[$aKey][$cKey] = $val;
1165 }
1166 } else {
1167 $main = explode('|*|', $val);
1168 $mainCount = count($main);
1169 $lastC = 0;
1170 $middleC = 0;
1171 $firstC = 0;
1172 if ($main[0]) {
1173 $first = explode('||', $main[0]);
1174 $firstC = count($first);
1175 }
1176 if ($main[1]) {
1177 $middle = explode('||', $main[1]);
1178 $middleC = count($middle);
1179 }
1180 if ($main[2]) {
1181 $last = explode('||', $main[2]);
1182 $lastC = count($last);
1183 $value = $last[0];
1184 }
1185 for ($aKey = 0; $aKey < $splitCount; $aKey++) {
1186 if ($firstC && isset($first[$aKey])) {
1187 $value = $first[$aKey];
1188 } elseif ($middleC) {
1189 $value = $middle[($aKey - $firstC) % $middleC];
1190 }
1191 if ($lastC && $lastC >= $splitCount - $aKey) {
1192 $value = $last[$lastC - ($splitCount - $aKey)];
1193 }
1194 $conf2[$aKey][$cKey] = trim($value);
1195 }
1196 }
1197 }
1198 }
1199 }
1200 return $conf2;
1201 }
1202
1203 /**
1204 * Returns the reference used for the frontend inclusion, checks against allowed paths for inclusion.
1205 *
1206 * @param string $fileFromSetup TypoScript "resource" data type value.
1207 * @return string Resulting filename, is either a full absolute URL or a relative path
1208 */
1209 public function getFileName($fileFromSetup) {
1210 $file = trim($fileFromSetup);
1211 if (!$file) {
1212 return;
1213 } elseif (strpos($file, '../') !== FALSE) {
1214 if ($this->tt_track) {
1215 $GLOBALS['TT']->setTSlogMessage('File path "' . $file . '" contained illegal string "../"!', 3);
1216 }
1217 return;
1218 }
1219 // Cache
1220 $hash = md5($file);
1221 if (isset($this->fileCache[$hash])) {
1222 return $this->fileCache[$hash];
1223 }
1224
1225 // if this is an URL, it can be returned directly
1226 $urlScheme = parse_url($file, PHP_URL_SCHEME);
1227 if ($urlScheme === 'https' || $urlScheme === 'http') {
1228 return $file;
1229 }
1230
1231 // this call also resolves EXT:myext/ files
1232 $file = GeneralUtility::getFileAbsFileName($file);
1233 if (!$file) {
1234 if ($this->tt_track) {
1235 $GLOBALS['TT']->setTSlogMessage('File "' . $fileFromSetup . '" was not found!', 3);
1236 }
1237 return;
1238 }
1239
1240 $file = \TYPO3\CMS\Core\Utility\PathUtility::stripPathSitePrefix($file);
1241
1242 // Check if the found file is in the allowed paths
1243 foreach ($this->allowedPaths as $val) {
1244 if (GeneralUtility::isFirstPartOfStr($file, $val)) {
1245 $this->fileCache[$hash] = $file;
1246 return $file;
1247 }
1248 }
1249
1250 if ($this->tt_track) {
1251 $GLOBALS['TT']->setTSlogMessage('"' . $file . '" was not located in the allowed paths: (' . implode(',', $this->allowedPaths) . ')', 3);
1252 }
1253 }
1254
1255 /**
1256 * Compiles the content for the page <title> tag.
1257 *
1258 * @param string $pageTitle The input title string, typically the "title" field of a page's record.
1259 * @param boolean $noTitle If set, then only the site title is outputted (from $this->setup['sitetitle'])
1260 * @param boolean $showTitleFirst If set, then "sitetitle" and $title is swapped
1261 * @return string The page title on the form "[sitetitle]: [input-title]". Not htmlspecialchar()'ed.
1262 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::tempPageCacheContent(), TSpagegen::renderContentWithHeader()
1263 * @todo Define visibility
1264 */
1265 public function printTitle($pageTitle, $noTitle = FALSE, $showTitleFirst = FALSE) {
1266 $siteTitle = trim($this->setup['sitetitle']);
1267 $pageTitle = $noTitle ? '' : $pageTitle;
1268 $pageTitleSeparator = '';
1269 if ($showTitleFirst) {
1270 $temp = $siteTitle;
1271 $siteTitle = $pageTitle;
1272 $pageTitle = $temp;
1273 }
1274 if ($pageTitle != '' && $siteTitle != '') {
1275 $pageTitleSeparator = ': ';
1276 if (isset($this->setup['config.']['pageTitleSeparator']) && $this->setup['config.']['pageTitleSeparator']) {
1277 $pageTitleSeparator = $this->setup['config.']['pageTitleSeparator'];
1278
1279 if (is_object($GLOBALS['TSFE']->cObj) && isset($this->setup['config.']['pageTitleSeparator.']) && is_array($this->setup['config.']['pageTitleSeparator.'])) {
1280 $pageTitleSeparator = $GLOBALS['TSFE']->cObj->stdWrap($pageTitleSeparator, $this->setup['config.']['pageTitleSeparator.']);
1281 } else {
1282 $pageTitleSeparator .= ' ';
1283 }
1284 }
1285 }
1286 return $siteTitle . $pageTitleSeparator . $pageTitle;
1287 }
1288
1289 /**
1290 * Reads the fileContent of $fileName and returns it.
1291 * Similar to GeneralUtility::getUrl() but with an additional check if the path is allowed
1292 *
1293 * @param string $fileName Absolute filepath to record
1294 * @return NULL|string The content returned
1295 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::fileResource(), \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::MULTIMEDIA(), GeneralUtility::getUrl()
1296 * @todo Define visibility
1297 */
1298 public function fileContent($fileName) {
1299 $fileName = $this->getFileName($fileName);
1300 if ($fileName) {
1301 return GeneralUtility::getUrl($fileName);
1302 }
1303 return NULL;
1304 }
1305
1306 /**
1307 * Ordinary "wrapping" function. Used in the AbstractMenuContentObject class and extension classes instead of the similar function in ContentObjectRenderer
1308 *
1309 * @param string $content The content to wrap
1310 * @param string $wrap The wrap value, eg. "<strong> | </strong>
1311 * @return string Wrapped input string
1312 * @deprecated since TYPO3 CMS 6.3, remove later - use \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::wrap() instead
1313 * @see \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject, \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::wrap()
1314 * @todo Define visibility
1315 */
1316 public function wrap($content, $wrap) {
1317 GeneralUtility::logDeprecatedFunction();
1318 if ($wrap) {
1319 $wrapArr = explode('|', $wrap);
1320 return trim($wrapArr[0]) . $content . trim($wrapArr[1]);
1321 } else {
1322 return $content;
1323 }
1324 }
1325
1326 /**
1327 * Removes the "?" of input string IF the "?" is the last character.
1328 *
1329 * @param string $url Input string
1330 * @return string Output string, free of "?" in the end, if any such character.
1331 * @see linkData(), \TYPO3\CMS\Frontend\Page\FramesetRenderer::frameParams()
1332 * @todo Define visibility
1333 */
1334 public function removeQueryString($url) {
1335 if (substr($url, -1) == '?') {
1336 return substr($url, 0, -1);
1337 } else {
1338 return $url;
1339 }
1340 }
1341
1342 /**
1343 * Takes a TypoScript array as input and returns an array which contains all integer properties found which had a value (not only properties). The output array will be sorted numerically.
1344 * Call it like \TYPO3\CMS\Core\TypoScript\TemplateService::sortedKeyList()
1345 *
1346 * @param array $setupArr TypoScript array with numerical array in
1347 * @param boolean $acceptOnlyProperties If set, then a value is not required - the properties alone will be enough.
1348 * @return array An array with all integer properties listed in numeric order.
1349 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::cObjGet(), \TYPO3\CMS\Frontend\Imaging\GifBuilder, \TYPO3\CMS\Frontend\ContentObject\Menu\ImageMenuContentObject::makeImageMap()
1350 */
1351 static public function sortedKeyList($setupArr, $acceptOnlyProperties = FALSE) {
1352 $keyArr = array();
1353 $setupArrKeys = array_keys($setupArr);
1354 foreach ($setupArrKeys as $key) {
1355 if ($acceptOnlyProperties || \TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($key)) {
1356 $keyArr[] = (int)$key;
1357 }
1358 }
1359 $keyArr = array_unique($keyArr);
1360 sort($keyArr);
1361 return $keyArr;
1362 }
1363
1364 /**
1365 * Returns the level of the given page in the rootline - Multiple pages can be given by separating the UIDs by comma.
1366 *
1367 * @param string $list A list of UIDs for which the rootline-level should get returned
1368 * @return integer The level in the rootline. If more than one page was given the lowest level will get returned.
1369 * @todo Define visibility
1370 */
1371 public function getRootlineLevel($list) {
1372 $idx = 0;
1373 foreach ($this->rootLine as $page) {
1374 if (GeneralUtility::inList($list, $page['uid'])) {
1375 return $idx;
1376 }
1377 $idx++;
1378 }
1379 return FALSE;
1380 }
1381
1382 /*******************************************************************
1383 *
1384 * Functions for creating links
1385 *
1386 *******************************************************************/
1387 /**
1388 * The mother of all functions creating links/URLs etc in a TypoScript environment.
1389 * See the references below.
1390 * Basically this function takes care of issues such as type,id,alias and Mount Points, URL rewriting (through hooks), M5/B6 encoded parameters etc.
1391 * It is important to pass all links created through this function since this is the guarantee that globally configured settings for link creating are observed and that your applications will conform to the various/many configuration options in TypoScript Templates regarding this.
1392 *
1393 * @param array $page The page record of the page to which we are creating a link. Needed due to fields like uid, alias, target, no_cache, title and sectionIndex_uid.
1394 * @param string $oTarget Default target string to use IF not $page['target'] is set.
1395 * @param boolean $no_cache If set, then the "&no_cache=1" parameter is included in the URL.
1396 * @param string $script Alternative script name if you don't want to use $GLOBALS['TSFE']->config['mainScript'] (normally set to "index.php")
1397 * @param array $overrideArray Array with overriding values for the $page array.
1398 * @param string $addParams Additional URL parameters to set in the URL. Syntax is "&foo=bar&foo2=bar2" etc. Also used internally to add parameters if needed.
1399 * @param string $typeOverride If you set this value to something else than a blank string, then the typeNumber used in the link will be forced to this value. Normally the typeNum is based on the target set OR on $GLOBALS['TSFE']->config['config']['forceTypeValue'] if found.
1400 * @param string $targetDomain The target Doamin, if any was detected in typolink
1401 * @return array Contains keys like "totalURL", "url", "sectionIndex", "linkVars", "no_cache", "type", "target" of which "totalURL" is normally the value you would use while the other keys contains various parts that was used to construct "totalURL
1402 * @see \TYPO3\CMS\Frontend\Page\FramesetRenderer::frameParams(), \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::typoLink(), \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::SEARCHRESULT(), TSpagegen::pagegenInit(), \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::link()
1403 * @todo Define visibility
1404 */
1405 public function linkData($page, $oTarget, $no_cache, $script, $overrideArray = NULL, $addParams = '', $typeOverride = '', $targetDomain = '') {
1406 $LD = array();
1407 // Overriding some fields in the page record and still preserves the values by adding them as parameters. Little strange function.
1408 if (is_array($overrideArray)) {
1409 foreach ($overrideArray as $theKey => $theNewVal) {
1410 $addParams .= '&real_' . $theKey . '=' . rawurlencode($page[$theKey]);
1411 $page[$theKey] = $theNewVal;
1412 }
1413 }
1414 // Adding Mount Points, "&MP=", parameter for the current page if any is set:
1415 if (!strstr($addParams, '&MP=')) {
1416 // Looking for hardcoded defaults:
1417 if (trim($GLOBALS['TSFE']->MP_defaults[$page['uid']])) {
1418 $addParams .= '&MP=' . rawurlencode(trim($GLOBALS['TSFE']->MP_defaults[$page['uid']]));
1419 } elseif ($GLOBALS['TSFE']->config['config']['MP_mapRootPoints']) {
1420 // Else look in automatically created map:
1421 $m = $this->getFromMPmap($page['uid']);
1422 if ($m) {
1423 $addParams .= '&MP=' . rawurlencode($m);
1424 }
1425 }
1426 }
1427 // Setting ID/alias:
1428 if (!$script) {
1429 $script = $GLOBALS['TSFE']->config['mainScript'];
1430 }
1431 if ($page['alias']) {
1432 $LD['url'] = $script . '?id=' . rawurlencode($page['alias']);
1433 } else {
1434 $LD['url'] = $script . '?id=' . $page['uid'];
1435 }
1436 // Setting target
1437 $LD['target'] = trim($page['target']) ?: $oTarget;
1438 // typeNum
1439 $typeNum = $this->setup[$LD['target'] . '.']['typeNum'];
1440 if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($typeOverride) && (int)$GLOBALS['TSFE']->config['config']['forceTypeValue']) {
1441 $typeOverride = (int)$GLOBALS['TSFE']->config['config']['forceTypeValue'];
1442 }
1443 if ((string)$typeOverride !== '') {
1444 $typeNum = $typeOverride;
1445 }
1446 // Override...
1447 if ($typeNum) {
1448 $LD['type'] = '&type=' . (int)$typeNum;
1449 } else {
1450 $LD['type'] = '';
1451 }
1452 // Preserving the type number.
1453 $LD['orig_type'] = $LD['type'];
1454 // noCache
1455 $LD['no_cache'] = trim($page['no_cache']) || $no_cache ? '&no_cache=1' : '';
1456 // linkVars
1457 if ($GLOBALS['TSFE']->config['config']['uniqueLinkVars']) {
1458 if ($addParams) {
1459 $LD['linkVars'] = GeneralUtility::implodeArrayForUrl('', GeneralUtility::explodeUrl2Array($GLOBALS['TSFE']->linkVars . $addParams), '', FALSE, TRUE);
1460 } else {
1461 $LD['linkVars'] = $GLOBALS['TSFE']->linkVars;
1462 }
1463 } else {
1464 $LD['linkVars'] = $GLOBALS['TSFE']->linkVars . $addParams;
1465 }
1466 // Add absRefPrefix if exists.
1467 $LD['url'] = $GLOBALS['TSFE']->absRefPrefix . $LD['url'];
1468 // If the special key 'sectionIndex_uid' (added 'manually' in tslib/menu.php to the page-record) is set, then the link jumps directly to a section on the page.
1469 $LD['sectionIndex'] = $page['sectionIndex_uid'] ? '#c' . $page['sectionIndex_uid'] : '';
1470 // Compile the normal total url
1471 $LD['totalURL'] = $this->removeQueryString(($LD['url'] . $LD['type'] . $LD['no_cache'] . $LD['linkVars'] . $GLOBALS['TSFE']->getMethodUrlIdToken)) . $LD['sectionIndex'];
1472 // Call post processing function for link rendering:
1473 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['linkData-PostProc'])) {
1474 $_params = array(
1475 'LD' => &$LD,
1476 'args' => array('page' => $page, 'oTarget' => $oTarget, 'no_cache' => $no_cache, 'script' => $script, 'overrideArray' => $overrideArray, 'addParams' => $addParams, 'typeOverride' => $typeOverride, 'targetDomain' => $targetDomain),
1477 'typeNum' => $typeNum
1478 );
1479 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['linkData-PostProc'] as $_funcRef) {
1480 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1481 }
1482 }
1483 // Return the LD-array
1484 return $LD;
1485 }
1486
1487 /**
1488 * Initializes the automatically created MPmap coming from the "config.MP_mapRootPoints" setting
1489 * Can be called many times with overhead only the first time since then the map is generated and cached in memory.
1490 *
1491 * @param integer $pageId Page id to return MPvar value for.
1492 * @return string
1493 * @see initMPmap_create()
1494 * @todo Implement some caching of the result between hits. (more than just the memory caching used here)
1495 * @todo Define visibility
1496 */
1497 public function getFromMPmap($pageId = 0) {
1498 // Create map if not found already:
1499 if (!is_array($this->MPmap)) {
1500 $this->MPmap = array();
1501 $rootPoints = GeneralUtility::trimExplode(',', strtolower($GLOBALS['TSFE']->config['config']['MP_mapRootPoints']), TRUE);
1502 // Traverse rootpoints:
1503 foreach ($rootPoints as $p) {
1504 if ($p == 'root') {
1505 $p = $this->rootLine[0]['uid'];
1506 $initMParray = array();
1507 if ($this->rootLine[0]['_MOUNT_OL'] && $this->rootLine[0]['_MP_PARAM']) {
1508 $initMParray[] = $this->rootLine[0]['_MP_PARAM'];
1509 }
1510 }
1511 $this->initMPmap_create($p, $initMParray);
1512 }
1513 }
1514 // Finding MP var for Page ID:
1515 if ($pageId) {
1516 if (is_array($this->MPmap[$pageId]) && count($this->MPmap[$pageId])) {
1517 return implode(',', $this->MPmap[$pageId]);
1518 }
1519 }
1520 }
1521
1522 /**
1523 * Creating MPmap for a certain ID root point.
1524 *
1525 * @param integer $id Root id from which to start map creation.
1526 * @param array $MP_array MP_array passed from root page.
1527 * @param integer $level Recursion brake. Incremented for each recursive call. 20 is the limit.
1528 * @return void
1529 * @see getFromMPvar()
1530 * @todo Define visibility
1531 */
1532 public function initMPmap_create($id, $MP_array = array(), $level = 0) {
1533 $id = (int)$id;
1534 if ($id <= 0) {
1535 return;
1536 }
1537 // First level, check id
1538 if (!$level) {
1539 // Find mount point if any:
1540 $mount_info = $GLOBALS['TSFE']->sys_page->getMountPointInfo($id);
1541 // Overlay mode:
1542 if (is_array($mount_info) && $mount_info['overlay']) {
1543 $MP_array[] = $mount_info['MPvar'];
1544 $id = $mount_info['mount_pid'];
1545 }
1546 // Set mapping information for this level:
1547 $this->MPmap[$id] = $MP_array;
1548 // Normal mode:
1549 if (is_array($mount_info) && !$mount_info['overlay']) {
1550 $MP_array[] = $mount_info['MPvar'];
1551 $id = $mount_info['mount_pid'];
1552 }
1553 }
1554 if ($id && $level < 20) {
1555 $nextLevelAcc = array();
1556 // Select and traverse current level pages:
1557 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,pid,doktype,mount_pid,mount_pid_ol', 'pages', 'pid=' . (int)$id . ' AND deleted=0 AND doktype<>' . \TYPO3\CMS\Frontend\Page\PageRepository::DOKTYPE_RECYCLER . ' AND doktype<>' . \TYPO3\CMS\Frontend\Page\PageRepository::DOKTYPE_BE_USER_SECTION);
1558 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
1559 // Find mount point if any:
1560 $next_id = $row['uid'];
1561 $next_MP_array = $MP_array;
1562 $mount_info = $GLOBALS['TSFE']->sys_page->getMountPointInfo($next_id, $row);
1563 // Overlay mode:
1564 if (is_array($mount_info) && $mount_info['overlay']) {
1565 $next_MP_array[] = $mount_info['MPvar'];
1566 $next_id = $mount_info['mount_pid'];
1567 }
1568 if (!isset($this->MPmap[$next_id])) {
1569 // Set mapping information for this level:
1570 $this->MPmap[$next_id] = $next_MP_array;
1571 // Normal mode:
1572 if (is_array($mount_info) && !$mount_info['overlay']) {
1573 $next_MP_array[] = $mount_info['MPvar'];
1574 $next_id = $mount_info['mount_pid'];
1575 }
1576 // Register recursive call
1577 // (have to do it this way since ALL of the current level should be registered BEFORE the sublevel at any time)
1578 $nextLevelAcc[] = array($next_id, $next_MP_array);
1579 }
1580 }
1581 $GLOBALS['TYPO3_DB']->sql_free_result($res);
1582 // Call recursively, if any:
1583 foreach ($nextLevelAcc as $pSet) {
1584 $this->initMPmap_create($pSet[0], $pSet[1], $level + 1);
1585 }
1586 }
1587 }
1588
1589 /**
1590 * Adds the TypoScript from the global array.
1591 * The class property isDefaultTypoScriptAdded ensures
1592 * that the adding only happens once.
1593 *
1594 * @return void
1595 * @see isDefaultTypoScriptAdded
1596 */
1597 protected function addDefaultTypoScript() {
1598 // Add default TS for all code types, if not done already
1599 if (!$this->isDefaultTypoScriptAdded) {
1600 // adding default setup and constants
1601 // defaultTypoScript_setup is *very* unlikely to be empty
1602 // the count of elements in ->constants, ->config and ->templateIncludePaths have to be in sync
1603 array_unshift($this->constants, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants']);
1604 array_unshift($this->config, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup']);
1605 array_unshift($this->templateIncludePaths, '');
1606 // prepare a proper entry to hierachyInfo (used by TemplateAnalyzer in BE)
1607 $rootTemplateId = $this->hierarchyInfo[count($this->hierarchyInfo)-1]['templateID'];
1608 $defaultTemplateInfo = array(
1609 'root' => '',
1610 'next' => '',
1611 'clConst' => '',
1612 'clConf' => '',
1613 'templateID' => '_defaultTypoScript_',
1614 'templateParent' => $rootTemplateId,
1615 'title' => 'SYS:TYPO3_CONF_VARS:FE:defaultTypoScript',
1616 'uid' => '_defaultTypoScript_',
1617 'pid' => '',
1618 'configLines' => substr_count((string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup'], LF) + 1
1619 );
1620 // push info to information arrays used in BE by TemplateTools (Analyzer)
1621 array_unshift($this->clearList_const, $defaultTemplateInfo['uid']);
1622 array_unshift($this->clearList_setup, $defaultTemplateInfo['uid']);
1623 array_unshift($this->hierarchyInfo, $defaultTemplateInfo);
1624 $this->isDefaultTypoScriptAdded = TRUE;
1625 }
1626 }
1627
1628 }