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