2 namespace TYPO3\CMS\Core\TypoScript
;
5 * This file is part of the TYPO3 CMS project.
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.
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
14 * The TYPO3 project - inspiring people to share!
17 use TYPO3\CMS\Core\Cache\CacheManager
;
18 use TYPO3\CMS\Core\Compatibility\PublicPropertyDeprecationTrait
;
19 use TYPO3\CMS\Core\Context\Context
;
20 use TYPO3\CMS\Core\Context\TypoScriptAspect
;
21 use TYPO3\CMS\Core\Database\Connection
;
22 use TYPO3\CMS\Core\Database\ConnectionPool
;
23 use TYPO3\CMS\Core\Database\Query\Restriction\AbstractRestrictionContainer
;
24 use TYPO3\CMS\Core\Database\Query\Restriction\DefaultRestrictionContainer
;
25 use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction
;
26 use TYPO3\CMS\Core\Domain\Repository\PageRepository
;
27 use TYPO3\CMS\Core\Package\PackageManager
;
28 use TYPO3\CMS\Core\TimeTracker\TimeTracker
;
29 use TYPO3\CMS\Core\Utility\ArrayUtility
;
30 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility
;
31 use TYPO3\CMS\Core\Utility\GeneralUtility
;
32 use TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher
;
33 use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController
;
36 * Template object that is responsible for generating the TypoScript template based on template records.
37 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
38 * @see \TYPO3\CMS\Core\Configuration\TypoScript\ConditionMatching\AbstractConditionMatcher
42 use PublicPropertyDeprecationTrait
;
44 private $deprecatedPublicProperties = [
45 'forceTemplateParsing' => 'Using tmpl->forceTemplateParsing is deprecated and will no longer work with TYPO3 v11.0. Use TypoScriptAspect from Context instead.'
49 * option to enable logging, time-tracking (FE-only)
50 * usually, this is only done when
51 * - in FE a BE_USER is logged-in
52 * - in BE when the BE_USER needs information about the template (TypoScript module)
55 protected $verbose = false
;
58 * If set, the global tt-timeobject is used to log the performance.
62 public $tt_track = true
;
65 * If set, the template is always rendered. Used from Admin Panel.
70 private $forceTemplateParsing = false
;
73 * This array is passed on to matchObj by generateConfig().
74 * If it holds elements, they are used for matching instead. See comment at the match-class.
75 * Used for backend modules only. Never frontend!
80 public $matchAlternative = [];
83 * If set, the match-class matches everything! Used for backend modules only. Never frontend!
87 protected $matchAll = false
;
90 * Externally set breakpoints (used by Backend Modules)
94 public $ext_constants_BRP = 0;
99 public $ext_config_BRP = 0;
104 public $ext_regLinenumbers = false
;
109 public $ext_regComments = false
;
112 * Set if preview of some kind is enabled.
116 protected $simulationHiddenOrTime = false
;
119 * Set, if the TypoScript template structure is loaded and OK, see ->start()
123 public $loaded = false
;
126 * @var array Contains TypoScript setup part after parsing
133 public $flatSetup = [];
136 * For fetching TypoScript code from template hierarchy before parsing it.
137 * Each array contains code field values from template records/files:
149 public $constants = [];
152 * Holds the include paths of the templates (empty if from database)
156 protected $templateIncludePaths = [];
159 * For Template Analyzer in backend
163 public $hierarchyInfo = [];
166 * For Template Analyzer in backend (setup content only)
170 protected $hierarchyInfoToRoot = [];
173 * The Page UID of the root page
180 * The rootline from current page to the root page
187 * Rootline all the way to the root. Set but runThroughTemplates
191 protected $absoluteRootLine;
194 * Array of arrays with title/uid of templates in hierarchy
201 * The current site title field.
205 protected $sitetitle = '';
208 * Tracking all conditions found during parsing of TypoScript. Used for the "all" key in currentPageData
215 * Tracking all matching conditions found
219 protected $sectionsMatch;
222 * Used by Backend only (Typoscript Template Analyzer)
224 public $clearList_const = [];
227 * Used by Backend only (Typoscript Template Analyzer)
231 public $clearList_setup = [];
236 public $parserErrors = [];
241 public $setup_constants = [];
244 * Indicator that extension statics are processed.
246 * These files are considered if either a root template
247 * has been processed or the $processExtensionStatics
248 * property has been set to TRUE.
252 protected $extensionStaticsProcessed = false
;
255 * Trigger value, to ensure that extension statics are processed.
259 protected $processExtensionStatics = false
;
262 * Set to TRUE after the default TypoScript was added during parsing.
263 * This prevents double inclusion of the same TypoScript code.
265 * @see addDefaultTypoScript()
268 protected $isDefaultTypoScriptAdded = false
;
271 * Set to TRUE after $this->config and $this->constants have processed all <INCLUDE_TYPOSCRIPT:> instructions.
273 * This prevents double processing of INCLUDES.
275 * @see processIncludes()
278 protected $processIncludesHasBeenRun = false
;
281 * Contains the restrictions about deleted, and some frontend related topics
282 * @var AbstractRestrictionContainer
284 protected $queryBuilderRestrictions;
292 * @var PackageManager
294 protected $packageManager;
297 * @var TypoScriptFrontendController|null
299 protected $frontendController;
302 * @param Context|null $context
303 * @param PackageManager|null $packageManager
304 * @param TypoScriptFrontendController|null $frontendController
306 public function __construct(Context
$context = null
, PackageManager
$packageManager = null
, TypoScriptFrontendController
$frontendController = null
)
308 $this->context
= $context ?? GeneralUtility
::makeInstance(Context
::class);
309 $this->packageManager
= $packageManager ?? GeneralUtility
::makeInstance(PackageManager
::class);
310 $this->frontendController
= $frontendController;
311 $this->initializeDatabaseQueryRestrictions();
312 if ($this->context
->getPropertyFromAspect('visibility', 'includeHiddenContent', false
) ||
$GLOBALS['SIM_ACCESS_TIME'] !== $GLOBALS['ACCESS_TIME']) {
313 // Set the simulation flag, if simulation is detected!
314 $this->simulationHiddenOrTime
= true
;
316 $this->tt_track
= $this->verbose
= (bool
)$this->context
->getPropertyFromAspect('backend.user', 'isLoggedIn', false
);
322 public function getProcessExtensionStatics()
324 return $this->processExtensionStatics
;
328 * @param bool $processExtensionStatics
330 public function setProcessExtensionStatics($processExtensionStatics)
332 $this->processExtensionStatics
= (bool
)$processExtensionStatics;
336 * sets the verbose parameter
337 * @param bool $verbose
339 public function setVerbose($verbose)
341 $this->verbose
= (bool
)$verbose;
345 * Set up the query builder restrictions, optionally include hidden records
347 protected function initializeDatabaseQueryRestrictions()
349 $this->queryBuilderRestrictions
= GeneralUtility
::makeInstance(DefaultRestrictionContainer
::class);
351 if ($this->context
->getPropertyFromAspect('visibility', 'includeHiddenContent', false
)) {
352 $this->queryBuilderRestrictions
->removeByType(HiddenRestriction
::class);
357 * Fetches the "currentPageData" array from cache
359 * NOTE about currentPageData:
360 * It holds information about the TypoScript conditions along with the list
361 * of template uid's which is used on the page. In the getFromCache() function
362 * in TSFE, currentPageData is used to evaluate if there is a template and
363 * if the matching conditions are alright. Unfortunately this does not take
364 * into account if the templates in the rowSum of currentPageData has
365 * changed composition, eg. due to hidden fields or start/end time. So if a
366 * template is hidden or times out, it'll not be discovered unless the page
367 * is regenerated - at least the this->start function must be called,
368 * because this will make a new portion of data in currentPageData string.
370 * @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
373 public function getCurrentPageData()
375 return GeneralUtility
::makeInstance(CacheManager
::class)->getCache('pagesection')->get((int)$this->getTypoScriptFrontendController()->id
. '_' . GeneralUtility
::md5int($this->getTypoScriptFrontendController()->MP
));
379 * Fetches data about which TypoScript-matches there are at this page. Then it performs a matchingtest.
381 * @param array $cc An array with three keys, "all", "rowSum" and "rootLine" - all coming from the "currentPageData" array
382 * @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.
384 public function matching($cc)
386 if (is_array($cc['all'])) {
387 /** @var ConditionMatcher $matchObj */
388 $matchObj = GeneralUtility
::makeInstance(ConditionMatcher
::class);
389 $matchObj->setRootline((array)$cc['rootLine']);
391 foreach ($cc['all'] as $key => $pre) {
392 if ($matchObj->match($pre)) {
393 $sectionsMatch[$key] = $pre;
396 $cc['match'] = $sectionsMatch;
402 * This is all about fetching the right TypoScript template structure. If it's not cached then it must be generated and cached!
403 * 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.
404 * Sets $this->setup to the parsed TypoScript template array
406 * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
407 * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getConfigArray()
409 public function start($theRootLine)
411 // @deprecated - can be removed with TYPO3 v11.0
412 if ((bool
)$this->forceTemplateParsing
) {
413 $this->context
->setAspect('typoscript', GeneralUtility
::makeInstance(TypoScriptAspect
::class, true
));
415 if (is_array($theRootLine)) {
418 $cacheIdentifier = '';
419 // Flag that indicates that the existing data in cache_pagesection
420 // could be used (this is the case if $TSFE->all is set, and the
421 // rowSum still matches). Based on this we decide if cache_pagesection
422 // needs to be updated...
424 $this->runThroughTemplates($theRootLine);
425 if ($this->getTypoScriptFrontendController()->all
) {
426 $cc = $this->getTypoScriptFrontendController()->all
;
427 // The two rowSums must NOT be different from each other - which they will be if start/endtime or hidden has changed!
428 if (serialize($this->rowSum
) !== serialize($cc['rowSum'])) {
431 // If $TSFE->all contains valid data, we don't need to update cache_pagesection (because this data was fetched from there already)
432 if (serialize($this->rootLine
) === serialize($cc['rootLine'])) {
435 // 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)...
436 unset($cc['rootLine']);
439 // This is about getting the hash string which is used to fetch the cached TypoScript template.
440 // If there was some cached currentPageData ($cc) then that's good (it gives us the hash).
441 if (isset($cc) && is_array($cc)) {
442 // If currentPageData was actually there, we match the result (if this wasn't done already in $TSFE->getFromCache()...)
444 // @todo check if this can ever be the case - otherwise remove
445 $cc = $this->matching($cc);
448 $cacheIdentifier = md5(serialize($cc));
450 // 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.
451 $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum
));
452 $result = $this->getCacheEntry($rowSumHash);
453 if (is_array($result)) {
455 $cc['all'] = $result;
456 $cc['rowSum'] = $this->rowSum
;
457 $cc = $this->matching($cc);
459 $cacheIdentifier = md5(serialize($cc));
462 if ($cacheIdentifier) {
463 // Get TypoScript setup array
464 $cachedData = $this->getCacheEntry($cacheIdentifier);
465 if (is_array($cachedData)) {
466 $constantsData = $cachedData['constants'];
467 $setupData = $cachedData['setup'];
470 if (!empty($setupData) && !$this->context
->getPropertyFromAspect('typoscript', 'forcedTemplateParsing')) {
471 // TypoScript constants + setup are found in the cache
472 $this->setup_constants
= $constantsData;
473 $this->setup
= $setupData;
474 if ($this->tt_track
) {
475 $this->getTimeTracker()->setTSlogMessage('Using cached TS template data');
478 if ($this->tt_track
) {
479 $this->getTimeTracker()->setTSlogMessage('Not using any cached TS data');
482 // Make configuration
483 $this->generateConfig();
484 // This stores the template hash thing
486 // All sections in the template at this point is found
487 $cc['all'] = $this->sections
;
488 // The line of templates is collected
489 $cc['rowSum'] = $this->rowSum
;
490 $cc = $this->matching($cc);
492 $cacheIdentifier = md5(serialize($cc));
493 // This stores the data.
494 $this->setCacheEntry($cacheIdentifier, ['constants' => $this->setup_constants
, 'setup' => $this->setup
], 'TS_TEMPLATE');
495 if ($this->tt_track
) {
496 $this->getTimeTracker()->setTSlogMessage('TS template size, serialized: ' . strlen(serialize($this->setup
)) . ' bytes');
498 $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum
));
499 $this->setCacheEntry($rowSumHash, $cc['all'], 'TMPL_CONDITIONS_ALL');
502 $cc['rootLine'] = $this->rootLine
;
504 // Make global and save
505 $this->getTypoScriptFrontendController()->all
= $cc;
506 // Matching must be executed for every request, so this must never be part of the pagesection cache!
508 if (!$isCached && !$this->simulationHiddenOrTime
&& !$this->getTypoScriptFrontendController()->no_cache
) {
509 // Only save the data if we're not simulating by hidden/starttime/endtime
510 $mpvarHash = GeneralUtility
::md5int($this->getTypoScriptFrontendController()->MP
);
511 /** @var \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface $pageSectionCache */
512 $pageSectionCache = GeneralUtility
::makeInstance(CacheManager
::class)->getCache('pagesection');
513 $pageSectionCache->set((int)$this->getTypoScriptFrontendController()->id
. '_' . $mpvarHash, $cc, [
514 'pageId_' . (int)$this->getTypoScriptFrontendController()->id
,
515 'mpvarHash_' . $mpvarHash
519 if ($this->rootId
&& $this->rootLine
&& $this->setup
) {
520 $this->loaded
= true
;
525 /*******************************************************************
527 * Fetching TypoScript code text for the Template Hierarchy
529 *******************************************************************/
531 * 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.
532 * Resets and affects internal variables like $this->constants, $this->config and $this->rowSum
533 * 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
535 * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
536 * @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)
539 public function runThroughTemplates($theRootLine, $start_template_uid = 0)
541 $this->constants
= [];
544 $this->hierarchyInfoToRoot
= [];
545 $this->absoluteRootLine
= $theRootLine;
546 $this->isDefaultTypoScriptAdded
= false
;
548 reset($this->absoluteRootLine
);
549 $c = count($this->absoluteRootLine
);
550 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable('sys_template');
551 for ($a = 0; $a < $c; $a++
) {
553 $queryBuilder->expr()->eq(
555 $queryBuilder->createNamedParameter($this->absoluteRootLine
[$a]['uid'], \PDO
::PARAM_INT
)
558 // If first loop AND there is set an alternative template uid, use that
559 if ($a === $c - 1 && $start_template_uid) {
560 $where[] = $queryBuilder->expr()->eq(
562 $queryBuilder->createNamedParameter($start_template_uid, \PDO
::PARAM_INT
)
565 $queryBuilder->setRestrictions($this->queryBuilderRestrictions
);
566 $queryResult = $queryBuilder
568 ->from('sys_template')
570 ->orderBy('root', 'DESC')
571 ->addOrderBy('sorting')
574 if ($row = $queryResult->fetch()) {
575 $this->versionOL($row);
576 if (is_array($row)) {
577 $this->processTemplate($row, 'sys_' . $row['uid'], $this->absoluteRootLine
[$a]['uid'], 'sys_' . $row['uid']);
580 $this->rootLine
[] = $this->absoluteRootLine
[$a];
583 // Hook into the default TypoScript to add custom typoscript logic
585 'extensionStaticsProcessed' => &$this->extensionStaticsProcessed
,
586 'isDefaultTypoScriptAdded' => &$this->isDefaultTypoScriptAdded
,
587 'absoluteRootLine' => &$this->absoluteRootLine
,
588 'rootLine' => &$this->rootLine
,
589 'startTemplateUid' => $start_template_uid,
591 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['Core/TypoScript/TemplateService']['runThroughTemplatesPostProcessing'] ??
[] as $listener) {
592 GeneralUtility
::callUserFunction($listener, $hookParameters, $this);
595 // Process extension static files if not done yet, but explicitly requested
596 if (!$this->extensionStaticsProcessed
&& $this->processExtensionStatics
) {
597 $this->addExtensionStatics('sys_0', 'sys_0', 0);
600 // Add the global default TypoScript from the TYPO3_CONF_VARS
601 $this->addDefaultTypoScript();
603 $this->processIncludes();
607 * Checks if the template ($row) has some included templates and after including them it fills the arrays with the setup
608 * Builds up $this->rowSum
610 * @param array $row A full TypoScript template record (sys_template/forged "dummy" record made from static template file)
611 * @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.
612 * @param int $pid The PID of the input template record
613 * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
614 * @param string $templateParent Parent template id (during recursive call); Same syntax as $idList ids, eg. "sys_123
615 * @param string $includePath Specifies the path from which the template was included (used with static_includes)
616 * @see runThroughTemplates()
618 public function processTemplate($row, $idList, $pid, $templateID = '', $templateParent = '', $includePath = '')
620 // Adding basic template record information to rowSum array
621 $this->rowSum
[] = [$row['uid'] ?? null
, $row['title'] ?? null
, $row['tstamp'] ?? null
];
622 // Processing "Clear"-flags
625 if (!empty($row['clear'])) {
626 $clConst = $row['clear'] & 1;
627 $clConf = $row['clear'] & 2;
629 // Keep amount of items to stay in sync with $this->templateIncludePaths so processIncludes() does not break
630 foreach ($this->constants
as &$constantConfiguration) {
631 $constantConfiguration = '';
633 unset($constantConfiguration);
634 $this->clearList_const
= [];
637 // Keep amount of items to stay in sync with $this->templateIncludePaths so processIncludes() does not break
638 foreach ($this->config
as &$configConfiguration) {
639 $configConfiguration = '';
641 unset($configConfiguration);
642 $this->hierarchyInfoToRoot
= [];
643 $this->clearList_setup
= [];
646 // Include files (from extensions) (#1/2)
647 // NORMAL inclusion, The EXACT same code is found below the basedOn inclusion!!!
648 if (!isset($row['includeStaticAfterBasedOn']) ||
!$row['includeStaticAfterBasedOn']) {
649 $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
651 // Include "Based On" sys_templates:
652 // 'basedOn' is a list of templates to include
653 if (trim($row['basedOn'] ??
'')) {
654 // Normal Operation, which is to include the "based-on" sys_templates,
655 // if they are not already included, and maintaining the sorting of the templates
656 $basedOnIds = GeneralUtility
::intExplode(',', $row['basedOn'], true
);
657 // skip template if it's already included
658 foreach ($basedOnIds as $key => $basedOnId) {
659 if (GeneralUtility
::inList($idList, 'sys_' . $basedOnId)) {
660 unset($basedOnIds[$key]);
663 if (!empty($basedOnIds)) {
664 $queryBuilder = GeneralUtility
::makeInstance(ConnectionPool
::class)->getQueryBuilderForTable('sys_template');
665 $queryBuilder->setRestrictions($this->queryBuilderRestrictions
);
666 $queryResult = $queryBuilder
668 ->from('sys_template')
670 $queryBuilder->expr()->in(
672 $queryBuilder->createNamedParameter($basedOnIds, Connection
::PARAM_INT_ARRAY
)
676 // make it an associative array with the UID as key
678 while ($rowItem = $queryResult->fetch()) {
679 $subTemplates[(int)$rowItem['uid']] = $rowItem;
681 // Traversing list again to ensure the sorting of the templates
682 foreach ($basedOnIds as $id) {
683 if (is_array($subTemplates[$id])) {
684 $this->versionOL($subTemplates[$id]);
685 $this->processTemplate($subTemplates[$id], $idList . ',sys_' . $id, $pid, 'sys_' . $id, $templateID);
690 // Include files (from extensions) (#2/2)
691 if (!empty($row['includeStaticAfterBasedOn'])) {
692 $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
694 // Creating hierarchy information; Used by backend analysis tools
695 $this->hierarchyInfo
[] = ($this->hierarchyInfoToRoot
[] = [
696 'root' => trim($row['root'] ??
''),
697 'clConst' => $clConst,
699 'templateID' => $templateID,
700 'templateParent' => $templateParent,
701 'title' => $row['title'],
702 'uid' => $row['uid'],
703 'pid' => $row['pid'] ?? null
,
704 'configLines' => substr_count($row['config'], LF
) +
1
706 // Adding the content of the fields constants (Constants) and config (Setup)
707 $this->constants
[] = $row['constants'];
708 $this->config
[] = $row['config'];
709 $this->templateIncludePaths
[] = $includePath;
710 // For backend analysis (Template Analyzer) provide the order of added constants/config template IDs
711 $this->clearList_const
[] = $templateID;
712 $this->clearList_setup
[] = $templateID;
713 if (trim($row['sitetitle'] ?? null
)) {
714 $this->sitetitle
= $row['sitetitle'];
716 // If the template record is a Rootlevel record, set the flag and clear the template rootLine (so it starts over from this point)
717 if (trim($row['root'] ?? null
)) {
718 $this->rootId
= $pid;
719 $this->rootLine
= [];
724 * This function can be used to update the data of the current rootLine
725 * e.g. when a different language is used.
727 * This function must not be used if there are different pages in the
728 * rootline as before!
730 * @param array $fullRootLine Array containing the FULL rootline (up to the TYPO3 root)
731 * @throws \RuntimeException If the given $fullRootLine does not contain all pages that are in the current template rootline
733 public function updateRootlineData($fullRootLine)
735 if (!is_array($this->rootLine
) ||
empty($this->rootLine
)) {
739 $fullRootLineByUid = [];
740 foreach ($fullRootLine as $rootLineData) {
741 $fullRootLineByUid[$rootLineData['uid']] = $rootLineData;
744 foreach ($this->rootLine
as $level => $dataArray) {
745 $currentUid = $dataArray['uid'];
747 if (!array_key_exists($currentUid, $fullRootLineByUid)) {
748 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);
751 $this->rootLine
[$level] = $fullRootLineByUid[$currentUid];
756 * Includes static template files (from extensions) for the input template record row.
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 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 string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
760 * @param int $pid The PID of the input template record
761 * @param array $row A full TypoScript template record
762 * @see processTemplate()
765 public function includeStaticTypoScriptSources($idList, $templateID, $pid, $row)
767 // Call function for link rendering:
769 'idList' => &$idList,
770 'templateId' => &$templateID,
774 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSources'] ??
[] as $_funcRef) {
775 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
777 // If "Include before all static templates if root-flag is set" is set:
778 $staticFileMode = $row['static_file_mode'] ?? null
;
779 if ($staticFileMode == 3 && strpos($templateID, 'sys_') === 0 && $row['root']) {
780 $this->addExtensionStatics($idList, $templateID, $pid);
782 // Static Template Files (Text files from extensions): include_static_file is a list of static files to include (from extensions)
783 if (trim($row['include_static_file'] ??
'')) {
784 $include_static_fileArr = GeneralUtility
::trimExplode(',', $row['include_static_file'], true
);
786 foreach ($include_static_fileArr as $ISF_file) {
787 if (strpos($ISF_file, 'EXT:') === 0) {
788 list($ISF_extKey, $ISF_localPath) = explode('/', substr($ISF_file, 4), 2);
789 if ((string)$ISF_extKey !== '' && ExtensionManagementUtility
::isLoaded($ISF_extKey) && (string)$ISF_localPath !== '') {
790 $ISF_localPath = rtrim($ISF_localPath, '/') . '/';
791 $ISF_filePath = ExtensionManagementUtility
::extPath($ISF_extKey) . $ISF_localPath;
792 if (@is_dir
($ISF_filePath)) {
793 $mExtKey = str_replace('_', '', $ISF_extKey . '/' . $ISF_localPath);
795 'constants' => $this->getTypoScriptSourceFileContent($ISF_filePath, 'constants'),
796 'config' => $this->getTypoScriptSourceFileContent($ISF_filePath, 'setup'),
797 'include_static' => @file_exists
($ISF_filePath . 'include_static.txt') ?
implode(',', array_unique(GeneralUtility
::intExplode(',', file_get_contents($ISF_filePath . 'include_static.txt')))) : '',
798 'include_static_file' => @file_exists
($ISF_filePath . 'include_static_file.txt') ?
implode(',', array_unique(explode(',', file_get_contents($ISF_filePath . 'include_static_file.txt')))) : '',
799 'title' => $ISF_file,
802 $subrow = $this->prependStaticExtra($subrow);
803 $this->processTemplate($subrow, $idList . ',ext_' . $mExtKey, $pid, 'ext_' . $mExtKey, $templateID, $ISF_filePath);
809 // If "Default (include before if root flag is set)" is set OR
810 // "Always include before this template record" AND root-flag are set
811 if ($staticFileMode == 1 ||
$staticFileMode == 0 && strpos($templateID, 'sys_') === 0 && $row['root']) {
812 $this->addExtensionStatics($idList, $templateID, $pid);
814 // Include Static Template Records after all other TypoScript has been included.
816 'idList' => &$idList,
817 'templateId' => &$templateID,
821 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSourcesAtEnd'] ??
[] as $_funcRef) {
822 GeneralUtility
::callUserFunction($_funcRef, $_params, $this);
827 * Retrieves the content of the first existing file by extension order.
828 * Returns the empty string if no file is found.
830 * @param string $filePath The location of the file.
831 * @param string $baseName The base file name. "constants" or "setup".
834 protected function getTypoScriptSourceFileContent($filePath, $baseName)
836 $extensions = ['.typoscript', '.ts', '.txt'];
837 foreach ($extensions as $extension) {
838 $fileName = $filePath . $baseName . $extension;
839 if (@file_exists
($fileName)) {
840 return file_get_contents($fileName);
847 * Adds the default TypoScript files for extensions if any.
849 * @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.
850 * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
851 * @param int $pid The PID of the input template record
853 * @see includeStaticTypoScriptSources()
855 public function addExtensionStatics($idList, $templateID, $pid)
857 $this->extensionStaticsProcessed
= true
;
859 foreach ($this->packageManager
->getActivePackages() as $package) {
860 $extKey = $package->getPackageKey();
861 $packagePath = $package->getPackagePath();
863 'ext_typoscript_constants.txt',
864 'ext_typoscript_constants.typoscript',
865 'ext_typoscript_setup.txt',
866 'ext_typoscript_setup.typoscript',
869 $hasExtensionStatics = false
;
870 foreach ($filesToCheck as $file) {
871 $path = $packagePath . $file;
872 if (@file_exists
($path)) {
873 $files[$file] = $path;
874 $hasExtensionStatics = true
;
876 $files[$file] = null
;
880 if ($hasExtensionStatics) {
881 $mExtKey = str_replace('_', '', $extKey);
885 if (!empty($files['ext_typoscript_constants.typoscript'])) {
886 $constants = @file_get_contents
($files['ext_typoscript_constants.typoscript']);
887 } elseif (!empty($files['ext_typoscript_constants.txt'])) {
888 $constants = @file_get_contents
($files['ext_typoscript_constants.txt']);
891 if (!empty($files['ext_typoscript_setup.typoscript'])) {
892 $config = @file_get_contents
($files['ext_typoscript_setup.typoscript']);
893 } elseif (!empty($files['ext_typoscript_setup.txt'])) {
894 $config = @file_get_contents
($files['ext_typoscript_setup.txt']);
897 $this->processTemplate(
898 $this->prependStaticExtra([
899 'constants' => $constants,
904 $idList . ',ext_' . $mExtKey,
915 * Appends (not prepends) additional TypoScript code to static template records/files as set in TYPO3_CONF_VARS
916 * 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
918 * @param array $subrow Static template record/file
919 * @return array Returns the input array where the values for keys "config" and "constants" may have been modified with prepended code.
920 * @see addExtensionStatics()
921 * @see includeStaticTypoScriptSources()
923 protected function prependStaticExtra($subrow)
925 // the identifier can be "43" if coming from "static template" extension or a path like "cssstyledcontent/static/"
926 $identifier = $subrow['uid'];
927 $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.'][$identifier] ?? null
;
928 $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.'][$identifier] ?? null
;
929 // 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
930 if (in_array($identifier, $GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'], true
)) {
931 $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.']['defaultContentRendering'];
932 $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.']['defaultContentRendering'];
938 * Creating versioning overlay of a sys_template record.
940 * @param array $row Row to overlay (passed by reference)
942 protected function versionOL(&$row)
944 if ($this->context
->getPropertyFromAspect('workspace', 'isOffline')) {
945 $pageRepository = GeneralUtility
::makeInstance(PageRepository
::class, $this->context
);
946 $pageRepository->versionOL('sys_template', $row);
950 /*******************************************************************
952 * Parsing TypoScript code text from Template Records into PHP array
954 *******************************************************************/
956 * Generates the configuration array by replacing constants and parsing the whole thing.
957 * Depends on $this->config and $this->constants to be set prior to this! (done by processTemplate/runThroughTemplates)
959 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
962 public function generateConfig()
964 // Add default TS for all code types
965 $this->addDefaultTypoScript();
967 // Parse the TypoScript code text for include-instructions!
968 $this->processIncludes();
969 // These vars are also set later on...
970 $this->setup
['sitetitle'] = $this->sitetitle
;
971 // ****************************
972 // Parse TypoScript Constants
973 // ****************************
974 // Initialize parser and match-condition classes:
975 /** @var Parser\TypoScriptParser $constants */
976 $constants = GeneralUtility
::makeInstance(Parser\TypoScriptParser
::class);
977 $constants->breakPointLN
= (int)$this->ext_constants_BRP
;
978 /** @var ConditionMatcher $matchObj */
979 $matchObj = GeneralUtility
::makeInstance(ConditionMatcher
::class);
980 $matchObj->setSimulateMatchConditions($this->matchAlternative
);
981 $matchObj->setSimulateMatchResult((bool
)$this->matchAll
);
982 // Traverse constants text fields and parse them
983 foreach ($this->constants
as $str) {
984 $constants->parse($str, $matchObj);
986 // Read out parse errors if any
987 $this->parserErrors
['constants'] = $constants->errors
;
988 // 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)
989 $this->flatSetup
= ArrayUtility
::flatten($constants->setup
, '', true
);
990 // ***********************************************
991 // Parse TypoScript Setup (here called "config")
992 // ***********************************************
993 // Initialize parser and match-condition classes:
994 /** @var Parser\TypoScriptParser $config */
995 $config = GeneralUtility
::makeInstance(Parser\TypoScriptParser
::class);
996 $config->breakPointLN
= (int)$this->ext_config_BRP
;
997 $config->regLinenumbers
= $this->ext_regLinenumbers
;
998 $config->regComments
= $this->ext_regComments
;
999 $config->setup
= $this->setup
;
1000 // Transfer information about conditions found in "Constants" and which of them returned TRUE.
1001 $config->sections
= $constants->sections
;
1002 $config->sectionsMatch
= $constants->sectionsMatch
;
1003 // Traverse setup text fields and concatenate them into one, single string separated by a [GLOBAL] condition
1005 foreach ($this->config
as $str) {
1010 // Substitute constants in the Setup code:
1011 if ($this->tt_track
) {
1012 $this->getTimeTracker()->push('Substitute Constants (' . count($this->flatSetup
) . ')');
1014 $all = $this->substituteConstants($all);
1015 if ($this->tt_track
) {
1016 $this->getTimeTracker()->pull();
1019 // Searching for possible unsubstituted constants left (only for information)
1020 if ($this->verbose
) {
1021 if (preg_match_all('/\\{\\$.[^}]*\\}/', $all, $constantList) > 0) {
1022 if ($this->tt_track
) {
1023 $this->getTimeTracker()->setTSlogMessage(implode(', ', $constantList[0]) . ': Constants may remain un-substituted!!', 2);
1028 // Logging the textual size of the TypoScript Setup field text with all constants substituted:
1029 if ($this->tt_track
) {
1030 $this->getTimeTracker()->setTSlogMessage('TypoScript template size as textfile: ' . strlen($all) . ' bytes');
1032 // Finally parse the Setup field TypoScript code (where constants are now substituted)
1033 $config->parse($all, $matchObj);
1034 // Read out parse errors if any
1035 $this->parserErrors
['config'] = $config->errors
;
1036 // Transfer the TypoScript array from the parser object to the internal $this->setup array:
1037 $this->setup
= $config->setup
;
1038 // Do the same for the constants
1039 $this->setup_constants
= $constants->setup
;
1040 // ****************************************************************
1041 // Final processing of the $this->setup TypoScript Template array
1042 // Basically: This is unsetting/setting of certain reserved keys.
1043 // ****************************************************************
1044 // 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!
1045 unset($this->setup
['sitetitle']);
1046 unset($this->setup
['sitetitle.']);
1047 $this->setup
['sitetitle'] = $this->sitetitle
;
1048 // Unsetting some vars...
1049 unset($this->setup
['types.']);
1050 unset($this->setup
['types']);
1051 if (is_array($this->setup
)) {
1052 foreach ($this->setup
as $key => $value) {
1053 if ($value === 'PAGE') {
1054 // Set the typeNum of the current page object:
1055 if (isset($this->setup
[$key . '.']['typeNum'])) {
1056 $typeNum = $this->setup
[$key . '.']['typeNum'];
1057 $this->setup
['types.'][$typeNum] = $key;
1058 } elseif (!isset($this->setup
['types.'][0]) ||
!$this->setup
['types.'][0]) {
1059 $this->setup
['types.'][0] = $key;
1064 unset($this->setup
['temp.']);
1066 // Storing the conditions found/matched information:
1067 $this->sections
= $config->sections
;
1068 $this->sectionsMatch
= $config->sectionsMatch
;
1072 * Searching TypoScript code text (for constants and config (Setup))
1073 * for include instructions and does the inclusion of external TypoScript files
1076 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
1077 * @see generateConfig()
1079 protected function processIncludes()
1081 if ($this->processIncludesHasBeenRun
) {
1085 $paths = $this->templateIncludePaths
;
1087 foreach ($this->constants
as &$value) {
1088 $includeData = Parser\TypoScriptParser
::checkIncludeLines($value, 1, true
, array_shift($paths));
1089 $files = array_merge($files, $includeData['files']);
1090 $value = $includeData['typoscript'];
1093 $paths = $this->templateIncludePaths
;
1094 foreach ($this->config
as &$value) {
1095 $includeData = Parser\TypoScriptParser
::checkIncludeLines($value, 1, true
, array_shift($paths));
1096 $files = array_merge($files, $includeData['files']);
1097 $value = $includeData['typoscript'];
1101 if (!empty($files)) {
1102 $files = array_unique($files);
1103 foreach ($files as $file) {
1104 $this->rowSum
[] = [$file, filemtime($file)];
1108 $this->processIncludesHasBeenRun
= true
;
1112 * Substitutes the constants from $this->flatSetup in the text string $all
1114 * @param string $all TypoScript code text string
1115 * @return string The processed string with all constants found in $this->flatSetup as key/value pairs substituted.
1116 * @see generateConfig()
1118 protected function substituteConstants($all)
1120 if ($this->tt_track
) {
1121 $this->getTimeTracker()->setTSlogMessage('Constants to substitute: ' . count($this->flatSetup
));
1124 // Recursive substitution of constants (up to 10 nested levels)
1125 for ($i = 0; $i < 10 && !$noChange; $i++
) {
1127 $all = preg_replace_callback('/\\{\\$(.[^}]*)\\}/', [$this, 'substituteConstantsCallBack'], $all);
1128 if ($old_all == $all) {
1136 * Call back method for preg_replace_callback in substituteConstants
1138 * @param array $matches Regular expression matches
1139 * @return string Replacement
1140 * @see substituteConstants()
1143 public function substituteConstantsCallBack($matches)
1145 // Replace {$CONST} if found in $this->flatSetup, else leave unchanged
1146 return isset($this->flatSetup
[$matches[1]]) && !is_array($this->flatSetup
[$matches[1]]) ?
$this->flatSetup
[$matches[1]] : $matches[0];
1149 /*******************************************************************
1151 * Various API functions, used from elsewhere in the frontend classes
1153 *******************************************************************/
1156 * Returns the level of the given page in the rootline - Multiple pages can be given by separating the UIDs by comma.
1158 * @param string $list A list of UIDs for which the rootline-level should get returned
1159 * @return int The level in the rootline. If more than one page was given the lowest level will get returned.
1161 public function getRootlineLevel($list)
1164 foreach ($this->rootLine
as $page) {
1165 if (GeneralUtility
::inList($list, $page['uid'])) {
1174 * Returns the page ID of the rootlevel
1178 public function getRootId(): int
1180 return (int)$this->rootId
;
1183 /*******************************************************************
1185 * Functions for creating links
1187 *******************************************************************/
1190 * Adds the TypoScript from the global array.
1191 * The class property isDefaultTypoScriptAdded ensures
1192 * that the adding only happens once.
1194 * @see isDefaultTypoScriptAdded
1196 protected function addDefaultTypoScript()
1198 // Add default TS for all code types, if not done already
1199 if (!$this->isDefaultTypoScriptAdded
) {
1200 // adding default setup and constants
1201 // defaultTypoScript_setup is *very* unlikely to be empty
1202 // the count of elements in ->constants, ->config and ->templateIncludePaths have to be in sync
1203 array_unshift($this->constants
, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants']);
1204 array_unshift($this->config
, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup']);
1205 array_unshift($this->templateIncludePaths
, '');
1206 // prepare a proper entry to hierachyInfo (used by TemplateAnalyzer in BE)
1207 $rootTemplateId = $this->hierarchyInfo
[count($this->hierarchyInfo
) - 1]['templateID'] ?? null
;
1208 $defaultTemplateInfo = [
1212 'templateID' => '_defaultTypoScript_',
1213 'templateParent' => $rootTemplateId,
1214 'title' => 'SYS:TYPO3_CONF_VARS:FE:defaultTypoScript',
1215 'uid' => '_defaultTypoScript_',
1217 'configLines' => substr_count((string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup'], LF
) +
1
1219 // push info to information arrays used in BE by TemplateTools (Analyzer)
1220 array_unshift($this->clearList_const
, $defaultTemplateInfo['uid']);
1221 array_unshift($this->clearList_setup
, $defaultTemplateInfo['uid']);
1222 array_unshift($this->hierarchyInfo
, $defaultTemplateInfo);
1223 $this->isDefaultTypoScriptAdded
= true
;
1228 * @return TypoScriptFrontendController
1230 protected function getTypoScriptFrontendController()
1232 return $this->frontendController ??
$GLOBALS['TSFE'];
1236 * @return TimeTracker
1238 protected function getTimeTracker()
1240 return GeneralUtility
::makeInstance(TimeTracker
::class);
1244 * Returns data stored for the hash string in the cache "cache_hash"
1245 * used to store the parsed TypoScript template structures.
1247 * @param string $identifier The hash-string which was used to store the data value
1248 * @return mixed The data from the cache
1250 protected function getCacheEntry($identifier)
1252 return GeneralUtility
::makeInstance(CacheManager
::class)->getCache('hash')->get($identifier);
1256 * Stores $data in the 'hash' cache with the hash key $identifier
1258 * @param string $identifier 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
1259 * @param mixed $data The data to store
1260 * @param string $tag Is just a textual identification in order to inform about the content
1262 protected function setCacheEntry($identifier, $data, $tag)
1264 GeneralUtility
::makeInstance(CacheManager
::class)->getCache('hash')->set($identifier, $data, ['ident_' . $tag], 0);