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