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