19755c62d03ca6588dbd02594a410ce04d94b284
[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 $this->tt_track = $this->verbose = (bool)$this->context->getPropertyFromAspect('backend.user', 'isLoggedIn', false);
402 }
403
404 /**
405 * @return bool
406 */
407 public function getProcessExtensionStatics()
408 {
409 return $this->processExtensionStatics;
410 }
411
412 /**
413 * @param bool $processExtensionStatics
414 */
415 public function setProcessExtensionStatics($processExtensionStatics)
416 {
417 $this->processExtensionStatics = (bool)$processExtensionStatics;
418 }
419
420 /**
421 * sets the verbose parameter
422 * @param bool $verbose
423 */
424 public function setVerbose($verbose)
425 {
426 $this->verbose = (bool)$verbose;
427 }
428
429 /**
430 * Initialize
431 *
432 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10
433 */
434 public function init()
435 {
436 trigger_error('Method will be removed in TYPO3 v10, __construct() does the job', E_USER_DEPRECATED);
437 $this->initializeDatabaseQueryRestrictions();
438 if ($this->context->getPropertyFromAspect('visibility', 'includeHiddenContent', false) || $GLOBALS['SIM_ACCESS_TIME'] !== $GLOBALS['ACCESS_TIME']) {
439 // Set the simulation flag, if simulation is detected!
440 $this->simulationHiddenOrTime = 1;
441 }
442
443 // Sets the paths from where TypoScript resources are allowed to be used:
444 $this->allowedPaths = [
445 $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'],
446 // fileadmin/ path
447 'uploads/',
448 'typo3temp/',
449 TYPO3_mainDir . 'ext/',
450 TYPO3_mainDir . 'sysext/',
451 'typo3conf/ext/'
452 ];
453 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['addAllowedPaths']) {
454 $pathArr = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['addAllowedPaths'], true);
455 foreach ($pathArr as $p) {
456 // 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.
457 $this->allowedPaths[] = $p;
458 }
459 }
460 }
461
462 /**
463 * $this->whereclause is kept for backwards compatibility
464 */
465 protected function initializeDatabaseQueryRestrictions()
466 {
467 $includeHiddenRecords = $this->context->getPropertyFromAspect('visibility', 'includeHiddenContent', false);
468 // $this->whereClause is used only to select templates from sys_template.
469 // $GLOBALS['SIM_ACCESS_TIME'] is used so that we're able to simulate a later time as a test...
470 $this->whereClause = 'AND deleted=0 ';
471 if (!$includeHiddenRecords) {
472 $this->whereClause .= 'AND hidden=0 ';
473 }
474 $this->whereClause .= 'AND (starttime<=' . $GLOBALS['SIM_ACCESS_TIME'] . ') AND (endtime=0 OR endtime>' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
475
476 // set up the query builder restrictions
477 $this->queryBuilderRestrictions = GeneralUtility::makeInstance(DefaultRestrictionContainer::class);
478
479 if ($includeHiddenRecords) {
480 $this->queryBuilderRestrictions->removeByType(HiddenRestriction::class);
481 }
482 }
483
484 /**
485 * Fetches the "currentPageData" array from cache
486 *
487 * NOTE about currentPageData:
488 * It holds information about the TypoScript conditions along with the list
489 * of template uid's which is used on the page. In the getFromCache() function
490 * in TSFE, currentPageData is used to evaluate if there is a template and
491 * if the matching conditions are alright. Unfortunately this does not take
492 * into account if the templates in the rowSum of currentPageData has
493 * changed composition, eg. due to hidden fields or start/end time. So if a
494 * template is hidden or times out, it'll not be discovered unless the page
495 * is regenerated - at least the this->start function must be called,
496 * because this will make a new portion of data in currentPageData string.
497 *
498 * @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
499 */
500 public function getCurrentPageData()
501 {
502 return GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_pagesection')->get((int)$this->getTypoScriptFrontendController()->id . '_' . GeneralUtility::md5int($this->getTypoScriptFrontendController()->MP));
503 }
504
505 /**
506 * Fetches data about which TypoScript-matches there are at this page. Then it performs a matchingtest.
507 *
508 * @param array $cc An array with three keys, "all", "rowSum" and "rootLine" - all coming from the "currentPageData" array
509 * @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.
510 */
511 public function matching($cc)
512 {
513 if (is_array($cc['all'])) {
514 /** @var ConditionMatcher $matchObj */
515 $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
516 $matchObj->setRootline((array)$cc['rootLine']);
517 $sectionsMatch = [];
518 foreach ($cc['all'] as $key => $pre) {
519 if ($matchObj->match($pre)) {
520 $sectionsMatch[$key] = $pre;
521 }
522 }
523 $cc['match'] = $sectionsMatch;
524 }
525 return $cc;
526 }
527
528 /**
529 * This is all about fetching the right TypoScript template structure. If it's not cached then it must be generated and cached!
530 * 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.
531 * Sets $this->setup to the parsed TypoScript template array
532 *
533 * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
534 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getConfigArray()
535 */
536 public function start($theRootLine)
537 {
538 if (is_array($theRootLine)) {
539 $constantsData = [];
540 $setupData = [];
541 $cacheIdentifier = '';
542 // Flag that indicates that the existing data in cache_pagesection
543 // could be used (this is the case if $TSFE->all is set, and the
544 // rowSum still matches). Based on this we decide if cache_pagesection
545 // needs to be updated...
546 $isCached = false;
547 $this->runThroughTemplates($theRootLine);
548 if ($this->getTypoScriptFrontendController()->all) {
549 $cc = $this->getTypoScriptFrontendController()->all;
550 // The two rowSums must NOT be different from each other - which they will be if start/endtime or hidden has changed!
551 if (serialize($this->rowSum) !== serialize($cc['rowSum'])) {
552 unset($cc);
553 } else {
554 // If $TSFE->all contains valid data, we don't need to update cache_pagesection (because this data was fetched from there already)
555 if (serialize($this->rootLine) === serialize($cc['rootLine'])) {
556 $isCached = true;
557 }
558 // 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)...
559 unset($cc['rootLine']);
560 }
561 }
562 // This is about getting the hash string which is used to fetch the cached TypoScript template.
563 // If there was some cached currentPageData ($cc) then that's good (it gives us the hash).
564 if (isset($cc) && is_array($cc)) {
565 // If currentPageData was actually there, we match the result (if this wasn't done already in $TSFE->getFromCache()...)
566 if (!$cc['match']) {
567 // @todo check if this can ever be the case - otherwise remove
568 $cc = $this->matching($cc);
569 ksort($cc);
570 }
571 $cacheIdentifier = md5(serialize($cc));
572 } else {
573 // 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.
574 $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
575 $result = $this->getCacheEntry($rowSumHash);
576 if (is_array($result)) {
577 $cc = [];
578 $cc['all'] = $result;
579 $cc['rowSum'] = $this->rowSum;
580 $cc = $this->matching($cc);
581 ksort($cc);
582 $cacheIdentifier = md5(serialize($cc));
583 }
584 }
585 if ($cacheIdentifier) {
586 // Get TypoScript setup array
587 $cachedData = $this->getCacheEntry($cacheIdentifier);
588 if (is_array($cachedData)) {
589 $constantsData = $cachedData['constants'];
590 $setupData = $cachedData['setup'];
591 }
592 }
593 if (!empty($setupData) && !$this->forceTemplateParsing) {
594 // TypoScript constants + setup are found in the cache
595 $this->setup_constants = $constantsData;
596 $this->setup = $setupData;
597 if ($this->tt_track) {
598 $this->getTimeTracker()->setTSlogMessage('Using cached TS template data');
599 }
600 } else {
601 if ($this->tt_track) {
602 $this->getTimeTracker()->setTSlogMessage('Not using any cached TS data');
603 }
604
605 // Make configuration
606 $this->generateConfig();
607 // This stores the template hash thing
608 $cc = [];
609 // All sections in the template at this point is found
610 $cc['all'] = $this->sections;
611 // The line of templates is collected
612 $cc['rowSum'] = $this->rowSum;
613 $cc = $this->matching($cc);
614 ksort($cc);
615 $cacheIdentifier = md5(serialize($cc));
616 // This stores the data.
617 $this->setCacheEntry($cacheIdentifier, ['constants' => $this->setup_constants, 'setup' => $this->setup], 'TS_TEMPLATE');
618 if ($this->tt_track) {
619 $this->getTimeTracker()->setTSlogMessage('TS template size, serialized: ' . strlen(serialize($this->setup)) . ' bytes');
620 }
621 $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
622 $this->setCacheEntry($rowSumHash, $cc['all'], 'TMPL_CONDITIONS_ALL');
623 }
624 // Add rootLine
625 $cc['rootLine'] = $this->rootLine;
626 ksort($cc);
627 // Make global and save
628 $this->getTypoScriptFrontendController()->all = $cc;
629 // Matching must be executed for every request, so this must never be part of the pagesection cache!
630 unset($cc['match']);
631 if (!$isCached && !$this->simulationHiddenOrTime && !$this->getTypoScriptFrontendController()->no_cache) {
632 // Only save the data if we're not simulating by hidden/starttime/endtime
633 $mpvarHash = GeneralUtility::md5int($this->getTypoScriptFrontendController()->MP);
634 /** @var \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface $pageSectionCache */
635 $pageSectionCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_pagesection');
636 $pageSectionCache->set((int)$this->getTypoScriptFrontendController()->id . '_' . $mpvarHash, $cc, [
637 'pageId_' . (int)$this->getTypoScriptFrontendController()->id,
638 'mpvarHash_' . $mpvarHash
639 ]);
640 }
641 // If everything OK.
642 if ($this->rootId && $this->rootLine && $this->setup) {
643 $this->loaded = true;
644 }
645 }
646 }
647
648 /*******************************************************************
649 *
650 * Fetching TypoScript code text for the Template Hierarchy
651 *
652 *******************************************************************/
653 /**
654 * 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.
655 * Resets and affects internal variables like $this->constants, $this->config and $this->rowSum
656 * 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
657 *
658 * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
659 * @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)
660 * @see start()
661 */
662 public function runThroughTemplates($theRootLine, $start_template_uid = 0)
663 {
664 $this->constants = [];
665 $this->config = [];
666 $this->rowSum = [];
667 $this->hierarchyInfoToRoot = [];
668 $this->absoluteRootLine = $theRootLine;
669 $this->isDefaultTypoScriptAdded = false;
670
671 reset($this->absoluteRootLine);
672 $c = count($this->absoluteRootLine);
673 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_template');
674 for ($a = 0; $a < $c; $a++) {
675 // If some template loaded before has set a template-id for the next level, then load this template first!
676 if ($this->nextLevel) {
677 $queryBuilder->setRestrictions($this->queryBuilderRestrictions);
678 $queryResult = $queryBuilder
679 ->select('*')
680 ->from('sys_template')
681 ->where(
682 $queryBuilder->expr()->eq(
683 'uid',
684 $queryBuilder->createNamedParameter($this->nextLevel, \PDO::PARAM_INT)
685 )
686 )
687 ->execute();
688 $this->nextLevel = 0;
689 if ($row = $queryResult->fetch()) {
690 $this->versionOL($row);
691 if (is_array($row)) {
692 $this->processTemplate($row, 'sys_' . $row['uid'], $this->absoluteRootLine[$a]['uid'], 'sys_' . $row['uid']);
693 $this->outermostRootlineIndexWithTemplate = $a;
694 }
695 }
696 }
697
698 $where = [
699 $queryBuilder->expr()->eq(
700 'pid',
701 $queryBuilder->createNamedParameter($this->absoluteRootLine[$a]['uid'], \PDO::PARAM_INT)
702 )
703 ];
704 // If first loop AND there is set an alternative template uid, use that
705 if ($a === $c - 1 && $start_template_uid) {
706 $where[] = $queryBuilder->expr()->eq(
707 'uid',
708 $queryBuilder->createNamedParameter($start_template_uid, \PDO::PARAM_INT)
709 );
710 }
711 $queryBuilder->setRestrictions($this->queryBuilderRestrictions);
712 $queryResult = $queryBuilder
713 ->select('*')
714 ->from('sys_template')
715 ->where(...$where)
716 ->orderBy('root', 'DESC')
717 ->addOrderBy('sorting')
718 ->setMaxResults(1)
719 ->execute();
720 if ($row = $queryResult->fetch()) {
721 $this->versionOL($row);
722 if (is_array($row)) {
723 $this->processTemplate($row, 'sys_' . $row['uid'], $this->absoluteRootLine[$a]['uid'], 'sys_' . $row['uid']);
724 $this->outermostRootlineIndexWithTemplate = $a;
725 }
726 }
727 $this->rootLine[] = $this->absoluteRootLine[$a];
728 }
729
730 // Hook into the default TypoScript to add custom typoscript logic
731 $hookParameters = [
732 'extensionStaticsProcessed' => &$this->extensionStaticsProcessed,
733 'isDefaultTypoScriptAdded' => &$this->isDefaultTypoScriptAdded,
734 'absoluteRootLine' => &$this->absoluteRootLine,
735 'rootLine' => &$this->rootLine,
736 'startTemplateUid' => $start_template_uid,
737 ];
738 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['Core/TypoScript/TemplateService']['runThroughTemplatesPostProcessing'] ?? [] as $listener) {
739 GeneralUtility::callUserFunction($listener, $hookParameters, $this);
740 }
741
742 // Process extension static files if not done yet, but explicitly requested
743 if (!$this->extensionStaticsProcessed && $this->processExtensionStatics) {
744 $this->addExtensionStatics('sys_0', 'sys_0', 0);
745 }
746
747 // Add the global default TypoScript from the TYPO3_CONF_VARS
748 $this->addDefaultTypoScript();
749
750 $this->processIncludes();
751 }
752
753 /**
754 * Checks if the template ($row) has some included templates and after including them it fills the arrays with the setup
755 * Builds up $this->rowSum
756 *
757 * @param array $row A full TypoScript template record (sys_template/forged "dummy" record made from static template file)
758 * @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.
759 * @param int $pid The PID of the input template record
760 * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
761 * @param string $templateParent Parent template id (during recursive call); Same syntax as $idList ids, eg. "sys_123
762 * @param string $includePath Specifies the path from which the template was included (used with static_includes)
763 * @see runThroughTemplates()
764 */
765 public function processTemplate($row, $idList, $pid, $templateID = '', $templateParent = '', $includePath = '')
766 {
767 // Adding basic template record information to rowSum array
768 $this->rowSum[] = [$row['uid'] ?? null, $row['title'] ?? null, $row['tstamp'] ?? null];
769 // Processing "Clear"-flags
770 $clConst = 0;
771 $clConf = 0;
772 if (!empty($row['clear'])) {
773 $clConst = $row['clear'] & 1;
774 $clConf = $row['clear'] & 2;
775 if ($clConst) {
776 // Keep amount of items to stay in sync with $this->templateIncludePaths so processIncludes() does not break
777 foreach ($this->constants as &$constantConfiguration) {
778 $constantConfiguration = '';
779 }
780 unset($constantConfiguration);
781 $this->clearList_const = [];
782 }
783 if ($clConf) {
784 // Keep amount of items to stay in sync with $this->templateIncludePaths so processIncludes() does not break
785 foreach ($this->config as &$configConfiguration) {
786 $configConfiguration = '';
787 }
788 unset($configConfiguration);
789 $this->hierarchyInfoToRoot = [];
790 $this->clearList_setup = [];
791 }
792 }
793 // Include files (from extensions) (#1/2)
794 // NORMAL inclusion, The EXACT same code is found below the basedOn inclusion!!!
795 if (!isset($row['includeStaticAfterBasedOn']) || !$row['includeStaticAfterBasedOn']) {
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);
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 && strpos($templateID, 'sys_') === 0 && $row['root']) {
965 $this->addExtensionStatics($idList, $templateID, $pid);
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 * @access private
1006 * @see includeStaticTypoScriptSources()
1007 */
1008 public function addExtensionStatics($idList, $templateID, $pid)
1009 {
1010 $this->extensionStaticsProcessed = true;
1011
1012 // @todo Change to use new API
1013 foreach ($GLOBALS['TYPO3_LOADED_EXT'] as $extKey => $files) {
1014 if ((is_array($files) || $files instanceof \ArrayAccess)
1015 && (
1016 !empty($files['ext_typoscript_constants.txt'])
1017 || !empty($files['ext_typoscript_constants.typoscript'])
1018 || !empty($files['ext_typoscript_setup.txt'])
1019 || !empty($files['ext_typoscript_setup.typoscript'])
1020 )
1021 ) {
1022 $mExtKey = str_replace('_', '', $extKey);
1023 $constants = '';
1024 $config = '';
1025
1026 if (!empty($files['ext_typoscript_constants.typoscript'])) {
1027 $constants = @file_get_contents($files['ext_typoscript_constants.typoscript']);
1028 } elseif (!empty($files['ext_typoscript_constants.txt'])) {
1029 $constants = @file_get_contents($files['ext_typoscript_constants.txt']);
1030 }
1031
1032 if (!empty($files['ext_typoscript_setup.typoscript'])) {
1033 $config = @file_get_contents($files['ext_typoscript_setup.typoscript']);
1034 } elseif (!empty($files['ext_typoscript_setup.txt'])) {
1035 $config = @file_get_contents($files['ext_typoscript_setup.txt']);
1036 }
1037
1038 $this->processTemplate(
1039 $this->prependStaticExtra([
1040 'constants' => $constants,
1041 'config' => $config,
1042 'title' => $extKey,
1043 'uid' => $mExtKey
1044 ]),
1045 $idList . ',ext_' . $mExtKey,
1046 $pid,
1047 'ext_' . $mExtKey,
1048 $templateID,
1049 ExtensionManagementUtility::extPath($extKey)
1050 );
1051 }
1052 }
1053 }
1054
1055 /**
1056 * Appends (not prepends) additional TypoScript code to static template records/files as set in TYPO3_CONF_VARS
1057 * 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
1058 *
1059 * @param array $subrow Static template record/file
1060 * @return array Returns the input array where the values for keys "config" and "constants" may have been modified with prepended code.
1061 * @access private
1062 * @see addExtensionStatics(), includeStaticTypoScriptSources()
1063 */
1064 public function prependStaticExtra($subrow)
1065 {
1066 // the identifier can be "43" if coming from "static template" extension or a path like "cssstyledcontent/static/"
1067 $identifier = $subrow['uid'];
1068 $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.'][$identifier] ?? null;
1069 $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.'][$identifier] ?? null;
1070 // 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
1071 if (in_array($identifier, $GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'], true)) {
1072 $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.']['defaultContentRendering'];
1073 $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.']['defaultContentRendering'];
1074 }
1075 return $subrow;
1076 }
1077
1078 /**
1079 * Creating versioning overlay of a sys_template record.
1080 * This will use either frontend or backend overlay functionality depending on environment.
1081 *
1082 * @param array $row Row to overlay (passed by reference)
1083 */
1084 public function versionOL(&$row)
1085 {
1086 // Distinguish frontend and backend call:
1087 // To do the fronted call a full frontend is required, just checking for
1088 // TYPO3_MODE === 'FE' is not enough. This could otherwise lead to fatals in
1089 // eId scripts that run in frontend scope, but do not have a full blown frontend.
1090 if (is_object($this->getTypoScriptFrontendController()) && property_exists($this->getTypoScriptFrontendController(), 'sys_page') && method_exists($this->getTypoScriptFrontendController()->sys_page, 'versionOL')) {
1091 // Frontend
1092 $this->getTypoScriptFrontendController()->sys_page->versionOL('sys_template', $row);
1093 } else {
1094 // Backend
1095 BackendUtility::workspaceOL('sys_template', $row);
1096 }
1097 }
1098
1099 /*******************************************************************
1100 *
1101 * Parsing TypoScript code text from Template Records into PHP array
1102 *
1103 *******************************************************************/
1104 /**
1105 * Generates the configuration array by replacing constants and parsing the whole thing.
1106 * Depends on $this->config and $this->constants to be set prior to this! (done by processTemplate/runThroughTemplates)
1107 *
1108 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser, start()
1109 */
1110 public function generateConfig()
1111 {
1112 // Add default TS for all code types
1113 $this->addDefaultTypoScript();
1114
1115 // Parse the TypoScript code text for include-instructions!
1116 $this->processIncludes();
1117 // These vars are also set lateron...
1118 $this->setup['sitetitle'] = $this->sitetitle;
1119 // ****************************
1120 // Parse TypoScript Constants
1121 // ****************************
1122 // Initialize parser and match-condition classes:
1123 /** @var Parser\TypoScriptParser $constants */
1124 $constants = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
1125 $constants->breakPointLN = (int)$this->ext_constants_BRP;
1126 $constants->setup = $this->mergeConstantsFromPageTSconfig([]);
1127 /** @var ConditionMatcher $matchObj */
1128 $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
1129 $matchObj->setSimulateMatchConditions($this->matchAlternative);
1130 $matchObj->setSimulateMatchResult((bool)$this->matchAll);
1131 // Traverse constants text fields and parse them
1132 foreach ($this->constants as $str) {
1133 $constants->parse($str, $matchObj);
1134 }
1135 // Read out parse errors if any
1136 $this->parserErrors['constants'] = $constants->errors;
1137 // 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)
1138 $this->flatSetup = [];
1139 $this->flattenSetup($constants->setup, '');
1140 // ***********************************************
1141 // Parse TypoScript Setup (here called "config")
1142 // ***********************************************
1143 // Initialize parser and match-condition classes:
1144 /** @var Parser\TypoScriptParser $config */
1145 $config = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
1146 $config->breakPointLN = (int)$this->ext_config_BRP;
1147 $config->regLinenumbers = $this->ext_regLinenumbers;
1148 $config->regComments = $this->ext_regComments;
1149 $config->setup = $this->setup;
1150 // Transfer information about conditions found in "Constants" and which of them returned TRUE.
1151 $config->sections = $constants->sections;
1152 $config->sectionsMatch = $constants->sectionsMatch;
1153 // Traverse setup text fields and concatenate them into one, single string separated by a [GLOBAL] condition
1154 $all = '';
1155 foreach ($this->config as $str) {
1156 $all .= '
1157 [GLOBAL]
1158 ' . $str;
1159 }
1160 // Substitute constants in the Setup code:
1161 if ($this->tt_track) {
1162 $this->getTimeTracker()->push('Substitute Constants (' . count($this->flatSetup) . ')');
1163 }
1164 $all = $this->substituteConstants($all);
1165 if ($this->tt_track) {
1166 $this->getTimeTracker()->pull();
1167 }
1168
1169 // Searching for possible unsubstituted constants left (only for information)
1170 if ($this->verbose) {
1171 if (preg_match_all('/\\{\\$.[^}]*\\}/', $all, $constantList) > 0) {
1172 if ($this->tt_track) {
1173 $this->getTimeTracker()->setTSlogMessage(implode(', ', $constantList[0]) . ': Constants may remain un-substituted!!', 2);
1174 }
1175 }
1176 }
1177
1178 // Logging the textual size of the TypoScript Setup field text with all constants substituted:
1179 if ($this->tt_track) {
1180 $this->getTimeTracker()->setTSlogMessage('TypoScript template size as textfile: ' . strlen($all) . ' bytes');
1181 }
1182 // Finally parse the Setup field TypoScript code (where constants are now substituted)
1183 $config->parse($all, $matchObj);
1184 // Read out parse errors if any
1185 $this->parserErrors['config'] = $config->errors;
1186 // Transfer the TypoScript array from the parser object to the internal $this->setup array:
1187 $this->setup = $config->setup;
1188 // Do the same for the constants
1189 $this->setup_constants = $constants->setup;
1190 // ****************************************************************
1191 // Final processing of the $this->setup TypoScript Template array
1192 // Basically: This is unsetting/setting of certain reserved keys.
1193 // ****************************************************************
1194 // 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!
1195 unset($this->setup['sitetitle']);
1196 unset($this->setup['sitetitle.']);
1197 $this->setup['sitetitle'] = $this->sitetitle;
1198 // Unsetting some vars...
1199 unset($this->setup['types.']);
1200 unset($this->setup['types']);
1201 if (is_array($this->setup)) {
1202 foreach ($this->setup as $key => $value) {
1203 if ($value === 'PAGE') {
1204 // Set the typeNum of the current page object:
1205 if (isset($this->setup[$key . '.']['typeNum'])) {
1206 $typeNum = $this->setup[$key . '.']['typeNum'];
1207 $this->setup['types.'][$typeNum] = $key;
1208 } elseif (!isset($this->setup['types.'][0]) || !$this->setup['types.'][0]) {
1209 $this->setup['types.'][0] = $key;
1210 }
1211 }
1212 }
1213 }
1214 unset($this->setup['temp.']);
1215 unset($constants);
1216 // Storing the conditions found/matched information:
1217 $this->sections = $config->sections;
1218 $this->sectionsMatch = $config->sectionsMatch;
1219 }
1220
1221 /**
1222 * Searching TypoScript code text (for constants and config (Setup))
1223 * for include instructions and does the inclusion of external TypoScript files
1224 * if needed.
1225 *
1226 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser, generateConfig()
1227 */
1228 public function processIncludes()
1229 {
1230 if ($this->processIncludesHasBeenRun) {
1231 return;
1232 }
1233
1234 $paths = $this->templateIncludePaths;
1235 $files = [];
1236 foreach ($this->constants as &$value) {
1237 $includeData = Parser\TypoScriptParser::checkIncludeLines($value, 1, true, array_shift($paths));
1238 $files = array_merge($files, $includeData['files']);
1239 $value = $includeData['typoscript'];
1240 }
1241 unset($value);
1242 $paths = $this->templateIncludePaths;
1243 foreach ($this->config as &$value) {
1244 $includeData = Parser\TypoScriptParser::checkIncludeLines($value, 1, true, array_shift($paths));
1245 $files = array_merge($files, $includeData['files']);
1246 $value = $includeData['typoscript'];
1247 }
1248 unset($value);
1249
1250 if (!empty($files)) {
1251 $files = array_unique($files);
1252 foreach ($files as $file) {
1253 $this->rowSum[] = [$file, filemtime($file)];
1254 }
1255 }
1256
1257 $this->processIncludesHasBeenRun = true;
1258 }
1259
1260 /**
1261 * 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!
1262 *
1263 * @param array $constArray Constants array, default input.
1264 * @return array Constants array, modified
1265 * @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...)
1266 */
1267 public function mergeConstantsFromPageTSconfig($constArray)
1268 {
1269 $TSdataArray = [];
1270 // Setting default configuration:
1271 $TSdataArray[] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];
1272 for ($a = 0; $a <= $this->outermostRootlineIndexWithTemplate; $a++) {
1273 if (trim($this->absoluteRootLine[$a]['tsconfig_includes'])) {
1274 $includeTsConfigFileList = GeneralUtility::trimExplode(
1275 ',',
1276 $this->absoluteRootLine[$a]['tsconfig_includes'],
1277 true
1278 );
1279
1280 $TSdataArray = $this->mergeConstantsFromIncludedTsConfigFiles($includeTsConfigFileList, $TSdataArray);
1281 }
1282 $TSdataArray[] = $this->absoluteRootLine[$a]['TSconfig'];
1283 }
1284 // Parsing the user TS (or getting from cache)
1285 $TSdataArray = Parser\TypoScriptParser::checkIncludeLines_array($TSdataArray);
1286 $userTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
1287 /** @var Parser\TypoScriptParser $parseObj */
1288 $parseObj = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
1289 $parseObj->parse($userTS);
1290 if (is_array($parseObj->setup['TSFE.']['constants.'])) {
1291 ArrayUtility::mergeRecursiveWithOverrule($constArray, $parseObj->setup['TSFE.']['constants.']);
1292 }
1293
1294 return $constArray;
1295 }
1296
1297 /**
1298 * Reads TSconfig defined in external files and appends it to the given TSconfig array (in this case only constants)
1299 *
1300 * @param array $filesToInclude The files to read constants from
1301 * @param array $TSdataArray The TSconfig array the constants should be appended to
1302 * @return array The TSconfig with the included constants appended
1303 */
1304 protected function mergeConstantsFromIncludedTsConfigFiles($filesToInclude, $TSdataArray)
1305 {
1306 foreach ($filesToInclude as $key => $file) {
1307 if (strpos($file, 'EXT:') !== 0) {
1308 continue;
1309 }
1310
1311 list($extensionKey, $filePath) = explode('/', substr($file, 4), 2);
1312
1313 if ((string)$extensionKey === '' || !ExtensionManagementUtility::isLoaded($extensionKey)) {
1314 continue;
1315 }
1316 if ((string)$filePath == '') {
1317 continue;
1318 }
1319
1320 $tsConfigFile = ExtensionManagementUtility::extPath($extensionKey) . $filePath;
1321 if (file_exists($tsConfigFile)) {
1322 $TSdataArray[] = file_get_contents($tsConfigFile);
1323 }
1324 }
1325
1326 return $TSdataArray;
1327 }
1328
1329 /**
1330 * This flattens a hierarchical TypoScript array to $this->flatSetup
1331 *
1332 * @param array $setupArray TypoScript array
1333 * @param string $prefix Prefix to the object path. Used for recursive calls to this function.
1334 * @see generateConfig()
1335 */
1336 public function flattenSetup($setupArray, $prefix)
1337 {
1338 if (is_array($setupArray)) {
1339 foreach ($setupArray as $key => $val) {
1340 if (is_array($val)) {
1341 $this->flattenSetup($val, $prefix . $key);
1342 } else {
1343 $this->flatSetup[$prefix . $key] = $val;
1344 }
1345 }
1346 }
1347 }
1348
1349 /**
1350 * Substitutes the constants from $this->flatSetup in the text string $all
1351 *
1352 * @param string $all TypoScript code text string
1353 * @return string The processed string with all constants found in $this->flatSetup as key/value pairs substituted.
1354 * @see generateConfig(), flattenSetup()
1355 */
1356 public function substituteConstants($all)
1357 {
1358 if ($this->tt_track) {
1359 $this->getTimeTracker()->setTSlogMessage('Constants to substitute: ' . count($this->flatSetup));
1360 }
1361 $noChange = false;
1362 // Recursive substitution of constants (up to 10 nested levels)
1363 for ($i = 0; $i < 10 && !$noChange; $i++) {
1364 $old_all = $all;
1365 $all = preg_replace_callback('/\\{\\$(.[^}]*)\\}/', [$this, 'substituteConstantsCallBack'], $all);
1366 if ($old_all == $all) {
1367 $noChange = true;
1368 }
1369 }
1370 return $all;
1371 }
1372
1373 /**
1374 * Call back method for preg_replace_callback in substituteConstants
1375 *
1376 * @param array $matches Regular expression matches
1377 * @return string Replacement
1378 * @see substituteConstants()
1379 */
1380 public function substituteConstantsCallBack($matches)
1381 {
1382 // Replace {$CONST} if found in $this->flatSetup, else leave unchanged
1383 return isset($this->flatSetup[$matches[1]]) && !is_array($this->flatSetup[$matches[1]]) ? $this->flatSetup[$matches[1]] : $matches[0];
1384 }
1385
1386 /*******************************************************************
1387 *
1388 * Various API functions, used from elsewhere in the frontend classes
1389 *
1390 *******************************************************************/
1391
1392 /**
1393 * Returns the reference used for the frontend inclusion, checks against allowed paths for inclusion.
1394 *
1395 * @param string $fileFromSetup TypoScript "resource" data type value.
1396 * @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
1397 * @deprecated since TYPO3 v9.4, will be removed in TYPO3 v10.0.
1398 */
1399 public function getFileName($fileFromSetup)
1400 {
1401 trigger_error('TemplateService->getFileName() will be removed in TYPO3 v10.0. Use FilePathSanitizer->sanitize() of EXT:frontend instead.', E_USER_DEPRECATED);
1402 try {
1403 $file = GeneralUtility::makeInstance(FilePathSanitizer::class)->sanitize((string)$fileFromSetup);
1404 $hash = md5($file);
1405 if (!isset($this->fileCache[$hash])) {
1406 $this->fileCache[$hash] = $file;
1407 }
1408 return $file;
1409 } catch (InvalidFileNameException $e) {
1410 // Empty file name
1411 } catch (InvalidPathException $e) {
1412 if ($this->tt_track) {
1413 $this->getTimeTracker()->setTSlogMessage('File path "' . $fileFromSetup . '" contained illegal string "../"!', 3);
1414 }
1415 } catch (FileDoesNotExistException $e) {
1416 if ($this->tt_track) {
1417 $this->getTimeTracker()->setTSlogMessage('File "' . $fileFromSetup . '" was not found!', 3);
1418 }
1419 } catch (InvalidFileException $e) {
1420 if ($this->tt_track) {
1421 $this->getTimeTracker()->setTSlogMessage('"' . $fileFromSetup . '" was not located in the allowed paths: (' . implode(',', $this->allowedPaths) . ')', 3);
1422 }
1423 }
1424 return null;
1425 }
1426
1427 /**
1428 * Compiles the content for the page <title> tag.
1429 *
1430 * @param string $pageTitle The input title string, typically the "title" field of a page's record.
1431 * @param bool $noTitle If set, then only the site title is outputted (from $this->setup['sitetitle'])
1432 * @param bool $showTitleFirst If set, then "sitetitle" and $title is swapped
1433 * @param string $pageTitleSeparator an alternative to the ": " as the separator between site title and page title
1434 * @return string The page title on the form "[sitetitle]: [input-title]". Not htmlspecialchar()'ed.
1435 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::tempPageCacheContent(), \TYPO3\CMS\Frontend\Page\PageGenerator::renderContentWithHeader()
1436 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10, use $TSFE->generatePageTitle() instead.
1437 */
1438 public function printTitle($pageTitle, $noTitle = false, $showTitleFirst = false, $pageTitleSeparator = '')
1439 {
1440 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);
1441 $siteTitle = trim($this->setup['sitetitle']);
1442 $pageTitle = $noTitle ? '' : $pageTitle;
1443 if ($showTitleFirst) {
1444 $temp = $siteTitle;
1445 $siteTitle = $pageTitle;
1446 $pageTitle = $temp;
1447 }
1448 // only show a separator if there are both site title and page title
1449 if ($pageTitle === '' || $siteTitle === '') {
1450 $pageTitleSeparator = '';
1451 } elseif (empty($pageTitleSeparator)) {
1452 // use the default separator if non given
1453 $pageTitleSeparator = ': ';
1454 }
1455 return $siteTitle . $pageTitleSeparator . $pageTitle;
1456 }
1457
1458 /**
1459 * Returns the level of the given page in the rootline - Multiple pages can be given by separating the UIDs by comma.
1460 *
1461 * @param string $list A list of UIDs for which the rootline-level should get returned
1462 * @return int The level in the rootline. If more than one page was given the lowest level will get returned.
1463 */
1464 public function getRootlineLevel($list)
1465 {
1466 $idx = 0;
1467 foreach ($this->rootLine as $page) {
1468 if (GeneralUtility::inList($list, $page['uid'])) {
1469 return $idx;
1470 }
1471 $idx++;
1472 }
1473 return false;
1474 }
1475
1476 /**
1477 * Returns the page ID of the rootlevel
1478 *
1479 * @return int
1480 */
1481 public function getRootId(): int
1482 {
1483 return (int)$this->rootId;
1484 }
1485
1486 /*******************************************************************
1487 *
1488 * Functions for creating links
1489 *
1490 *******************************************************************/
1491 /**
1492 * The mother of all functions creating links/URLs etc in a TypoScript environment.
1493 * See the references below.
1494 * Basically this function takes care of issues such as type,id,alias and Mount Points, URL rewriting (through hooks), M5/B6 encoded parameters etc.
1495 * 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.
1496 *
1497 * @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.
1498 * @param string $oTarget Default target string to use IF not $page['target'] is set.
1499 * @param bool $no_cache If set, then the "&no_cache=1" parameter is included in the URL.
1500 * @param string $_ not in use anymore
1501 * @param array $overrideArray Array with overriding values for the $page array.
1502 * @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.
1503 * @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.
1504 * @param string $targetDomain The target Doamin, if any was detected in typolink
1505 * @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
1506 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::typoLink(), \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::link()
1507 * @deprecated - will be removed in TYPO3 v10.0 - have a look at PageLinkBuilder
1508 */
1509 public function linkData($page, $oTarget, $no_cache, $_ = null, $overrideArray = null, $addParams = '', $typeOverride = '', $targetDomain = '')
1510 {
1511 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);
1512 $LD = [];
1513 // Overriding some fields in the page record and still preserves the values by adding them as parameters. Little strange function.
1514 if (is_array($overrideArray)) {
1515 foreach ($overrideArray as $theKey => $theNewVal) {
1516 $addParams .= '&real_' . $theKey . '=' . rawurlencode($page[$theKey]);
1517 $page[$theKey] = $theNewVal;
1518 }
1519 }
1520 // Adding Mount Points, "&MP=", parameter for the current page if any is set:
1521 if (!strstr($addParams, '&MP=')) {
1522 // Looking for hardcoded defaults:
1523 if (trim($this->getTypoScriptFrontendController()->MP_defaults[$page['uid']])) {
1524 $addParams .= '&MP=' . rawurlencode(trim($this->getTypoScriptFrontendController()->MP_defaults[$page['uid']]));
1525 } elseif ($this->getTypoScriptFrontendController()->config['config']['MP_mapRootPoints']) {
1526 // Else look in automatically created map:
1527 $m = $this->getFromMPmap($page['uid']);
1528 if ($m) {
1529 $addParams .= '&MP=' . rawurlencode($m);
1530 }
1531 }
1532 }
1533 // Setting ID/alias:
1534 $script = 'index.php';
1535 if ($page['alias']) {
1536 $LD['url'] = $script . '?id=' . rawurlencode($page['alias']);
1537 } else {
1538 $LD['url'] = $script . '?id=' . $page['uid'];
1539 }
1540 // Setting target
1541 $LD['target'] = trim($page['target']) ?: $oTarget;
1542 // typeNum
1543 $typeNum = $this->setup[$LD['target'] . '.']['typeNum'];
1544 if (!MathUtility::canBeInterpretedAsInteger($typeOverride) && (int)$this->getTypoScriptFrontendController()->config['config']['forceTypeValue']) {
1545 $typeOverride = (int)$this->getTypoScriptFrontendController()->config['config']['forceTypeValue'];
1546 }
1547 if ((string)$typeOverride !== '') {
1548 $typeNum = $typeOverride;
1549 }
1550 // Override...
1551 if ($typeNum) {
1552 $LD['type'] = '&type=' . (int)$typeNum;
1553 } else {
1554 $LD['type'] = '';
1555 }
1556 // Preserving the type number.
1557 $LD['orig_type'] = $LD['type'];
1558 // noCache
1559 $LD['no_cache'] = $no_cache ? '&no_cache=1' : '';
1560 // linkVars
1561 if ($addParams) {
1562 $LD['linkVars'] = GeneralUtility::implodeArrayForUrl('', GeneralUtility::explodeUrl2Array($this->getTypoScriptFrontendController()->linkVars . $addParams), '', false, true);
1563 } else {
1564 $LD['linkVars'] = $this->getTypoScriptFrontendController()->linkVars;
1565 }
1566 // Add absRefPrefix if exists.
1567 $LD['url'] = $this->getTypoScriptFrontendController()->absRefPrefix . $LD['url'];
1568 // 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.
1569 $LD['sectionIndex'] = $page['sectionIndex_uid'] ? '#c' . $page['sectionIndex_uid'] : '';
1570 // Compile the normal total url
1571 $LD['totalURL'] = rtrim($LD['url'] . $LD['type'] . $LD['no_cache'] . $LD['linkVars'] . $this->getTypoScriptFrontendController()->getMethodUrlIdToken, '?') . $LD['sectionIndex'];
1572 // Call post processing function for link rendering:
1573 $_params = [
1574 'LD' => &$LD,
1575 'args' => ['page' => $page, 'oTarget' => $oTarget, 'no_cache' => $no_cache, 'script' => $script, 'overrideArray' => $overrideArray, 'addParams' => $addParams, 'typeOverride' => $typeOverride, 'targetDomain' => $targetDomain],
1576 'typeNum' => $typeNum
1577 ];
1578 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['linkData-PostProc'] ?? [] as $_funcRef) {
1579 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1580 }
1581 // Return the LD-array
1582 return $LD;
1583 }
1584
1585 /**
1586 * Initializes the automatically created MPmap coming from the "config.MP_mapRootPoints" setting
1587 * Can be called many times with overhead only the first time since then the map is generated and cached in memory.
1588 *
1589 * @param int $pageId Page id to return MPvar value for.
1590 * @return string
1591 * @see initMPmap_create()
1592 * @todo Implement some caching of the result between hits. (more than just the memory caching used here)
1593 * @deprecated - will be removed in TYPO3 v10.
1594 */
1595 public function getFromMPmap($pageId = 0)
1596 {
1597 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);
1598 // Create map if not found already:
1599 if (!is_array($this->MPmap)) {
1600 $this->MPmap = [];
1601 $rootPoints = GeneralUtility::trimExplode(',', strtolower($this->getTypoScriptFrontendController()->config['config']['MP_mapRootPoints']), true);
1602 // Traverse rootpoints:
1603 foreach ($rootPoints as $p) {
1604 $initMParray = [];
1605 if ($p === 'root') {
1606 $p = $this->rootLine[0]['uid'];
1607 if ($this->rootLine[0]['_MOUNT_OL'] && $this->rootLine[0]['_MP_PARAM']) {
1608 $initMParray[] = $this->rootLine[0]['_MP_PARAM'];
1609 }
1610 }
1611 $this->initMPmap_create($p, $initMParray);
1612 }
1613 }
1614 // Finding MP var for Page ID:
1615 if ($pageId) {
1616 if (is_array($this->MPmap[$pageId]) && !empty($this->MPmap[$pageId])) {
1617 return implode(',', $this->MPmap[$pageId]);
1618 }
1619 }
1620 return '';
1621 }
1622
1623 /**
1624 * Creating MPmap for a certain ID root point.
1625 *
1626 * @param int $id Root id from which to start map creation.
1627 * @param array $MP_array MP_array passed from root page.
1628 * @param int $level Recursion brake. Incremented for each recursive call. 20 is the limit.
1629 * @see getFromMPvar()
1630 * @deprecated will be removed in TYPO3 v10.0
1631 */
1632 public function initMPmap_create($id, $MP_array = [], $level = 0)
1633 {
1634 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);
1635 $id = (int)$id;
1636 if ($id <= 0) {
1637 return;
1638 }
1639 // First level, check id
1640 if (!$level) {
1641 // Find mount point if any:
1642 $mount_info = $this->getTypoScriptFrontendController()->sys_page->getMountPointInfo($id);
1643 // Overlay mode:
1644 if (is_array($mount_info) && $mount_info['overlay']) {
1645 $MP_array[] = $mount_info['MPvar'];
1646 $id = $mount_info['mount_pid'];
1647 }
1648 // Set mapping information for this level:
1649 $this->MPmap[$id] = $MP_array;
1650 // Normal mode:
1651 if (is_array($mount_info) && !$mount_info['overlay']) {
1652 $MP_array[] = $mount_info['MPvar'];
1653 $id = $mount_info['mount_pid'];
1654 }
1655 }
1656 if ($id && $level < 20) {
1657 $nextLevelAcc = [];
1658 // Select and traverse current level pages:
1659 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1660 $queryBuilder->getRestrictions()
1661 ->removeAll()
1662 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1663 $queryResult = $queryBuilder
1664 ->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol')
1665 ->from('pages')
1666 ->where(
1667 $queryBuilder->expr()->eq(
1668 'pid',
1669 $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)
1670 ),
1671 $queryBuilder->expr()->neq(
1672 'doktype',
1673 $queryBuilder->createNamedParameter(PageRepository::DOKTYPE_RECYCLER, \PDO::PARAM_INT)
1674 ),
1675 $queryBuilder->expr()->neq(
1676 'doktype',
1677 $queryBuilder->createNamedParameter(PageRepository::DOKTYPE_BE_USER_SECTION, \PDO::PARAM_INT)
1678 )
1679 )->execute();
1680 while ($row = $queryResult->fetch()) {
1681 // Find mount point if any:
1682 $next_id = $row['uid'];
1683 $next_MP_array = $MP_array;
1684 $mount_info = $this->getTypoScriptFrontendController()->sys_page->getMountPointInfo($next_id, $row);
1685 // Overlay mode:
1686 if (is_array($mount_info) && $mount_info['overlay']) {
1687 $next_MP_array[] = $mount_info['MPvar'];
1688 $next_id = $mount_info['mount_pid'];
1689 }
1690 if (!isset($this->MPmap[$next_id])) {
1691 // Set mapping information for this level:
1692 $this->MPmap[$next_id] = $next_MP_array;
1693 // Normal mode:
1694 if (is_array($mount_info) && !$mount_info['overlay']) {
1695 $next_MP_array[] = $mount_info['MPvar'];
1696 $next_id = $mount_info['mount_pid'];
1697 }
1698 // Register recursive call
1699 // (have to do it this way since ALL of the current level should be registered BEFORE the sublevel at any time)
1700 $nextLevelAcc[] = [$next_id, $next_MP_array];
1701 }
1702 }
1703 // Call recursively, if any:
1704 foreach ($nextLevelAcc as $pSet) {
1705 $this->initMPmap_create($pSet[0], $pSet[1], $level + 1);
1706 }
1707 }
1708 }
1709
1710 /**
1711 * Adds the TypoScript from the global array.
1712 * The class property isDefaultTypoScriptAdded ensures
1713 * that the adding only happens once.
1714 *
1715 * @see isDefaultTypoScriptAdded
1716 */
1717 protected function addDefaultTypoScript()
1718 {
1719 // Add default TS for all code types, if not done already
1720 if (!$this->isDefaultTypoScriptAdded) {
1721 // adding default setup and constants
1722 // defaultTypoScript_setup is *very* unlikely to be empty
1723 // the count of elements in ->constants, ->config and ->templateIncludePaths have to be in sync
1724 array_unshift($this->constants, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants']);
1725 array_unshift($this->config, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup']);
1726 array_unshift($this->templateIncludePaths, '');
1727 // prepare a proper entry to hierachyInfo (used by TemplateAnalyzer in BE)
1728 $rootTemplateId = $this->hierarchyInfo[count($this->hierarchyInfo) - 1]['templateID'] ?? null;
1729 $defaultTemplateInfo = [
1730 'root' => '',
1731 'next' => '',
1732 'clConst' => '',
1733 'clConf' => '',
1734 'templateID' => '_defaultTypoScript_',
1735 'templateParent' => $rootTemplateId,
1736 'title' => 'SYS:TYPO3_CONF_VARS:FE:defaultTypoScript',
1737 'uid' => '_defaultTypoScript_',
1738 'pid' => '',
1739 'configLines' => substr_count((string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup'], LF) + 1
1740 ];
1741 // push info to information arrays used in BE by TemplateTools (Analyzer)
1742 array_unshift($this->clearList_const, $defaultTemplateInfo['uid']);
1743 array_unshift($this->clearList_setup, $defaultTemplateInfo['uid']);
1744 array_unshift($this->hierarchyInfo, $defaultTemplateInfo);
1745 $this->isDefaultTypoScriptAdded = true;
1746 }
1747 }
1748
1749 /**
1750 * @return TypoScriptFrontendController
1751 */
1752 protected function getTypoScriptFrontendController()
1753 {
1754 return $GLOBALS['TSFE'];
1755 }
1756
1757 /**
1758 * @return TimeTracker
1759 */
1760 protected function getTimeTracker()
1761 {
1762 return GeneralUtility::makeInstance(TimeTracker::class);
1763 }
1764
1765 /**
1766 * Returns data stored for the hash string in the cache "cache_hash"
1767 * used to store the parsed TypoScript template structures.
1768 *
1769 * @param string $identifier The hash-string which was used to store the data value
1770 * @return mixed The data from the cache
1771 */
1772 protected function getCacheEntry($identifier)
1773 {
1774 return GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash')->get($identifier);
1775 }
1776
1777 /**
1778 * Stores $data in the 'cache_hash' cache with the hash key $identifier
1779 *
1780 * @param string $identifier 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
1781 * @param mixed $data The data to store
1782 * @param string $tag Is just a textual identification in order to inform about the content
1783 */
1784 protected function setCacheEntry($identifier, $data, $tag)
1785 {
1786 GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash')->set($identifier, $data, ['ident_' . $tag], 0);
1787 }
1788 }