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