[!!!][TASK] Remove deprecated code from TemplateService
[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\Context\Context;
20 use TYPO3\CMS\Core\Database\Connection;
21 use TYPO3\CMS\Core\Database\ConnectionPool;
22 use TYPO3\CMS\Core\Database\Query\Restriction\AbstractRestrictionContainer;
23 use TYPO3\CMS\Core\Database\Query\Restriction\DefaultRestrictionContainer;
24 use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
25 use TYPO3\CMS\Core\Package\PackageManager;
26 use TYPO3\CMS\Core\TimeTracker\TimeTracker;
27 use TYPO3\CMS\Core\Utility\ArrayUtility;
28 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
29 use TYPO3\CMS\Core\Utility\GeneralUtility;
30 use TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher;
31 use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
32
33 /**
34 * Template object that is responsible for generating the TypoScript template based on template records.
35 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
36 * @see \TYPO3\CMS\Core\Configuration\TypoScript\ConditionMatching\AbstractConditionMatcher
37 */
38 class TemplateService
39 {
40 /**
41 * option to enable logging, time-tracking (FE-only)
42 * usually, this is only done when
43 * - in FE a BE_USER is logged-in
44 * - in BE when the BE_USER needs information about the template (TypoScript module)
45 * @var bool
46 */
47 protected $verbose = false;
48
49 /**
50 * If set, the global tt-timeobject is used to log the performance.
51 *
52 * @var bool
53 */
54 public $tt_track = true;
55
56 /**
57 * If set, the template is always rendered. Used from Admin Panel.
58 *
59 * @var bool
60 */
61 public $forceTemplateParsing = false;
62
63 /**
64 * This array is passed on to matchObj by generateConfig().
65 * If it holds elements, they are used for matching instead. See comment at the match-class.
66 * Used for backend modules only. Never frontend!
67 *
68 * @var array
69 * @internal
70 */
71 public $matchAlternative = [];
72
73 /**
74 * If set, the match-class matches everything! Used for backend modules only. Never frontend!
75 *
76 * @var bool
77 */
78 protected $matchAll = false;
79
80 /**
81 * Externally set breakpoints (used by Backend Modules)
82 *
83 * @var int
84 */
85 public $ext_constants_BRP = 0;
86
87 /**
88 * @var int
89 */
90 public $ext_config_BRP = 0;
91
92 /**
93 * @var bool
94 */
95 public $ext_regLinenumbers = false;
96
97 /**
98 * @var bool
99 */
100 public $ext_regComments = false;
101
102 /**
103 * Set if preview of some kind is enabled.
104 *
105 * @var bool
106 */
107 protected $simulationHiddenOrTime = false;
108
109 /**
110 * Set, if the TypoScript template structure is loaded and OK, see ->start()
111 *
112 * @var bool
113 */
114 public $loaded = false;
115
116 /**
117 * @var array Contains TypoScript setup part after parsing
118 */
119 public $setup = [];
120
121 /**
122 * @var array
123 */
124 public $flatSetup = [];
125
126 /**
127 * For fetching TypoScript code from template hierarchy before parsing it.
128 * Each array contains code field values from template records/files:
129 * Setup field
130 *
131 * @var array
132 */
133 public $config = [];
134
135 /**
136 * Constant field
137 *
138 * @var array
139 */
140 public $constants = [];
141
142 /**
143 * Holds the include paths of the templates (empty if from database)
144 *
145 * @var array
146 */
147 protected $templateIncludePaths = [];
148
149 /**
150 * For Template Analyzer in backend
151 *
152 * @var array
153 */
154 public $hierarchyInfo = [];
155
156 /**
157 * For Template Analyzer in backend (setup content only)
158 *
159 * @var array
160 */
161 protected $hierarchyInfoToRoot = [];
162
163 /**
164 * Next-level flag (see runThroughTemplates())
165 *
166 * @var int
167 */
168 protected $nextLevel = 0;
169
170 /**
171 * The Page UID of the root page
172 *
173 * @var int
174 */
175 protected $rootId;
176
177 /**
178 * The rootline from current page to the root page
179 *
180 * @var array
181 */
182 public $rootLine;
183
184 /**
185 * Rootline all the way to the root. Set but runThroughTemplates
186 *
187 * @var array
188 */
189 protected $absoluteRootLine;
190
191 /**
192 * A pointer to the last entry in the rootline where a template was found.
193 *
194 * @var int
195 */
196 protected $outermostRootlineIndexWithTemplate = 0;
197
198 /**
199 * Array of arrays with title/uid of templates in hierarchy
200 *
201 * @var array
202 */
203 protected $rowSum;
204
205 /**
206 * The current site title field.
207 *
208 * @var string
209 */
210 protected $sitetitle = '';
211
212 /**
213 * Tracking all conditions found during parsing of TypoScript. Used for the "all" key in currentPageData
214 *
215 * @var array|null
216 */
217 public $sections;
218
219 /**
220 * Tracking all matching conditions found
221 *
222 * @var array
223 */
224 protected $sectionsMatch;
225
226 /**
227 * Used by Backend only (Typoscript Template Analyzer)
228 */
229 public $clearList_const = [];
230
231 /**
232 * Used by Backend only (Typoscript Template Analyzer)
233 *
234 * @var array
235 */
236 public $clearList_setup = [];
237
238 /**
239 * @var array
240 */
241 public $parserErrors = [];
242
243 /**
244 * @var array
245 */
246 public $setup_constants = [];
247
248 /**
249 * Indicator that extension statics are processed.
250 *
251 * These files are considered if either a root template
252 * has been processed or the $processExtensionStatics
253 * property has been set to TRUE.
254 *
255 * @var bool
256 */
257 protected $extensionStaticsProcessed = false;
258
259 /**
260 * Trigger value, to ensure that extension statics are processed.
261 *
262 * @var bool
263 */
264 protected $processExtensionStatics = false;
265
266 /**
267 * Set to TRUE after the default TypoScript was added during parsing.
268 * This prevents double inclusion of the same TypoScript code.
269 *
270 * @see addDefaultTypoScript()
271 * @var bool
272 */
273 protected $isDefaultTypoScriptAdded = false;
274
275 /**
276 * Set to TRUE after $this->config and $this->constants have processed all <INCLUDE_TYPOSCRIPT:> instructions.
277 *
278 * This prevents double processing of INCLUDES.
279 *
280 * @see processIncludes()
281 * @var bool
282 */
283 protected $processIncludesHasBeenRun = false;
284
285 /**
286 * Contains the restrictions about deleted, and some frontend related topics
287 * @var AbstractRestrictionContainer
288 */
289 protected $queryBuilderRestrictions;
290
291 /**
292 * @var Context
293 */
294 protected $context;
295
296 /**
297 * @var PackageManager
298 */
299 protected $packageManager;
300
301 /**
302 * @param Context|null $context
303 * @param PackageManager|null $packageManager
304 */
305 public function __construct(Context $context = null, PackageManager $packageManager = null)
306 {
307 $this->context = $context ?? GeneralUtility::makeInstance(Context::class);
308 $this->packageManager = $packageManager ?? GeneralUtility::makeInstance(PackageManager::class);
309 $this->initializeDatabaseQueryRestrictions();
310 if ($this->context->getPropertyFromAspect('visibility', 'includeHiddenContent', false) || $GLOBALS['SIM_ACCESS_TIME'] !== $GLOBALS['ACCESS_TIME']) {
311 // Set the simulation flag, if simulation is detected!
312 $this->simulationHiddenOrTime = true;
313 }
314 $this->tt_track = $this->verbose = (bool)$this->context->getPropertyFromAspect('backend.user', 'isLoggedIn', false);
315 }
316
317 /**
318 * @return bool
319 */
320 public function getProcessExtensionStatics()
321 {
322 return $this->processExtensionStatics;
323 }
324
325 /**
326 * @param bool $processExtensionStatics
327 */
328 public function setProcessExtensionStatics($processExtensionStatics)
329 {
330 $this->processExtensionStatics = (bool)$processExtensionStatics;
331 }
332
333 /**
334 * sets the verbose parameter
335 * @param bool $verbose
336 */
337 public function setVerbose($verbose)
338 {
339 $this->verbose = (bool)$verbose;
340 }
341
342 /**
343 * Set up the query builder restrictions, optionally include hidden records
344 */
345 protected function initializeDatabaseQueryRestrictions()
346 {
347 $this->queryBuilderRestrictions = GeneralUtility::makeInstance(DefaultRestrictionContainer::class);
348
349 if ($this->context->getPropertyFromAspect('visibility', 'includeHiddenContent', false)) {
350 $this->queryBuilderRestrictions->removeByType(HiddenRestriction::class);
351 }
352 }
353
354 /**
355 * Fetches the "currentPageData" array from cache
356 *
357 * NOTE about currentPageData:
358 * It holds information about the TypoScript conditions along with the list
359 * of template uid's which is used on the page. In the getFromCache() function
360 * in TSFE, currentPageData is used to evaluate if there is a template and
361 * if the matching conditions are alright. Unfortunately this does not take
362 * into account if the templates in the rowSum of currentPageData has
363 * changed composition, eg. due to hidden fields or start/end time. So if a
364 * template is hidden or times out, it'll not be discovered unless the page
365 * is regenerated - at least the this->start function must be called,
366 * because this will make a new portion of data in currentPageData string.
367 *
368 * @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
369 * @internal
370 */
371 public function getCurrentPageData()
372 {
373 return GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_pagesection')->get((int)$this->getTypoScriptFrontendController()->id . '_' . GeneralUtility::md5int($this->getTypoScriptFrontendController()->MP));
374 }
375
376 /**
377 * Fetches data about which TypoScript-matches there are at this page. Then it performs a matchingtest.
378 *
379 * @param array $cc An array with three keys, "all", "rowSum" and "rootLine" - all coming from the "currentPageData" array
380 * @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.
381 */
382 public function matching($cc)
383 {
384 if (is_array($cc['all'])) {
385 /** @var ConditionMatcher $matchObj */
386 $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
387 $matchObj->setRootline((array)$cc['rootLine']);
388 $sectionsMatch = [];
389 foreach ($cc['all'] as $key => $pre) {
390 if ($matchObj->match($pre)) {
391 $sectionsMatch[$key] = $pre;
392 }
393 }
394 $cc['match'] = $sectionsMatch;
395 }
396 return $cc;
397 }
398
399 /**
400 * This is all about fetching the right TypoScript template structure. If it's not cached then it must be generated and cached!
401 * 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.
402 * Sets $this->setup to the parsed TypoScript template array
403 *
404 * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
405 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getConfigArray()
406 */
407 public function start($theRootLine)
408 {
409 if (is_array($theRootLine)) {
410 $constantsData = [];
411 $setupData = [];
412 $cacheIdentifier = '';
413 // Flag that indicates that the existing data in cache_pagesection
414 // could be used (this is the case if $TSFE->all is set, and the
415 // rowSum still matches). Based on this we decide if cache_pagesection
416 // needs to be updated...
417 $isCached = false;
418 $this->runThroughTemplates($theRootLine);
419 if ($this->getTypoScriptFrontendController()->all) {
420 $cc = $this->getTypoScriptFrontendController()->all;
421 // The two rowSums must NOT be different from each other - which they will be if start/endtime or hidden has changed!
422 if (serialize($this->rowSum) !== serialize($cc['rowSum'])) {
423 unset($cc);
424 } else {
425 // If $TSFE->all contains valid data, we don't need to update cache_pagesection (because this data was fetched from there already)
426 if (serialize($this->rootLine) === serialize($cc['rootLine'])) {
427 $isCached = true;
428 }
429 // 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)...
430 unset($cc['rootLine']);
431 }
432 }
433 // This is about getting the hash string which is used to fetch the cached TypoScript template.
434 // If there was some cached currentPageData ($cc) then that's good (it gives us the hash).
435 if (isset($cc) && is_array($cc)) {
436 // If currentPageData was actually there, we match the result (if this wasn't done already in $TSFE->getFromCache()...)
437 if (!$cc['match']) {
438 // @todo check if this can ever be the case - otherwise remove
439 $cc = $this->matching($cc);
440 ksort($cc);
441 }
442 $cacheIdentifier = md5(serialize($cc));
443 } else {
444 // 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.
445 $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
446 $result = $this->getCacheEntry($rowSumHash);
447 if (is_array($result)) {
448 $cc = [];
449 $cc['all'] = $result;
450 $cc['rowSum'] = $this->rowSum;
451 $cc = $this->matching($cc);
452 ksort($cc);
453 $cacheIdentifier = md5(serialize($cc));
454 }
455 }
456 if ($cacheIdentifier) {
457 // Get TypoScript setup array
458 $cachedData = $this->getCacheEntry($cacheIdentifier);
459 if (is_array($cachedData)) {
460 $constantsData = $cachedData['constants'];
461 $setupData = $cachedData['setup'];
462 }
463 }
464 if (!empty($setupData) && !$this->forceTemplateParsing) {
465 // TypoScript constants + setup are found in the cache
466 $this->setup_constants = $constantsData;
467 $this->setup = $setupData;
468 if ($this->tt_track) {
469 $this->getTimeTracker()->setTSlogMessage('Using cached TS template data');
470 }
471 } else {
472 if ($this->tt_track) {
473 $this->getTimeTracker()->setTSlogMessage('Not using any cached TS data');
474 }
475
476 // Make configuration
477 $this->generateConfig();
478 // This stores the template hash thing
479 $cc = [];
480 // All sections in the template at this point is found
481 $cc['all'] = $this->sections;
482 // The line of templates is collected
483 $cc['rowSum'] = $this->rowSum;
484 $cc = $this->matching($cc);
485 ksort($cc);
486 $cacheIdentifier = md5(serialize($cc));
487 // This stores the data.
488 $this->setCacheEntry($cacheIdentifier, ['constants' => $this->setup_constants, 'setup' => $this->setup], 'TS_TEMPLATE');
489 if ($this->tt_track) {
490 $this->getTimeTracker()->setTSlogMessage('TS template size, serialized: ' . strlen(serialize($this->setup)) . ' bytes');
491 }
492 $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
493 $this->setCacheEntry($rowSumHash, $cc['all'], 'TMPL_CONDITIONS_ALL');
494 }
495 // Add rootLine
496 $cc['rootLine'] = $this->rootLine;
497 ksort($cc);
498 // Make global and save
499 $this->getTypoScriptFrontendController()->all = $cc;
500 // Matching must be executed for every request, so this must never be part of the pagesection cache!
501 unset($cc['match']);
502 if (!$isCached && !$this->simulationHiddenOrTime && !$this->getTypoScriptFrontendController()->no_cache) {
503 // Only save the data if we're not simulating by hidden/starttime/endtime
504 $mpvarHash = GeneralUtility::md5int($this->getTypoScriptFrontendController()->MP);
505 /** @var \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface $pageSectionCache */
506 $pageSectionCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_pagesection');
507 $pageSectionCache->set((int)$this->getTypoScriptFrontendController()->id . '_' . $mpvarHash, $cc, [
508 'pageId_' . (int)$this->getTypoScriptFrontendController()->id,
509 'mpvarHash_' . $mpvarHash
510 ]);
511 }
512 // If everything OK.
513 if ($this->rootId && $this->rootLine && $this->setup) {
514 $this->loaded = true;
515 }
516 }
517 }
518
519 /*******************************************************************
520 *
521 * Fetching TypoScript code text for the Template Hierarchy
522 *
523 *******************************************************************/
524 /**
525 * 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.
526 * Resets and affects internal variables like $this->constants, $this->config and $this->rowSum
527 * 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
528 *
529 * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
530 * @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)
531 * @see start()
532 */
533 public function runThroughTemplates($theRootLine, $start_template_uid = 0)
534 {
535 $this->constants = [];
536 $this->config = [];
537 $this->rowSum = [];
538 $this->hierarchyInfoToRoot = [];
539 $this->absoluteRootLine = $theRootLine;
540 $this->isDefaultTypoScriptAdded = false;
541
542 reset($this->absoluteRootLine);
543 $c = count($this->absoluteRootLine);
544 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_template');
545 for ($a = 0; $a < $c; $a++) {
546 // If some template loaded before has set a template-id for the next level, then load this template first!
547 if ($this->nextLevel) {
548 $queryBuilder->setRestrictions($this->queryBuilderRestrictions);
549 $queryResult = $queryBuilder
550 ->select('*')
551 ->from('sys_template')
552 ->where(
553 $queryBuilder->expr()->eq(
554 'uid',
555 $queryBuilder->createNamedParameter($this->nextLevel, \PDO::PARAM_INT)
556 )
557 )
558 ->execute();
559 $this->nextLevel = 0;
560 if ($row = $queryResult->fetch()) {
561 $this->versionOL($row);
562 if (is_array($row)) {
563 $this->processTemplate($row, 'sys_' . $row['uid'], $this->absoluteRootLine[$a]['uid'], 'sys_' . $row['uid']);
564 $this->outermostRootlineIndexWithTemplate = $a;
565 }
566 }
567 }
568
569 $where = [
570 $queryBuilder->expr()->eq(
571 'pid',
572 $queryBuilder->createNamedParameter($this->absoluteRootLine[$a]['uid'], \PDO::PARAM_INT)
573 )
574 ];
575 // If first loop AND there is set an alternative template uid, use that
576 if ($a === $c - 1 && $start_template_uid) {
577 $where[] = $queryBuilder->expr()->eq(
578 'uid',
579 $queryBuilder->createNamedParameter($start_template_uid, \PDO::PARAM_INT)
580 );
581 }
582 $queryBuilder->setRestrictions($this->queryBuilderRestrictions);
583 $queryResult = $queryBuilder
584 ->select('*')
585 ->from('sys_template')
586 ->where(...$where)
587 ->orderBy('root', 'DESC')
588 ->addOrderBy('sorting')
589 ->setMaxResults(1)
590 ->execute();
591 if ($row = $queryResult->fetch()) {
592 $this->versionOL($row);
593 if (is_array($row)) {
594 $this->processTemplate($row, 'sys_' . $row['uid'], $this->absoluteRootLine[$a]['uid'], 'sys_' . $row['uid']);
595 $this->outermostRootlineIndexWithTemplate = $a;
596 }
597 }
598 $this->rootLine[] = $this->absoluteRootLine[$a];
599 }
600
601 // Hook into the default TypoScript to add custom typoscript logic
602 $hookParameters = [
603 'extensionStaticsProcessed' => &$this->extensionStaticsProcessed,
604 'isDefaultTypoScriptAdded' => &$this->isDefaultTypoScriptAdded,
605 'absoluteRootLine' => &$this->absoluteRootLine,
606 'rootLine' => &$this->rootLine,
607 'startTemplateUid' => $start_template_uid,
608 ];
609 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['Core/TypoScript/TemplateService']['runThroughTemplatesPostProcessing'] ?? [] as $listener) {
610 GeneralUtility::callUserFunction($listener, $hookParameters, $this);
611 }
612
613 // Process extension static files if not done yet, but explicitly requested
614 if (!$this->extensionStaticsProcessed && $this->processExtensionStatics) {
615 $this->addExtensionStatics('sys_0', 'sys_0', 0);
616 }
617
618 // Add the global default TypoScript from the TYPO3_CONF_VARS
619 $this->addDefaultTypoScript();
620
621 $this->processIncludes();
622 }
623
624 /**
625 * Checks if the template ($row) has some included templates and after including them it fills the arrays with the setup
626 * Builds up $this->rowSum
627 *
628 * @param array $row A full TypoScript template record (sys_template/forged "dummy" record made from static template file)
629 * @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.
630 * @param int $pid The PID of the input template record
631 * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
632 * @param string $templateParent Parent template id (during recursive call); Same syntax as $idList ids, eg. "sys_123
633 * @param string $includePath Specifies the path from which the template was included (used with static_includes)
634 * @see runThroughTemplates()
635 */
636 public function processTemplate($row, $idList, $pid, $templateID = '', $templateParent = '', $includePath = '')
637 {
638 // Adding basic template record information to rowSum array
639 $this->rowSum[] = [$row['uid'] ?? null, $row['title'] ?? null, $row['tstamp'] ?? null];
640 // Processing "Clear"-flags
641 $clConst = 0;
642 $clConf = 0;
643 if (!empty($row['clear'])) {
644 $clConst = $row['clear'] & 1;
645 $clConf = $row['clear'] & 2;
646 if ($clConst) {
647 // Keep amount of items to stay in sync with $this->templateIncludePaths so processIncludes() does not break
648 foreach ($this->constants as &$constantConfiguration) {
649 $constantConfiguration = '';
650 }
651 unset($constantConfiguration);
652 $this->clearList_const = [];
653 }
654 if ($clConf) {
655 // Keep amount of items to stay in sync with $this->templateIncludePaths so processIncludes() does not break
656 foreach ($this->config as &$configConfiguration) {
657 $configConfiguration = '';
658 }
659 unset($configConfiguration);
660 $this->hierarchyInfoToRoot = [];
661 $this->clearList_setup = [];
662 }
663 }
664 // Include files (from extensions) (#1/2)
665 // NORMAL inclusion, The EXACT same code is found below the basedOn inclusion!!!
666 if (!isset($row['includeStaticAfterBasedOn']) || !$row['includeStaticAfterBasedOn']) {
667 $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
668 }
669 // Include "Based On" sys_templates:
670 // 'basedOn' is a list of templates to include
671 if (trim($row['basedOn'] ?? '')) {
672 // Normal Operation, which is to include the "based-on" sys_templates,
673 // if they are not already included, and maintaining the sorting of the templates
674 $basedOnIds = GeneralUtility::intExplode(',', $row['basedOn'], true);
675 // skip template if it's already included
676 foreach ($basedOnIds as $key => $basedOnId) {
677 if (GeneralUtility::inList($idList, 'sys_' . $basedOnId)) {
678 unset($basedOnIds[$key]);
679 }
680 }
681 if (!empty($basedOnIds)) {
682 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_template');
683 $queryBuilder->setRestrictions($this->queryBuilderRestrictions);
684 $queryResult = $queryBuilder
685 ->select('*')
686 ->from('sys_template')
687 ->where(
688 $queryBuilder->expr()->in(
689 'uid',
690 $queryBuilder->createNamedParameter($basedOnIds, Connection::PARAM_INT_ARRAY)
691 )
692 )
693 ->execute();
694 // make it an associative array with the UID as key
695 $subTemplates = [];
696 while ($rowItem = $queryResult->fetch()) {
697 $subTemplates[(int)$rowItem['uid']] = $rowItem;
698 }
699 // Traversing list again to ensure the sorting of the templates
700 foreach ($basedOnIds as $id) {
701 if (is_array($subTemplates[$id])) {
702 $this->versionOL($subTemplates[$id]);
703 $this->processTemplate($subTemplates[$id], $idList . ',sys_' . $id, $pid, 'sys_' . $id, $templateID);
704 }
705 }
706 }
707 }
708 // Include files (from extensions) (#2/2)
709 if (!empty($row['includeStaticAfterBasedOn'])) {
710 $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
711 }
712 // Creating hierarchy information; Used by backend analysis tools
713 $this->hierarchyInfo[] = ($this->hierarchyInfoToRoot[] = [
714 'root' => trim($row['root'] ?? ''),
715 'next' => $row['nextLevel'] ?? null,
716 'clConst' => $clConst,
717 'clConf' => $clConf,
718 'templateID' => $templateID,
719 'templateParent' => $templateParent,
720 'title' => $row['title'],
721 'uid' => $row['uid'],
722 'pid' => $row['pid'] ?? null,
723 'configLines' => substr_count($row['config'], LF) + 1
724 ]);
725 // Adding the content of the fields constants (Constants) and config (Setup)
726 $this->constants[] = $row['constants'];
727 $this->config[] = $row['config'];
728 $this->templateIncludePaths[] = $includePath;
729 // For backend analysis (Template Analyzer) provide the order of added constants/config template IDs
730 $this->clearList_const[] = $templateID;
731 $this->clearList_setup[] = $templateID;
732 if (trim($row['sitetitle'] ?? null)) {
733 $this->sitetitle = $row['sitetitle'];
734 }
735 // If the template record is a Rootlevel record, set the flag and clear the template rootLine (so it starts over from this point)
736 if (trim($row['root'] ?? null)) {
737 $this->rootId = $pid;
738 $this->rootLine = [];
739 }
740 // If a template is set to be active on the next level set this internal value to point to this UID. (See runThroughTemplates())
741 if ($row['nextLevel'] ?? null) {
742 $this->nextLevel = $row['nextLevel'];
743 } else {
744 $this->nextLevel = 0;
745 }
746 }
747
748 /**
749 * This function can be used to update the data of the current rootLine
750 * e.g. when a different language is used.
751 *
752 * This function must not be used if there are different pages in the
753 * rootline as before!
754 *
755 * @param array $fullRootLine Array containing the FULL rootline (up to the TYPO3 root)
756 * @throws \RuntimeException If the given $fullRootLine does not contain all pages that are in the current template rootline
757 */
758 public function updateRootlineData($fullRootLine)
759 {
760 if (!is_array($this->rootLine) || empty($this->rootLine)) {
761 return;
762 }
763
764 $fullRootLineByUid = [];
765 foreach ($fullRootLine as $rootLineData) {
766 $fullRootLineByUid[$rootLineData['uid']] = $rootLineData;
767 }
768
769 foreach ($this->rootLine as $level => $dataArray) {
770 $currentUid = $dataArray['uid'];
771
772 if (!array_key_exists($currentUid, $fullRootLineByUid)) {
773 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);
774 }
775
776 $this->rootLine[$level] = $fullRootLineByUid[$currentUid];
777 }
778 }
779
780 /**
781 * Includes static template files (from extensions) for the input template record row.
782 *
783 * @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.
784 * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
785 * @param int $pid The PID of the input template record
786 * @param array $row A full TypoScript template record
787 * @see processTemplate()
788 * @internal
789 */
790 public function includeStaticTypoScriptSources($idList, $templateID, $pid, $row)
791 {
792 // Call function for link rendering:
793 $_params = [
794 'idList' => &$idList,
795 'templateId' => &$templateID,
796 'pid' => &$pid,
797 'row' => &$row
798 ];
799 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSources'] ?? [] as $_funcRef) {
800 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
801 }
802 // If "Include before all static templates if root-flag is set" is set:
803 $staticFileMode = $row['static_file_mode'] ?? null;
804 if ($staticFileMode == 3 && strpos($templateID, 'sys_') === 0 && $row['root']) {
805 $this->addExtensionStatics($idList, $templateID, $pid);
806 }
807 // Static Template Files (Text files from extensions): include_static_file is a list of static files to include (from extensions)
808 if (trim($row['include_static_file'] ?? '')) {
809 $include_static_fileArr = GeneralUtility::trimExplode(',', $row['include_static_file'], true);
810 // Traversing list
811 foreach ($include_static_fileArr as $ISF_file) {
812 if (strpos($ISF_file, 'EXT:') === 0) {
813 list($ISF_extKey, $ISF_localPath) = explode('/', substr($ISF_file, 4), 2);
814 if ((string)$ISF_extKey !== '' && ExtensionManagementUtility::isLoaded($ISF_extKey) && (string)$ISF_localPath !== '') {
815 $ISF_localPath = rtrim($ISF_localPath, '/') . '/';
816 $ISF_filePath = ExtensionManagementUtility::extPath($ISF_extKey) . $ISF_localPath;
817 if (@is_dir($ISF_filePath)) {
818 $mExtKey = str_replace('_', '', $ISF_extKey . '/' . $ISF_localPath);
819 $subrow = [
820 'constants' => $this->getTypoScriptSourceFileContent($ISF_filePath, 'constants'),
821 'config' => $this->getTypoScriptSourceFileContent($ISF_filePath, 'setup'),
822 'include_static' => @file_exists($ISF_filePath . 'include_static.txt') ? implode(',', array_unique(GeneralUtility::intExplode(',', file_get_contents($ISF_filePath . 'include_static.txt')))) : '',
823 'include_static_file' => @file_exists($ISF_filePath . 'include_static_file.txt') ? implode(',', array_unique(explode(',', file_get_contents($ISF_filePath . 'include_static_file.txt')))) : '',
824 'title' => $ISF_file,
825 'uid' => $mExtKey
826 ];
827 $subrow = $this->prependStaticExtra($subrow);
828 $this->processTemplate($subrow, $idList . ',ext_' . $mExtKey, $pid, 'ext_' . $mExtKey, $templateID, $ISF_filePath);
829 }
830 }
831 }
832 }
833 }
834 // If "Default (include before if root flag is set)" is set OR
835 // "Always include before this template record" AND root-flag are set
836 if ($staticFileMode == 1 || $staticFileMode == 0 && strpos($templateID, 'sys_') === 0 && $row['root']) {
837 $this->addExtensionStatics($idList, $templateID, $pid);
838 }
839 // Include Static Template Records after all other TypoScript has been included.
840 $_params = [
841 'idList' => &$idList,
842 'templateId' => &$templateID,
843 'pid' => &$pid,
844 'row' => &$row
845 ];
846 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSourcesAtEnd'] ?? [] as $_funcRef) {
847 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
848 }
849 }
850
851 /**
852 * Retrieves the content of the first existing file by extension order.
853 * Returns the empty string if no file is found.
854 *
855 * @param string $filePath The location of the file.
856 * @param string $baseName The base file name. "constants" or "setup".
857 * @return string
858 */
859 protected function getTypoScriptSourceFileContent($filePath, $baseName)
860 {
861 $extensions = ['.typoscript', '.ts', '.txt'];
862 foreach ($extensions as $extension) {
863 $fileName = $filePath . $baseName . $extension;
864 if (@file_exists($fileName)) {
865 return file_get_contents($fileName);
866 }
867 }
868 return '';
869 }
870
871 /**
872 * Adds the default TypoScript files for extensions if any.
873 *
874 * @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.
875 * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
876 * @param int $pid The PID of the input template record
877 * @internal
878 * @see includeStaticTypoScriptSources()
879 */
880 public function addExtensionStatics($idList, $templateID, $pid)
881 {
882 $this->extensionStaticsProcessed = true;
883
884 foreach ($this->packageManager->getActivePackages() as $package) {
885 $extKey = $package->getPackageKey();
886 $packagePath = $package->getPackagePath();
887 $filesToCheck = [
888 'ext_typoscript_constants.txt',
889 'ext_typoscript_constants.typoscript',
890 'ext_typoscript_setup.txt',
891 'ext_typoscript_setup.typoscript',
892 ];
893 $files = [];
894 $hasExtensionStatics = false;
895 foreach ($filesToCheck as $file) {
896 $path = $packagePath . $file;
897 if (@file_exists($path)) {
898 $files[$file] = $path;
899 $hasExtensionStatics = true;
900 } else {
901 $files[$file] = null;
902 }
903 }
904
905 if ($hasExtensionStatics) {
906 $mExtKey = str_replace('_', '', $extKey);
907 $constants = '';
908 $config = '';
909
910 if (!empty($files['ext_typoscript_constants.typoscript'])) {
911 $constants = @file_get_contents($files['ext_typoscript_constants.typoscript']);
912 } elseif (!empty($files['ext_typoscript_constants.txt'])) {
913 $constants = @file_get_contents($files['ext_typoscript_constants.txt']);
914 }
915
916 if (!empty($files['ext_typoscript_setup.typoscript'])) {
917 $config = @file_get_contents($files['ext_typoscript_setup.typoscript']);
918 } elseif (!empty($files['ext_typoscript_setup.txt'])) {
919 $config = @file_get_contents($files['ext_typoscript_setup.txt']);
920 }
921
922 $this->processTemplate(
923 $this->prependStaticExtra([
924 'constants' => $constants,
925 'config' => $config,
926 'title' => $extKey,
927 'uid' => $mExtKey
928 ]),
929 $idList . ',ext_' . $mExtKey,
930 $pid,
931 'ext_' . $mExtKey,
932 $templateID,
933 $packagePath
934 );
935 }
936 }
937 }
938
939 /**
940 * Appends (not prepends) additional TypoScript code to static template records/files as set in TYPO3_CONF_VARS
941 * 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
942 *
943 * @param array $subrow Static template record/file
944 * @return array Returns the input array where the values for keys "config" and "constants" may have been modified with prepended code.
945 * @see addExtensionStatics(), includeStaticTypoScriptSources()
946 */
947 protected function prependStaticExtra($subrow)
948 {
949 // the identifier can be "43" if coming from "static template" extension or a path like "cssstyledcontent/static/"
950 $identifier = $subrow['uid'];
951 $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.'][$identifier] ?? null;
952 $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.'][$identifier] ?? null;
953 // 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
954 if (in_array($identifier, $GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'], true)) {
955 $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.']['defaultContentRendering'];
956 $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.']['defaultContentRendering'];
957 }
958 return $subrow;
959 }
960
961 /**
962 * Creating versioning overlay of a sys_template record.
963 * This will use either frontend or backend overlay functionality depending on environment.
964 *
965 * @param array $row Row to overlay (passed by reference)
966 */
967 protected function versionOL(&$row)
968 {
969 // Distinguish frontend and backend call:
970 // To do the fronted call a full frontend is required, just checking for
971 // TYPO3_MODE === 'FE' is not enough. This could otherwise lead to fatals in
972 // eId scripts that run in frontend scope, but do not have a full blown frontend.
973 if (is_object($this->getTypoScriptFrontendController()) && property_exists($this->getTypoScriptFrontendController(), 'sys_page') && method_exists($this->getTypoScriptFrontendController()->sys_page, 'versionOL')) {
974 // Frontend
975 $this->getTypoScriptFrontendController()->sys_page->versionOL('sys_template', $row);
976 } else {
977 // Backend
978 BackendUtility::workspaceOL('sys_template', $row);
979 }
980 }
981
982 /*******************************************************************
983 *
984 * Parsing TypoScript code text from Template Records into PHP array
985 *
986 *******************************************************************/
987 /**
988 * Generates the configuration array by replacing constants and parsing the whole thing.
989 * Depends on $this->config and $this->constants to be set prior to this! (done by processTemplate/runThroughTemplates)
990 *
991 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser, start()
992 */
993 public function generateConfig()
994 {
995 // Add default TS for all code types
996 $this->addDefaultTypoScript();
997
998 // Parse the TypoScript code text for include-instructions!
999 $this->processIncludes();
1000 // These vars are also set lateron...
1001 $this->setup['sitetitle'] = $this->sitetitle;
1002 // ****************************
1003 // Parse TypoScript Constants
1004 // ****************************
1005 // Initialize parser and match-condition classes:
1006 /** @var Parser\TypoScriptParser $constants */
1007 $constants = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
1008 $constants->breakPointLN = (int)$this->ext_constants_BRP;
1009 $constants->setup = $this->mergeConstantsFromPageTSconfig([]);
1010 /** @var ConditionMatcher $matchObj */
1011 $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
1012 $matchObj->setSimulateMatchConditions($this->matchAlternative);
1013 $matchObj->setSimulateMatchResult((bool)$this->matchAll);
1014 // Traverse constants text fields and parse them
1015 foreach ($this->constants as $str) {
1016 $constants->parse($str, $matchObj);
1017 }
1018 // Read out parse errors if any
1019 $this->parserErrors['constants'] = $constants->errors;
1020 // 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)
1021 $this->flatSetup = [];
1022 $this->flattenSetup($constants->setup, '');
1023 // ***********************************************
1024 // Parse TypoScript Setup (here called "config")
1025 // ***********************************************
1026 // Initialize parser and match-condition classes:
1027 /** @var Parser\TypoScriptParser $config */
1028 $config = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
1029 $config->breakPointLN = (int)$this->ext_config_BRP;
1030 $config->regLinenumbers = $this->ext_regLinenumbers;
1031 $config->regComments = $this->ext_regComments;
1032 $config->setup = $this->setup;
1033 // Transfer information about conditions found in "Constants" and which of them returned TRUE.
1034 $config->sections = $constants->sections;
1035 $config->sectionsMatch = $constants->sectionsMatch;
1036 // Traverse setup text fields and concatenate them into one, single string separated by a [GLOBAL] condition
1037 $all = '';
1038 foreach ($this->config as $str) {
1039 $all .= '
1040 [GLOBAL]
1041 ' . $str;
1042 }
1043 // Substitute constants in the Setup code:
1044 if ($this->tt_track) {
1045 $this->getTimeTracker()->push('Substitute Constants (' . count($this->flatSetup) . ')');
1046 }
1047 $all = $this->substituteConstants($all);
1048 if ($this->tt_track) {
1049 $this->getTimeTracker()->pull();
1050 }
1051
1052 // Searching for possible unsubstituted constants left (only for information)
1053 if ($this->verbose) {
1054 if (preg_match_all('/\\{\\$.[^}]*\\}/', $all, $constantList) > 0) {
1055 if ($this->tt_track) {
1056 $this->getTimeTracker()->setTSlogMessage(implode(', ', $constantList[0]) . ': Constants may remain un-substituted!!', 2);
1057 }
1058 }
1059 }
1060
1061 // Logging the textual size of the TypoScript Setup field text with all constants substituted:
1062 if ($this->tt_track) {
1063 $this->getTimeTracker()->setTSlogMessage('TypoScript template size as textfile: ' . strlen($all) . ' bytes');
1064 }
1065 // Finally parse the Setup field TypoScript code (where constants are now substituted)
1066 $config->parse($all, $matchObj);
1067 // Read out parse errors if any
1068 $this->parserErrors['config'] = $config->errors;
1069 // Transfer the TypoScript array from the parser object to the internal $this->setup array:
1070 $this->setup = $config->setup;
1071 // Do the same for the constants
1072 $this->setup_constants = $constants->setup;
1073 // ****************************************************************
1074 // Final processing of the $this->setup TypoScript Template array
1075 // Basically: This is unsetting/setting of certain reserved keys.
1076 // ****************************************************************
1077 // 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!
1078 unset($this->setup['sitetitle']);
1079 unset($this->setup['sitetitle.']);
1080 $this->setup['sitetitle'] = $this->sitetitle;
1081 // Unsetting some vars...
1082 unset($this->setup['types.']);
1083 unset($this->setup['types']);
1084 if (is_array($this->setup)) {
1085 foreach ($this->setup as $key => $value) {
1086 if ($value === 'PAGE') {
1087 // Set the typeNum of the current page object:
1088 if (isset($this->setup[$key . '.']['typeNum'])) {
1089 $typeNum = $this->setup[$key . '.']['typeNum'];
1090 $this->setup['types.'][$typeNum] = $key;
1091 } elseif (!isset($this->setup['types.'][0]) || !$this->setup['types.'][0]) {
1092 $this->setup['types.'][0] = $key;
1093 }
1094 }
1095 }
1096 }
1097 unset($this->setup['temp.']);
1098 unset($constants);
1099 // Storing the conditions found/matched information:
1100 $this->sections = $config->sections;
1101 $this->sectionsMatch = $config->sectionsMatch;
1102 }
1103
1104 /**
1105 * Searching TypoScript code text (for constants and config (Setup))
1106 * for include instructions and does the inclusion of external TypoScript files
1107 * if needed.
1108 *
1109 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser, generateConfig()
1110 */
1111 protected function processIncludes()
1112 {
1113 if ($this->processIncludesHasBeenRun) {
1114 return;
1115 }
1116
1117 $paths = $this->templateIncludePaths;
1118 $files = [];
1119 foreach ($this->constants as &$value) {
1120 $includeData = Parser\TypoScriptParser::checkIncludeLines($value, 1, true, array_shift($paths));
1121 $files = array_merge($files, $includeData['files']);
1122 $value = $includeData['typoscript'];
1123 }
1124 unset($value);
1125 $paths = $this->templateIncludePaths;
1126 foreach ($this->config as &$value) {
1127 $includeData = Parser\TypoScriptParser::checkIncludeLines($value, 1, true, array_shift($paths));
1128 $files = array_merge($files, $includeData['files']);
1129 $value = $includeData['typoscript'];
1130 }
1131 unset($value);
1132
1133 if (!empty($files)) {
1134 $files = array_unique($files);
1135 foreach ($files as $file) {
1136 $this->rowSum[] = [$file, filemtime($file)];
1137 }
1138 }
1139
1140 $this->processIncludesHasBeenRun = true;
1141 }
1142
1143 /**
1144 * 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!
1145 *
1146 * @param array $constArray Constants array, default input.
1147 * @return array Constants array, modified
1148 * @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...)
1149 */
1150 protected function mergeConstantsFromPageTSconfig($constArray)
1151 {
1152 $TSdataArray = [];
1153 // Setting default configuration:
1154 $TSdataArray[] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];
1155 for ($a = 0; $a <= $this->outermostRootlineIndexWithTemplate; $a++) {
1156 if (trim($this->absoluteRootLine[$a]['tsconfig_includes'])) {
1157 $includeTsConfigFileList = GeneralUtility::trimExplode(
1158 ',',
1159 $this->absoluteRootLine[$a]['tsconfig_includes'],
1160 true
1161 );
1162
1163 $TSdataArray = $this->mergeConstantsFromIncludedTsConfigFiles($includeTsConfigFileList, $TSdataArray);
1164 }
1165 $TSdataArray[] = $this->absoluteRootLine[$a]['TSconfig'];
1166 }
1167 // Parsing the user TS (or getting from cache)
1168 $TSdataArray = Parser\TypoScriptParser::checkIncludeLines_array($TSdataArray);
1169 $userTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
1170 /** @var Parser\TypoScriptParser $parseObj */
1171 $parseObj = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
1172 $parseObj->parse($userTS);
1173 if (is_array($parseObj->setup['TSFE.']['constants.'])) {
1174 ArrayUtility::mergeRecursiveWithOverrule($constArray, $parseObj->setup['TSFE.']['constants.']);
1175 }
1176
1177 return $constArray;
1178 }
1179
1180 /**
1181 * Reads TSconfig defined in external files and appends it to the given TSconfig array (in this case only constants)
1182 *
1183 * @param array $filesToInclude The files to read constants from
1184 * @param array $TSdataArray The TSconfig array the constants should be appended to
1185 * @return array The TSconfig with the included constants appended
1186 */
1187 protected function mergeConstantsFromIncludedTsConfigFiles($filesToInclude, $TSdataArray)
1188 {
1189 foreach ($filesToInclude as $key => $file) {
1190 if (strpos($file, 'EXT:') !== 0) {
1191 continue;
1192 }
1193
1194 list($extensionKey, $filePath) = explode('/', substr($file, 4), 2);
1195
1196 if ((string)$extensionKey === '' || !ExtensionManagementUtility::isLoaded($extensionKey)) {
1197 continue;
1198 }
1199 if ((string)$filePath == '') {
1200 continue;
1201 }
1202
1203 $tsConfigFile = ExtensionManagementUtility::extPath($extensionKey) . $filePath;
1204 if (file_exists($tsConfigFile)) {
1205 $TSdataArray[] = file_get_contents($tsConfigFile);
1206 }
1207 }
1208
1209 return $TSdataArray;
1210 }
1211
1212 /**
1213 * This flattens a hierarchical TypoScript array to $this->flatSetup
1214 *
1215 * @param array $setupArray TypoScript array
1216 * @param string $prefix Prefix to the object path. Used for recursive calls to this function.
1217 * @see generateConfig()
1218 */
1219 protected function flattenSetup($setupArray, $prefix)
1220 {
1221 if (is_array($setupArray)) {
1222 foreach ($setupArray as $key => $val) {
1223 if (is_array($val)) {
1224 $this->flattenSetup($val, $prefix . $key);
1225 } else {
1226 $this->flatSetup[$prefix . $key] = $val;
1227 }
1228 }
1229 }
1230 }
1231
1232 /**
1233 * Substitutes the constants from $this->flatSetup in the text string $all
1234 *
1235 * @param string $all TypoScript code text string
1236 * @return string The processed string with all constants found in $this->flatSetup as key/value pairs substituted.
1237 * @see generateConfig(), flattenSetup()
1238 */
1239 protected function substituteConstants($all)
1240 {
1241 if ($this->tt_track) {
1242 $this->getTimeTracker()->setTSlogMessage('Constants to substitute: ' . count($this->flatSetup));
1243 }
1244 $noChange = false;
1245 // Recursive substitution of constants (up to 10 nested levels)
1246 for ($i = 0; $i < 10 && !$noChange; $i++) {
1247 $old_all = $all;
1248 $all = preg_replace_callback('/\\{\\$(.[^}]*)\\}/', [$this, 'substituteConstantsCallBack'], $all);
1249 if ($old_all == $all) {
1250 $noChange = true;
1251 }
1252 }
1253 return $all;
1254 }
1255
1256 /**
1257 * Call back method for preg_replace_callback in substituteConstants
1258 *
1259 * @param array $matches Regular expression matches
1260 * @return string Replacement
1261 * @see substituteConstants()
1262 * @internal
1263 */
1264 public function substituteConstantsCallBack($matches)
1265 {
1266 // Replace {$CONST} if found in $this->flatSetup, else leave unchanged
1267 return isset($this->flatSetup[$matches[1]]) && !is_array($this->flatSetup[$matches[1]]) ? $this->flatSetup[$matches[1]] : $matches[0];
1268 }
1269
1270 /*******************************************************************
1271 *
1272 * Various API functions, used from elsewhere in the frontend classes
1273 *
1274 *******************************************************************/
1275
1276 /**
1277 * Returns the level of the given page in the rootline - Multiple pages can be given by separating the UIDs by comma.
1278 *
1279 * @param string $list A list of UIDs for which the rootline-level should get returned
1280 * @return int The level in the rootline. If more than one page was given the lowest level will get returned.
1281 */
1282 public function getRootlineLevel($list)
1283 {
1284 $idx = 0;
1285 foreach ($this->rootLine as $page) {
1286 if (GeneralUtility::inList($list, $page['uid'])) {
1287 return $idx;
1288 }
1289 $idx++;
1290 }
1291 return false;
1292 }
1293
1294 /**
1295 * Returns the page ID of the rootlevel
1296 *
1297 * @return int
1298 */
1299 public function getRootId(): int
1300 {
1301 return (int)$this->rootId;
1302 }
1303
1304 /*******************************************************************
1305 *
1306 * Functions for creating links
1307 *
1308 *******************************************************************/
1309
1310 /**
1311 * Adds the TypoScript from the global array.
1312 * The class property isDefaultTypoScriptAdded ensures
1313 * that the adding only happens once.
1314 *
1315 * @see isDefaultTypoScriptAdded
1316 */
1317 protected function addDefaultTypoScript()
1318 {
1319 // Add default TS for all code types, if not done already
1320 if (!$this->isDefaultTypoScriptAdded) {
1321 // adding default setup and constants
1322 // defaultTypoScript_setup is *very* unlikely to be empty
1323 // the count of elements in ->constants, ->config and ->templateIncludePaths have to be in sync
1324 array_unshift($this->constants, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants']);
1325 array_unshift($this->config, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup']);
1326 array_unshift($this->templateIncludePaths, '');
1327 // prepare a proper entry to hierachyInfo (used by TemplateAnalyzer in BE)
1328 $rootTemplateId = $this->hierarchyInfo[count($this->hierarchyInfo) - 1]['templateID'] ?? null;
1329 $defaultTemplateInfo = [
1330 'root' => '',
1331 'next' => '',
1332 'clConst' => '',
1333 'clConf' => '',
1334 'templateID' => '_defaultTypoScript_',
1335 'templateParent' => $rootTemplateId,
1336 'title' => 'SYS:TYPO3_CONF_VARS:FE:defaultTypoScript',
1337 'uid' => '_defaultTypoScript_',
1338 'pid' => '',
1339 'configLines' => substr_count((string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup'], LF) + 1
1340 ];
1341 // push info to information arrays used in BE by TemplateTools (Analyzer)
1342 array_unshift($this->clearList_const, $defaultTemplateInfo['uid']);
1343 array_unshift($this->clearList_setup, $defaultTemplateInfo['uid']);
1344 array_unshift($this->hierarchyInfo, $defaultTemplateInfo);
1345 $this->isDefaultTypoScriptAdded = true;
1346 }
1347 }
1348
1349 /**
1350 * @return TypoScriptFrontendController
1351 */
1352 protected function getTypoScriptFrontendController()
1353 {
1354 return $GLOBALS['TSFE'];
1355 }
1356
1357 /**
1358 * @return TimeTracker
1359 */
1360 protected function getTimeTracker()
1361 {
1362 return GeneralUtility::makeInstance(TimeTracker::class);
1363 }
1364
1365 /**
1366 * Returns data stored for the hash string in the cache "cache_hash"
1367 * used to store the parsed TypoScript template structures.
1368 *
1369 * @param string $identifier The hash-string which was used to store the data value
1370 * @return mixed The data from the cache
1371 */
1372 protected function getCacheEntry($identifier)
1373 {
1374 return GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash')->get($identifier);
1375 }
1376
1377 /**
1378 * Stores $data in the 'cache_hash' cache with the hash key $identifier
1379 *
1380 * @param string $identifier 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
1381 * @param mixed $data The data to store
1382 * @param string $tag Is just a textual identification in order to inform about the content
1383 */
1384 protected function setCacheEntry($identifier, $data, $tag)
1385 {
1386 GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash')->set($identifier, $data, ['ident_' . $tag], 0);
1387 }
1388 }