TemplateService::getTypoScriptFrontendController()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the TYPO3 CMS project.
5
 *
6
 * It is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License, either version 2
8
 * of the License, or any later version.
9
 *
10
 * For the full copyright and license information, please read the
11
 * LICENSE.txt file that was distributed with this source code.
12
 *
13
 * The TYPO3 project - inspiring people to share!
14
 */
15
16
namespace TYPO3\CMS\Core\TypoScript;
17
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\Domain\Repository\PageRepository;
26
use TYPO3\CMS\Core\Exception\SiteNotFoundException;
27
use TYPO3\CMS\Core\Package\PackageManager;
28
use TYPO3\CMS\Core\Site\Entity\Site;
29
use TYPO3\CMS\Core\Site\SiteFinder;
30
use TYPO3\CMS\Core\TimeTracker\TimeTracker;
31
use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
32
use TYPO3\CMS\Core\Utility\ArrayUtility;
33
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
34
use TYPO3\CMS\Core\Utility\GeneralUtility;
35
use TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher;
36
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
37
38
/**
39
 * Template object that is responsible for generating the TypoScript template based on template records.
40
 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
41
 * @see \TYPO3\CMS\Core\Configuration\TypoScript\ConditionMatching\AbstractConditionMatcher
42
 */
43
class TemplateService
44
{
45
    /**
46
     * option to enable logging, time-tracking (FE-only)
47
     * usually, this is only done when
48
     *  - in FE a BE_USER is logged-in
49
     *  - in BE when the BE_USER needs information about the template (TypoScript module)
50
     * @var bool
51
     */
52
    protected $verbose = false;
53
54
    /**
55
     * If set, the global tt-timeobject is used to log the performance.
56
     *
57
     * @var bool
58
     */
59
    public $tt_track = true;
60
61
    /**
62
     * This array is passed on to matchObj by generateConfig().
63
     * If it holds elements, they are used for matching instead. See comment at the match-class.
64
     * Used for backend modules only. Never frontend!
65
     *
66
     * @var array
67
     * @internal
68
     */
69
    public $matchAlternative = [];
70
71
    /**
72
     * If set, the match-class matches everything! Used for backend modules only. Never frontend!
73
     *
74
     * @var bool
75
     */
76
    protected $matchAll = false;
77
78
    /**
79
     * @deprecated Unused since v11, will be removed in v12
80
     */
81
    public $ext_constants_BRP = 0;
82
83
    /**
84
     * @deprecated Unused since v11, will be removed in v12
85
     */
86
    public $ext_config_BRP = 0;
87
88
    /**
89
     * @var bool
90
     */
91
    public $ext_regLinenumbers = false;
92
93
    /**
94
     * @var bool
95
     */
96
    public $ext_regComments = false;
97
98
    /**
99
     * Set if preview of some kind is enabled.
100
     *
101
     * @var bool
102
     */
103
    protected $simulationHiddenOrTime = false;
104
105
    /**
106
     * Set, if the TypoScript template structure is loaded and OK, see ->start()
107
     *
108
     * @var bool
109
     */
110
    public $loaded = false;
111
112
    /**
113
     * @var array Contains TypoScript setup part after parsing
114
     */
115
    public $setup = [];
116
117
    /**
118
     * @var array
119
     */
120
    public $flatSetup = [];
121
122
    /**
123
     * For fetching TypoScript code from template hierarchy before parsing it.
124
     * Each array contains code field values from template records/files:
125
     * Setup field
126
     *
127
     * @var array
128
     */
129
    public $config = [];
130
131
    /**
132
     * Constant field
133
     *
134
     * @var array
135
     */
136
    public $constants = [];
137
138
    /**
139
     * Holds the include paths of the templates (empty if from database)
140
     *
141
     * @var array
142
     */
143
    protected $templateIncludePaths = [];
144
145
    /**
146
     * For Template Analyzer in backend
147
     *
148
     * @var array
149
     */
150
    public $hierarchyInfo = [];
151
152
    /**
153
     * For Template Analyzer in backend (setup content only)
154
     *
155
     * @var array
156
     */
157
    protected $hierarchyInfoToRoot = [];
158
159
    /**
160
     * The Page UID of the root page
161
     *
162
     * @var int
163
     */
164
    protected $rootId;
165
166
    /**
167
     * The rootline from current page to the root page
168
     *
169
     * @var array
170
     */
171
    public $rootLine;
172
173
    /**
174
     * Rootline all the way to the root. Set but runThroughTemplates
175
     *
176
     * @var array
177
     */
178
    protected $absoluteRootLine;
179
180
    /**
181
     * Array of arrays with title/uid of templates in hierarchy
182
     *
183
     * @var array
184
     */
185
    protected $rowSum;
186
187
    /**
188
     * Tracking all conditions found during parsing of TypoScript. Used for the "all" key in currentPageData
189
     *
190
     * @var array|null
191
     */
192
    public $sections;
193
194
    /**
195
     * Tracking all matching conditions found
196
     *
197
     * @var array
198
     */
199
    protected $sectionsMatch;
200
201
    /**
202
     * Used by Backend only (Typoscript Template Analyzer)
203
     * @var string[]
204
     */
205
    public $clearList_const = [];
206
207
    /**
208
     * Used by Backend only (Typoscript Template Analyzer)
209
     *
210
     * @var array
211
     */
212
    public $clearList_setup = [];
213
214
    /**
215
     * @var array
216
     */
217
    public $parserErrors = [];
218
219
    /**
220
     * @var array
221
     */
222
    public $setup_constants = [];
223
224
    /**
225
     * Indicator that extension statics are processed.
226
     *
227
     * These files are considered if either a root template
228
     * has been processed or the $processExtensionStatics
229
     * property has been set to TRUE.
230
     *
231
     * @var bool
232
     */
233
    protected $extensionStaticsProcessed = false;
234
235
    /**
236
     * Trigger value, to ensure that extension statics are processed.
237
     *
238
     * @var bool
239
     */
240
    protected $processExtensionStatics = false;
241
242
    /**
243
     * Set to TRUE after the default TypoScript was added during parsing.
244
     * This prevents double inclusion of the same TypoScript code.
245
     *
246
     * @see addDefaultTypoScript()
247
     * @var bool
248
     */
249
    protected $isDefaultTypoScriptAdded = false;
250
251
    /**
252
     * Set to TRUE after $this->config and $this->constants have processed all <INCLUDE_TYPOSCRIPT:> instructions.
253
     *
254
     * This prevents double processing of INCLUDES.
255
     *
256
     * @see processIncludes()
257
     * @var bool
258
     */
259
    protected $processIncludesHasBeenRun = false;
260
261
    /**
262
     * Contains the restrictions about deleted, and some frontend related topics
263
     * @var AbstractRestrictionContainer
264
     */
265
    protected $queryBuilderRestrictions;
266
267
    /**
268
     * @var Context
269
     */
270
    protected $context;
271
272
    /**
273
     * @var PackageManager
274
     */
275
    protected $packageManager;
276
277
    /**
278
     * @var TypoScriptFrontendController|null
279
     */
280
    protected $frontendController;
281
282
    /**
283
     * @param Context|null $context
284
     * @param PackageManager|null $packageManager
285
     * @param TypoScriptFrontendController|null $frontendController
286
     */
287
    public function __construct(Context $context = null, PackageManager $packageManager = null, TypoScriptFrontendController $frontendController = null)
288
    {
289
        $this->context = $context ?? GeneralUtility::makeInstance(Context::class);
290
        $this->packageManager = $packageManager ?? GeneralUtility::makeInstance(PackageManager::class);
291
        $this->frontendController = $frontendController;
292
        $this->initializeDatabaseQueryRestrictions();
293
        if ($this->context->getPropertyFromAspect('visibility', 'includeHiddenContent', false) || $GLOBALS['SIM_ACCESS_TIME'] !== $GLOBALS['ACCESS_TIME']) {
294
            // Set the simulation flag, if simulation is detected!
295
            $this->simulationHiddenOrTime = true;
296
        }
297
        $this->tt_track = $this->verbose = (bool)$this->context->getPropertyFromAspect('backend.user', 'isLoggedIn', false);
298
    }
299
300
    /**
301
     * @return bool
302
     */
303
    public function getProcessExtensionStatics()
304
    {
305
        return $this->processExtensionStatics;
306
    }
307
308
    /**
309
     * @param bool $processExtensionStatics
310
     */
311
    public function setProcessExtensionStatics($processExtensionStatics)
312
    {
313
        $this->processExtensionStatics = (bool)$processExtensionStatics;
314
    }
315
316
    /**
317
     * sets the verbose parameter
318
     * @param bool $verbose
319
     */
320
    public function setVerbose($verbose)
321
    {
322
        $this->verbose = (bool)$verbose;
323
    }
324
325
    /**
326
     * Set up the query builder restrictions, optionally include hidden records
327
     */
328
    protected function initializeDatabaseQueryRestrictions()
329
    {
330
        $this->queryBuilderRestrictions = GeneralUtility::makeInstance(DefaultRestrictionContainer::class);
331
332
        if ($this->context->getPropertyFromAspect('visibility', 'includeHiddenContent', false)) {
333
            $this->queryBuilderRestrictions->removeByType(HiddenRestriction::class);
334
        }
335
    }
336
337
    /**
338
     * Fetches the "currentPageData" array from cache
339
     *
340
     * NOTE about currentPageData:
341
     * It holds information about the TypoScript conditions along with the list
342
     * of template uid's which is used on the page. In the getFromCache() function
343
     * in TSFE, currentPageData is used to evaluate if there is a template and
344
     * if the matching conditions are alright. Unfortunately this does not take
345
     * into account if the templates in the rowSum of currentPageData has
346
     * changed composition, eg. due to hidden fields or start/end time. So if a
347
     * template is hidden or times out, it'll not be discovered unless the page
348
     * is regenerated - at least the this->start function must be called,
349
     * because this will make a new portion of data in currentPageData string.
350
     *
351
     * @param int $pageId
352
     * @param string $mountPointValue
353
     * @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
354
     * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
355
     * @internal
356
     */
357
    public function getCurrentPageData(int $pageId, string $mountPointValue)
358
    {
359
        return GeneralUtility::makeInstance(CacheManager::class)->getCache('pagesection')->get($pageId . '_' . GeneralUtility::md5int($mountPointValue));
360
    }
361
362
    /**
363
     * Fetches data about which TypoScript-matches there are at this page. Then it performs a matchingtest.
364
     *
365
     * @param array $cc An array with three keys, "all", "rowSum" and "rootLine" - all coming from the "currentPageData" array
366
     * @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.
367
     */
368
    public function matching($cc)
369
    {
370
        if (is_array($cc['all'])) {
371
            /** @var ConditionMatcher $matchObj */
372
            $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
373
            $matchObj->setRootline((array)($cc['rootLine'] ?? []));
374
            $sectionsMatch = [];
375
            foreach ($cc['all'] as $key => $pre) {
376
                if ($matchObj->match($pre)) {
377
                    $sectionsMatch[$key] = $pre;
378
                }
379
            }
380
            $cc['match'] = $sectionsMatch;
381
        }
382
        return $cc;
383
    }
384
385
    /**
386
     * This is all about fetching the right TypoScript template structure. If it's not cached then it must be generated and cached!
387
     * 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.
388
     * Sets $this->setup to the parsed TypoScript template array
389
     *
390
     * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
391
     * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getConfigArray()
392
     */
393
    public function start($theRootLine)
394
    {
395
        $cc = [];
396
        if (is_array($theRootLine)) {
0 ignored issues
show
introduced by
The condition is_array($theRootLine) is always true.
Loading history...
397
            $constantsData = [];
398
            $setupData = [];
399
            $cacheIdentifier = '';
400
            // Flag that indicates that the existing data in cache_pagesection
401
            // could be used (this is the case if $TSFE->all is set, and the
402
            // rowSum still matches). Based on this we decide if cache_pagesection
403
            // needs to be updated...
404
            $isCached = false;
405
            $this->runThroughTemplates($theRootLine);
406
            if ($this->getTypoScriptFrontendController()->all) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->getTypoScriptFrontendController()->all of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
407
                $cc = $this->getTypoScriptFrontendController()->all;
408
                // The two rowSums must NOT be different from each other - which they will be if start/endtime or hidden has changed!
409
                if (serialize($this->rowSum) !== serialize($cc['rowSum'])) {
410
                    $cc = [];
411
                } else {
412
                    // If $TSFE->all contains valid data, we don't need to update cache_pagesection (because this data was fetched from there already)
413
                    if (serialize($this->rootLine) === serialize($cc['rootLine'])) {
414
                        $isCached = true;
415
                    }
416
                    // 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)...
417
                    unset($cc['rootLine']);
418
                }
419
            }
420
            // This is about getting the hash string which is used to fetch the cached TypoScript template.
421
            // If there was some cached currentPageData ($cc) then that's good (it gives us the hash).
422
            if (!empty($cc)) {
423
                // If currentPageData was actually there, we match the result (if this wasn't done already in $TSFE->getFromCache()...)
424
                if (!$cc['match']) {
425
                    // @todo check if this can ever be the case - otherwise remove
426
                    $cc = $this->matching($cc);
427
                    ksort($cc);
428
                }
429
                $cacheIdentifier = md5(serialize($cc));
430
            } else {
431
                // 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.
432
                $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
433
                $result = $this->getCacheEntry($rowSumHash);
434
                if (is_array($result)) {
435
                    $cc['all'] = $result;
436
                    $cc['rowSum'] = $this->rowSum;
437
                    $cc = $this->matching($cc);
438
                    ksort($cc);
439
                    $cacheIdentifier = md5(serialize($cc));
440
                }
441
            }
442
            if ($cacheIdentifier) {
443
                // Get TypoScript setup array
444
                $cachedData = $this->getCacheEntry($cacheIdentifier);
445
                if (is_array($cachedData)) {
446
                    $constantsData = $cachedData['constants'];
447
                    $setupData = $cachedData['setup'];
448
                }
449
            }
450
            if (!empty($setupData) && !$this->context->getPropertyFromAspect('typoscript', 'forcedTemplateParsing')) {
451
                // TypoScript constants + setup are found in the cache
452
                $this->setup_constants = $constantsData;
453
                $this->setup = $setupData;
454
                if ($this->tt_track) {
455
                    $this->getTimeTracker()->setTSlogMessage('Using cached TS template data');
456
                }
457
            } else {
458
                if ($this->tt_track) {
459
                    $this->getTimeTracker()->setTSlogMessage('Not using any cached TS data');
460
                }
461
462
                // Make configuration
463
                $this->generateConfig();
464
                // This stores the template hash thing
465
                $cc = [];
466
                // All sections in the template at this point is found
467
                $cc['all'] = $this->sections;
468
                // The line of templates is collected
469
                $cc['rowSum'] = $this->rowSum;
470
                $cc = $this->matching($cc);
471
                ksort($cc);
472
                $cacheIdentifier = md5(serialize($cc));
473
                // This stores the data.
474
                $this->setCacheEntry($cacheIdentifier, ['constants' => $this->setup_constants, 'setup' => $this->setup], 'TS_TEMPLATE');
475
                if ($this->tt_track) {
476
                    $this->getTimeTracker()->setTSlogMessage('TS template size, serialized: ' . strlen(serialize($this->setup)) . ' bytes');
477
                }
478
                $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
479
                $this->setCacheEntry($rowSumHash, $cc['all'], 'TMPL_CONDITIONS_ALL');
480
            }
481
            // Add rootLine
482
            $cc['rootLine'] = $this->rootLine;
483
            ksort($cc);
484
            // Make global and save
485
            $this->getTypoScriptFrontendController()->all = $cc;
486
            // Matching must be executed for every request, so this must never be part of the pagesection cache!
487
            unset($cc['match']);
488
            if (!$isCached && !$this->simulationHiddenOrTime && !$this->getTypoScriptFrontendController()->no_cache) {
489
                // Only save the data if we're not simulating by hidden/starttime/endtime
490
                $mpvarHash = GeneralUtility::md5int($this->getTypoScriptFrontendController()->MP);
491
                /** @var \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface $pageSectionCache */
492
                $pageSectionCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('pagesection');
493
                $pageSectionCache->set((int)$this->getTypoScriptFrontendController()->id . '_' . $mpvarHash, $cc, [
494
                    'pageId_' . (int)$this->getTypoScriptFrontendController()->id,
495
                    'mpvarHash_' . $mpvarHash
496
                ]);
497
            }
498
            // If everything OK.
499
            if ($this->rootId && $this->rootLine && $this->setup) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->rootLine of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
500
                $this->loaded = true;
501
            }
502
        }
503
    }
504
505
    /*******************************************************************
506
     *
507
     * Fetching TypoScript code text for the Template Hierarchy
508
     *
509
     *******************************************************************/
510
    /**
511
     * 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.
512
     * Resets and affects internal variables like $this->constants, $this->config and $this->rowSum
513
     * 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
514
     *
515
     * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
516
     * @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)
517
     * @see start()
518
     */
519
    public function runThroughTemplates($theRootLine, $start_template_uid = 0)
520
    {
521
        $this->constants = [];
522
        $this->config = [];
523
        $this->rowSum = [];
524
        $this->hierarchyInfoToRoot = [];
525
        $this->absoluteRootLine = $theRootLine;
526
        $this->isDefaultTypoScriptAdded = false;
527
528
        reset($this->absoluteRootLine);
529
        $c = count($this->absoluteRootLine);
530
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_template');
531
        for ($a = 0; $a < $c; $a++) {
532
            $where = [
533
                $queryBuilder->expr()->eq(
534
                    'pid',
535
                    $queryBuilder->createNamedParameter($this->absoluteRootLine[$a]['uid'], \PDO::PARAM_INT)
536
                )
537
            ];
538
            // If first loop AND there is set an alternative template uid, use that
539
            if ($a === $c - 1 && $start_template_uid) {
540
                $where[] = $queryBuilder->expr()->eq(
541
                    'uid',
542
                    $queryBuilder->createNamedParameter($start_template_uid, \PDO::PARAM_INT)
543
                );
544
            }
545
            $queryBuilder->setRestrictions($this->queryBuilderRestrictions);
546
            $queryResult = $queryBuilder
547
                ->select('*')
548
                ->from('sys_template')
549
                ->where(...$where)
550
                ->orderBy('root', 'DESC')
551
                ->addOrderBy('sorting')
552
                ->setMaxResults(1)
553
                ->execute();
554
            if ($row = $queryResult->fetch()) {
555
                $this->versionOL($row);
556
                if (is_array($row)) {
557
                    $this->processTemplate($row, 'sys_' . $row['uid'], $this->absoluteRootLine[$a]['uid'], 'sys_' . $row['uid']);
558
                }
559
            }
560
            $this->rootLine[] = $this->absoluteRootLine[$a];
561
        }
562
563
        // Hook into the default TypoScript to add custom typoscript logic
564
        $hookParameters = [
565
            'extensionStaticsProcessed' => &$this->extensionStaticsProcessed,
566
            'isDefaultTypoScriptAdded'  => &$this->isDefaultTypoScriptAdded,
567
            'absoluteRootLine' => &$this->absoluteRootLine,
568
            'rootLine'         => &$this->rootLine,
569
            'startTemplateUid' => $start_template_uid,
570
            'rowSum'           => &$this->rowSum,
571
        ];
572
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['Core/TypoScript/TemplateService']['runThroughTemplatesPostProcessing'] ?? [] as $listener) {
573
            GeneralUtility::callUserFunction($listener, $hookParameters, $this);
574
        }
575
576
        // Process extension static files if not done yet, but explicitly requested
577
        if (!$this->extensionStaticsProcessed && $this->processExtensionStatics) {
578
            $this->addExtensionStatics('sys_0', 'sys_0', 0);
0 ignored issues
show
Bug introduced by
The method addExtensionStatics() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

578
            $this->/** @scrutinizer ignore-call */ 
579
                   addExtensionStatics('sys_0', 'sys_0', 0);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
579
        }
580
581
        // Add the global default TypoScript from the TYPO3_CONF_VARS
582
        $this->addDefaultTypoScript();
583
584
        $this->processIncludes();
585
    }
586
587
    /**
588
     * Checks if the template ($row) has some included templates and after including them it fills the arrays with the setup
589
     * Builds up $this->rowSum
590
     *
591
     * @param array $row A full TypoScript template record (sys_template/forged "dummy" record made from static template file)
592
     * @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.
593
     * @param int $pid The PID of the input template record
594
     * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
595
     * @param string $templateParent Parent template id (during recursive call); Same syntax as $idList ids, eg. "sys_123
596
     * @param string $includePath Specifies the path from which the template was included (used with static_includes)
597
     * @see runThroughTemplates()
598
     */
599
    public function processTemplate($row, $idList, $pid, $templateID = '', $templateParent = '', $includePath = '')
600
    {
601
        // Adding basic template record information to rowSum array
602
        $this->rowSum[] = [$row['uid'] ?? null, $row['title'] ?? null, $row['tstamp'] ?? null];
603
        // Processing "Clear"-flags
604
        $clConst = 0;
605
        $clConf = 0;
606
        if (!empty($row['clear'])) {
607
            $clConst = $row['clear'] & 1;
608
            $clConf = $row['clear'] & 2;
609
            if ($clConst) {
610
                // Keep amount of items to stay in sync with $this->templateIncludePaths so processIncludes() does not break
611
                foreach ($this->constants as &$constantConfiguration) {
612
                    $constantConfiguration = '';
613
                }
614
                unset($constantConfiguration);
615
                $this->clearList_const = [];
616
            }
617
            if ($clConf) {
618
                // Keep amount of items to stay in sync with $this->templateIncludePaths so processIncludes() does not break
619
                foreach ($this->config as &$configConfiguration) {
620
                    $configConfiguration = '';
621
                }
622
                unset($configConfiguration);
623
                $this->hierarchyInfoToRoot = [];
624
                $this->clearList_setup = [];
625
            }
626
        }
627
        // Include files (from extensions) (#1/2)
628
        // NORMAL inclusion, The EXACT same code is found below the basedOn inclusion!!!
629
        if (!isset($row['includeStaticAfterBasedOn']) || !$row['includeStaticAfterBasedOn']) {
630
            $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
631
        }
632
        // Include "Based On" sys_templates:
633
        // 'basedOn' is a list of templates to include
634
        if (trim($row['basedOn'] ?? '')) {
635
            // Normal Operation, which is to include the "based-on" sys_templates,
636
            // if they are not already included, and maintaining the sorting of the templates
637
            $basedOnIds = GeneralUtility::intExplode(',', $row['basedOn'], true);
638
            // skip template if it's already included
639
            foreach ($basedOnIds as $key => $basedOnId) {
640
                if (GeneralUtility::inList($idList, 'sys_' . $basedOnId)) {
641
                    unset($basedOnIds[$key]);
642
                }
643
            }
644
            if (!empty($basedOnIds)) {
645
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_template');
646
                $queryBuilder->setRestrictions($this->queryBuilderRestrictions);
647
                $queryResult = $queryBuilder
648
                    ->select('*')
649
                    ->from('sys_template')
650
                    ->where(
651
                        $queryBuilder->expr()->in(
652
                            'uid',
653
                            $queryBuilder->createNamedParameter($basedOnIds, Connection::PARAM_INT_ARRAY)
654
                        )
655
                    )
656
                    ->execute();
657
                // make it an associative array with the UID as key
658
                $subTemplates = [];
659
                while ($rowItem = $queryResult->fetch()) {
660
                    $subTemplates[(int)$rowItem['uid']] = $rowItem;
661
                }
662
                // Traversing list again to ensure the sorting of the templates
663
                foreach ($basedOnIds as $id) {
664
                    if (is_array($subTemplates[$id])) {
665
                        $this->versionOL($subTemplates[$id]);
666
                        $this->processTemplate($subTemplates[$id], $idList . ',sys_' . $id, $pid, 'sys_' . $id, $templateID);
667
                    }
668
                }
669
            }
670
        }
671
        // Include files (from extensions) (#2/2)
672
        if (!empty($row['includeStaticAfterBasedOn'])) {
673
            $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
674
        }
675
        // Creating hierarchy information; Used by backend analysis tools
676
        $this->hierarchyInfo[] = ($this->hierarchyInfoToRoot[] = [
677
            'root' => trim($row['root'] ?? ''),
678
            'clConst' => $clConst,
679
            'clConf' => $clConf,
680
            'templateID' => $templateID,
681
            'templateParent' => $templateParent,
682
            'title' => $row['title'],
683
            'uid' => $row['uid'],
684
            'pid' => $row['pid'] ?? null,
685
            'configLines' => substr_count($row['config'], LF) + 1
686
        ]);
687
        // Adding the content of the fields constants (Constants) and config (Setup)
688
        $this->constants[] = $row['constants'];
689
        $this->config[] = $row['config'];
690
        $this->templateIncludePaths[] = $includePath;
691
        // For backend analysis (Template Analyzer) provide the order of added constants/config template IDs
692
        $this->clearList_const[] = $templateID;
693
        $this->clearList_setup[] = $templateID;
694
        // If the template record is a Rootlevel record, set the flag and clear the template rootLine (so it starts over from this point)
695
        if (trim($row['root'] ?? null)) {
0 ignored issues
show
Bug introduced by
It seems like $row['root'] ?? null can also be of type null; however, parameter $string of trim() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

695
        if (trim(/** @scrutinizer ignore-type */ $row['root'] ?? null)) {
Loading history...
696
            $this->rootId = $pid;
697
            $this->rootLine = [];
698
        }
699
    }
700
701
    /**
702
     * This function can be used to update the data of the current rootLine
703
     * e.g. when a different language is used.
704
     *
705
     * This function must not be used if there are different pages in the
706
     * rootline as before!
707
     *
708
     * @param array $fullRootLine Array containing the FULL rootline (up to the TYPO3 root)
709
     * @throws \RuntimeException If the given $fullRootLine does not contain all pages that are in the current template rootline
710
     */
711
    public function updateRootlineData($fullRootLine)
712
    {
713
        if (!is_array($this->rootLine) || empty($this->rootLine)) {
0 ignored issues
show
introduced by
The condition is_array($this->rootLine) is always true.
Loading history...
714
            return;
715
        }
716
717
        $fullRootLineByUid = [];
718
        foreach ($fullRootLine as $rootLineData) {
719
            $fullRootLineByUid[$rootLineData['uid']] = $rootLineData;
720
        }
721
722
        foreach ($this->rootLine as $level => $dataArray) {
723
            $currentUid = $dataArray['uid'];
724
725
            if (!array_key_exists($currentUid, $fullRootLineByUid)) {
726
                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);
727
            }
728
729
            $this->rootLine[$level] = $fullRootLineByUid[$currentUid];
730
        }
731
    }
732
733
    /**
734
     * Includes static template files (from extensions) for the input template record row.
735
     *
736
     * @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.
737
     * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
738
     * @param int $pid The PID of the input template record
739
     * @param array $row A full TypoScript template record
740
     * @see processTemplate()
741
     * @internal
742
     */
743
    public function includeStaticTypoScriptSources($idList, $templateID, $pid, $row)
744
    {
745
        // Call function for link rendering:
746
        $_params = [
747
            'idList' => &$idList,
748
            'templateId' => &$templateID,
749
            'pid' => &$pid,
750
            'row' => &$row
751
        ];
752
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSources'] ?? [] as $_funcRef) {
753
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
754
        }
755
        // If "Include before all static templates if root-flag is set" is set:
756
        $staticFileMode = $row['static_file_mode'] ?? null;
757
        if ($staticFileMode == 3 && strpos($templateID, 'sys_') === 0 && $row['root']) {
758
            $this->addExtensionStatics($idList, $templateID, $pid);
759
        }
760
        // Static Template Files (Text files from extensions): include_static_file is a list of static files to include (from extensions)
761
        if (trim($row['include_static_file'] ?? '')) {
762
            $include_static_fileArr = GeneralUtility::trimExplode(',', $row['include_static_file'], true);
763
            // Traversing list
764
            foreach ($include_static_fileArr as $ISF_file) {
765
                if (strpos($ISF_file, 'EXT:') === 0) {
766
                    [$ISF_extKey, $ISF_localPath] = explode('/', substr($ISF_file, 4), 2);
767
                    if ((string)$ISF_extKey !== '' && ExtensionManagementUtility::isLoaded($ISF_extKey) && (string)$ISF_localPath !== '') {
768
                        $ISF_localPath = rtrim($ISF_localPath, '/') . '/';
769
                        $ISF_filePath = ExtensionManagementUtility::extPath($ISF_extKey) . $ISF_localPath;
770
                        if (@is_dir($ISF_filePath)) {
771
                            $mExtKey = str_replace('_', '', $ISF_extKey . '/' . $ISF_localPath);
772
773
                            $includeStaticTxtPath = $ISF_filePath . 'include_static.txt';
774
                            $includeStaticTxtContents = '';
775
                            if (@file_exists($includeStaticTxtPath)) {
776
                                $includeStaticTxtContents = (string)file_get_contents($includeStaticTxtPath);
777
                                $includeStaticTxtContents = implode(',', array_unique(GeneralUtility::intExplode(',', $includeStaticTxtContents)));
778
                            }
779
780
                            $includeStaticFileTxtPath = $ISF_filePath . 'include_static_file.txt';
781
                            $includeStaticFileTxtContents = '';
782
                            if (@file_exists($includeStaticFileTxtPath)) {
783
                                $includeStaticFileTxtContents = (string)file_get_contents($includeStaticFileTxtPath);
784
                                $includeStaticFileTxtContents = implode(',', array_unique(GeneralUtility::trimExplode(',', $includeStaticFileTxtContents)));
785
                            }
786
787
                            $subrow = [
788
                                'constants' => $this->getTypoScriptSourceFileContent($ISF_filePath, 'constants'),
789
                                'config' => $this->getTypoScriptSourceFileContent($ISF_filePath, 'setup'),
790
                                'include_static' => $includeStaticTxtContents,
791
                                'include_static_file' => $includeStaticFileTxtContents,
792
                                'title' => $ISF_file,
793
                                'uid' => $mExtKey
794
                            ];
795
                            $subrow = $this->prependStaticExtra($subrow);
796
                            $this->processTemplate($subrow, $idList . ',ext_' . $mExtKey, $pid, 'ext_' . $mExtKey, $templateID, $ISF_filePath);
797
                        }
798
                    }
799
                }
800
            }
801
        }
802
        // If "Default (include before if root flag is set)" is set OR
803
        // "Always include before this template record" AND root-flag are set
804
        if ($staticFileMode == 1 || $staticFileMode == 0 && strpos($templateID, 'sys_') === 0 && $row['root']) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $staticFileMode of type mixed|null to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
805
            $this->addExtensionStatics($idList, $templateID, $pid);
806
        }
807
        // Include Static Template Records after all other TypoScript has been included.
808
        $_params = [
809
            'idList' => &$idList,
810
            'templateId' => &$templateID,
811
            'pid' => &$pid,
812
            'row' => &$row
813
        ];
814
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSourcesAtEnd'] ?? [] as $_funcRef) {
815
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
816
        }
817
    }
818
819
    /**
820
     * Retrieves the content of the first existing file by extension order.
821
     * Returns the empty string if no file is found.
822
     *
823
     * @param string $filePath The location of the file.
824
     * @param string $baseName The base file name. "constants" or "setup".
825
     * @return string
826
     */
827
    protected function getTypoScriptSourceFileContent($filePath, $baseName)
828
    {
829
        $extensions = ['.typoscript', '.ts', '.txt'];
830
        foreach ($extensions as $extension) {
831
            $fileName = $filePath . $baseName . $extension;
832
            if (@file_exists($fileName)) {
833
                return file_get_contents($fileName);
834
            }
835
        }
836
        return '';
837
    }
838
839
    /**
840
     * Adds the default TypoScript files for extensions if any.
841
     *
842
     * @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.
843
     * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
844
     * @param int $pid The PID of the input template record
845
     * @internal
846
     * @see includeStaticTypoScriptSources()
847
     */
848
    public function addExtensionStatics($idList, $templateID, $pid)
849
    {
850
        $this->extensionStaticsProcessed = true;
851
852
        foreach ($this->packageManager->getActivePackages() as $package) {
853
            $extKey = $package->getPackageKey();
854
            $packagePath = $package->getPackagePath();
855
            $filesToCheck = [
856
                'ext_typoscript_constants.txt',
857
                'ext_typoscript_constants.typoscript',
858
                'ext_typoscript_setup.txt',
859
                'ext_typoscript_setup.typoscript',
860
            ];
861
            $files = [];
862
            $hasExtensionStatics = false;
863
            foreach ($filesToCheck as $file) {
864
                $path = $packagePath . $file;
865
                if (@file_exists($path)) {
866
                    $files[$file] = $path;
867
                    $hasExtensionStatics = true;
868
                } else {
869
                    $files[$file] = null;
870
                }
871
            }
872
873
            if ($hasExtensionStatics) {
874
                $mExtKey = str_replace('_', '', $extKey);
875
                $constants = '';
876
                $config = '';
877
878
                if (!empty($files['ext_typoscript_constants.typoscript'])) {
879
                    $constants = @file_get_contents($files['ext_typoscript_constants.typoscript']);
880
                } elseif (!empty($files['ext_typoscript_constants.txt'])) {
881
                    $constants = @file_get_contents($files['ext_typoscript_constants.txt']);
882
                }
883
884
                if (!empty($files['ext_typoscript_setup.typoscript'])) {
885
                    $config = @file_get_contents($files['ext_typoscript_setup.typoscript']);
886
                } elseif (!empty($files['ext_typoscript_setup.txt'])) {
887
                    $config = @file_get_contents($files['ext_typoscript_setup.txt']);
888
                }
889
890
                $this->processTemplate(
891
                    $this->prependStaticExtra([
892
                        'constants' => $constants,
893
                        'config' => $config,
894
                        'title' => $extKey,
895
                        'uid' => $mExtKey
896
                    ]),
897
                    $idList . ',ext_' . $mExtKey,
898
                    $pid,
899
                    'ext_' . $mExtKey,
900
                    $templateID,
901
                    $packagePath
902
                );
903
            }
904
        }
905
    }
906
907
    /**
908
     * Appends (not prepends) additional TypoScript code to static template records/files as set in TYPO3_CONF_VARS
909
     * 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
910
     *
911
     * @param array $subrow Static template record/file
912
     * @return array Returns the input array where the values for keys "config" and "constants" may have been modified with prepended code.
913
     * @see addExtensionStatics()
914
     * @see includeStaticTypoScriptSources()
915
     */
916
    protected function prependStaticExtra($subrow)
917
    {
918
        // the identifier can be "43" if coming from "static template" extension or a path like "cssstyledcontent/static/"
919
        $identifier = $subrow['uid'];
920
        $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.'][$identifier] ?? '';
921
        $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.'][$identifier] ?? '';
922
        // 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
923
        if (in_array($identifier, $GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'], true)) {
924
            $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.']['defaultContentRendering'] ?? '';
925
            $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.']['defaultContentRendering'] ?? '';
926
        }
927
        return $subrow;
928
    }
929
930
    /**
931
     * Creating versioning overlay of a sys_template record.
932
     *
933
     * @param array $row Row to overlay (passed by reference)
934
     */
935
    protected function versionOL(&$row)
936
    {
937
        if ($this->context->getPropertyFromAspect('workspace', 'isOffline')) {
938
            $pageRepository = GeneralUtility::makeInstance(PageRepository::class, $this->context);
939
            $pageRepository->versionOL('sys_template', $row);
940
        }
941
    }
942
943
    /*******************************************************************
944
     *
945
     * Parsing TypoScript code text from Template Records into PHP array
946
     *
947
     *******************************************************************/
948
    /**
949
     * Generates the configuration array by replacing constants and parsing the whole thing.
950
     * Depends on $this->config and $this->constants to be set prior to this! (done by processTemplate/runThroughTemplates)
951
     *
952
     * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
953
     * @see start()
954
     */
955
    public function generateConfig()
956
    {
957
        // Add default TS for all code types
958
        $this->addDefaultTypoScript();
959
960
        // Parse the TypoScript code text for include-instructions!
961
        $this->processIncludes();
962
        // ****************************
963
        // Parse TypoScript Constants
964
        // ****************************
965
        // Initialize parser and match-condition classes:
966
        /** @var Parser\TypoScriptParser $constants */
967
        $constants = GeneralUtility::makeInstance(TypoScriptParser::class);
968
        /** @var ConditionMatcher $matchObj */
969
        $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
970
        $matchObj->setSimulateMatchConditions($this->matchAlternative);
971
        $matchObj->setSimulateMatchResult((bool)$this->matchAll);
972
        // Traverse constants text fields and parse them
973
        foreach ($this->constants as $str) {
974
            $constants->parse($str, $matchObj);
975
        }
976
        // Read out parse errors if any
977
        $this->parserErrors['constants'] = $constants->errors;
978
        // 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)
979
        $this->flatSetup = ArrayUtility::flatten($constants->setup, '', true);
980
        // ***********************************************
981
        // Parse TypoScript Setup (here called "config")
982
        // ***********************************************
983
        // Initialize parser and match-condition classes:
984
        /** @var Parser\TypoScriptParser $config */
985
        $config = GeneralUtility::makeInstance(TypoScriptParser::class);
986
        $config->regLinenumbers = $this->ext_regLinenumbers;
987
        $config->regComments = $this->ext_regComments;
988
        $config->setup = $this->setup;
989
        // Transfer information about conditions found in "Constants" and which of them returned TRUE.
990
        $config->sections = $constants->sections;
991
        $config->sectionsMatch = $constants->sectionsMatch;
992
        // Traverse setup text fields and concatenate them into one, single string separated by a [GLOBAL] condition
993
        $all = '';
994
        foreach ($this->config as $str) {
995
            $all .= '
996
[GLOBAL]
997
' . $str;
998
        }
999
        // Substitute constants in the Setup code:
1000
        if ($this->tt_track) {
1001
            $this->getTimeTracker()->push('Substitute Constants (' . count($this->flatSetup) . ')');
1002
        }
1003
        $all = $this->substituteConstants($all);
1004
        if ($this->tt_track) {
1005
            $this->getTimeTracker()->pull();
1006
        }
1007
1008
        // Searching for possible unsubstituted constants left (only for information)
1009
        if ($this->verbose) {
1010
            if (preg_match_all('/\\{\\$.[^}]*\\}/', $all, $constantList) > 0) {
1011
                if ($this->tt_track) {
1012
                    $this->getTimeTracker()->setTSlogMessage(implode(', ', $constantList[0]) . ': Constants may remain un-substituted!!', 2);
1013
                }
1014
            }
1015
        }
1016
1017
        // Logging the textual size of the TypoScript Setup field text with all constants substituted:
1018
        if ($this->tt_track) {
1019
            $this->getTimeTracker()->setTSlogMessage('TypoScript template size as textfile: ' . strlen($all) . ' bytes');
1020
        }
1021
        // Finally parse the Setup field TypoScript code (where constants are now substituted)
1022
        $config->parse($all, $matchObj);
1023
        // Read out parse errors if any
1024
        $this->parserErrors['config'] = $config->errors;
1025
        // Transfer the TypoScript array from the parser object to the internal $this->setup array:
1026
        $this->setup = $config->setup;
1027
        // Do the same for the constants
1028
        $this->setup_constants = $constants->setup;
1029
        // ****************************************************************
1030
        // Final processing of the $this->setup TypoScript Template array
1031
        // Basically: This is unsetting/setting of certain reserved keys.
1032
        // ****************************************************************
1033
        // 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!
1034
        unset($this->setup['types.']);
1035
        unset($this->setup['types']);
1036
        if (is_array($this->setup)) {
1037
            foreach ($this->setup as $key => $value) {
1038
                if ($value === 'PAGE') {
1039
                    // Set the typeNum of the current page object:
1040
                    if (isset($this->setup[$key . '.']['typeNum'])) {
1041
                        $typeNum = $this->setup[$key . '.']['typeNum'];
1042
                        $this->setup['types.'][$typeNum] = $key;
1043
                    } elseif (!isset($this->setup['types.'][0]) || !$this->setup['types.'][0]) {
1044
                        $this->setup['types.'][0] = $key;
1045
                    }
1046
                }
1047
            }
1048
        }
1049
        unset($this->setup['temp.']);
1050
        unset($constants);
1051
        // Storing the conditions found/matched information:
1052
        $this->sections = $config->sections;
1053
        $this->sectionsMatch = $config->sectionsMatch;
1054
    }
1055
1056
    /**
1057
     * Searching TypoScript code text (for constants and config (Setup))
1058
     * for include instructions and does the inclusion of external TypoScript files
1059
     * if needed.
1060
     *
1061
     * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
1062
     * @see generateConfig()
1063
     */
1064
    protected function processIncludes()
1065
    {
1066
        if ($this->processIncludesHasBeenRun) {
1067
            return;
1068
        }
1069
1070
        $paths = $this->templateIncludePaths;
1071
        $files = [];
1072
        foreach ($this->constants as &$value) {
1073
            $includeData = TypoScriptParser::checkIncludeLines($value, 1, true, array_shift($paths));
1074
            $files = array_merge($files, $includeData['files']);
1075
            $value = $includeData['typoscript'];
1076
        }
1077
        unset($value);
1078
        $paths = $this->templateIncludePaths;
1079
        foreach ($this->config as &$value) {
1080
            $includeData = TypoScriptParser::checkIncludeLines($value, 1, true, array_shift($paths));
1081
            $files = array_merge($files, $includeData['files']);
1082
            $value = $includeData['typoscript'];
1083
        }
1084
        unset($value);
1085
1086
        if (!empty($files)) {
1087
            $files = array_unique($files);
1088
            foreach ($files as $file) {
1089
                $this->rowSum[] = [$file, filemtime($file)];
1090
            }
1091
        }
1092
1093
        $this->processIncludesHasBeenRun = true;
1094
    }
1095
1096
    /**
1097
     * Substitutes the constants from $this->flatSetup in the text string $all
1098
     *
1099
     * @param string $all TypoScript code text string
1100
     * @return string The processed string with all constants found in $this->flatSetup as key/value pairs substituted.
1101
     * @see generateConfig()
1102
     */
1103
    protected function substituteConstants($all)
1104
    {
1105
        if ($this->tt_track) {
1106
            $this->getTimeTracker()->setTSlogMessage('Constants to substitute: ' . count($this->flatSetup));
1107
        }
1108
        $noChange = false;
1109
        // Recursive substitution of constants (up to 10 nested levels)
1110
        for ($i = 0; $i < 10 && !$noChange; $i++) {
1111
            $old_all = $all;
1112
            $all = preg_replace_callback('/\\{\\$(.[^}]*)\\}/', [$this, 'substituteConstantsCallBack'], $all) ?? '';
1113
            if ($old_all == $all) {
1114
                $noChange = true;
1115
            }
1116
        }
1117
        return $all;
1118
    }
1119
1120
    /**
1121
     * Call back method for preg_replace_callback in substituteConstants
1122
     *
1123
     * @param array $matches Regular expression matches
1124
     * @return string Replacement
1125
     * @see substituteConstants()
1126
     * @internal
1127
     */
1128
    public function substituteConstantsCallBack($matches)
1129
    {
1130
        // Replace {$CONST} if found in $this->flatSetup, else leave unchanged
1131
        return isset($this->flatSetup[$matches[1]]) && !is_array($this->flatSetup[$matches[1]]) ? $this->flatSetup[$matches[1]] : $matches[0];
1132
    }
1133
1134
    /*******************************************************************
1135
     *
1136
     * Various API functions, used from elsewhere in the frontend classes
1137
     *
1138
     *******************************************************************/
1139
1140
    /**
1141
     * Returns the level of the given page in the rootline - Multiple pages can be given by separating the UIDs by comma.
1142
     *
1143
     * @param string $list A list of UIDs for which the rootline-level should get returned
1144
     * @return int The level in the rootline. If more than one page was given the lowest level will get returned.
1145
     */
1146
    public function getRootlineLevel($list)
1147
    {
1148
        $idx = 0;
1149
        foreach ($this->rootLine as $page) {
1150
            if (GeneralUtility::inList($list, $page['uid'])) {
1151
                return $idx;
1152
            }
1153
            $idx++;
1154
        }
1155
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type integer.
Loading history...
1156
    }
1157
1158
    /**
1159
     * Returns the page ID of the rootlevel
1160
     *
1161
     * @return int
1162
     */
1163
    public function getRootId(): int
1164
    {
1165
        return (int)$this->rootId;
1166
    }
1167
1168
    /*******************************************************************
1169
     *
1170
     * Functions for creating links
1171
     *
1172
     *******************************************************************/
1173
    /**
1174
     * Adds the TypoScript from the global array.
1175
     * The class property isDefaultTypoScriptAdded ensures
1176
     * that the adding only happens once.
1177
     *
1178
     * @see isDefaultTypoScriptAdded
1179
     */
1180
    protected function addDefaultTypoScript()
1181
    {
1182
        // Add default TS for all code types, if not done already
1183
        if (!$this->isDefaultTypoScriptAdded) {
1184
            $rootTemplateId = $this->hierarchyInfo[count($this->hierarchyInfo) - 1]['templateID'] ?? null;
1185
1186
            // adding constants from site settings
1187
            $siteConstants = '';
1188
            if ($this->getTypoScriptFrontendController() instanceof TypoScriptFrontendController) {
0 ignored issues
show
introduced by
$this->getTypoScriptFrontendController() is always a sub-type of TYPO3\CMS\Frontend\Contr...criptFrontendController.
Loading history...
1189
                $site = $this->getTypoScriptFrontendController()->getSite();
1190
            } else {
1191
                $currentPage = end($this->absoluteRootLine);
1192
                try {
1193
                    $site = GeneralUtility::makeInstance(SiteFinder::class)->getSiteByPageId((int)($currentPage['uid'] ?? 0));
1194
                } catch (SiteNotFoundException $exception) {
1195
                    $site = null;
1196
                }
1197
            }
1198
            if ($site instanceof Site) {
1199
                $siteSettings = $site->getConfiguration()['settings'] ?? [];
1200
                if (!empty($siteSettings)) {
1201
                    $siteSettings = ArrayUtility::flatten($siteSettings);
1202
                    foreach ($siteSettings as $k => $v) {
1203
                        $siteConstants .= $k . ' = ' . $v . LF;
1204
                    }
1205
                }
1206
            }
1207
1208
            if ($siteConstants !== '') {
1209
                // the count of elements in ->constants, ->config and ->templateIncludePaths have to be in sync
1210
                array_unshift($this->constants, $siteConstants);
1211
                array_unshift($this->config, '');
1212
                array_unshift($this->templateIncludePaths, '');
1213
                // prepare a proper entry to hierachyInfo (used by TemplateAnalyzer in BE)
1214
                $defaultTemplateInfo = [
1215
                    'root' => '',
1216
                    'clConst' => '',
1217
                    'clConf' => '',
1218
                    'templateID' => '_siteConstants_',
1219
                    'templateParent' => $rootTemplateId,
1220
                    'title' => 'Site settings',
1221
                    'uid' => '_siteConstants_',
1222
                    'pid' => '',
1223
                    'configLines' => 0
1224
                ];
1225
                // push info to information arrays used in BE by TemplateTools (Analyzer)
1226
                array_unshift($this->clearList_const, $defaultTemplateInfo['uid']);
1227
                array_unshift($this->clearList_setup, $defaultTemplateInfo['uid']);
1228
                array_unshift($this->hierarchyInfo, $defaultTemplateInfo);
1229
            }
1230
1231
            // adding default setup and constants
1232
            // defaultTypoScript_setup is *very* unlikely to be empty
1233
            // the count of elements in ->constants, ->config and ->templateIncludePaths have to be in sync
1234
            array_unshift($this->constants, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants']);
1235
            array_unshift($this->config, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup']);
1236
            array_unshift($this->templateIncludePaths, '');
1237
            // prepare a proper entry to hierachyInfo (used by TemplateAnalyzer in BE)
1238
            $defaultTemplateInfo = [
1239
                'root' => '',
1240
                'clConst' => '',
1241
                'clConf' => '',
1242
                'templateID' => '_defaultTypoScript_',
1243
                'templateParent' => $rootTemplateId,
1244
                'title' => 'SYS:TYPO3_CONF_VARS:FE:defaultTypoScript',
1245
                'uid' => '_defaultTypoScript_',
1246
                'pid' => '',
1247
                'configLines' => substr_count((string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup'], LF) + 1
1248
            ];
1249
            // push info to information arrays used in BE by TemplateTools (Analyzer)
1250
            array_unshift($this->clearList_const, $defaultTemplateInfo['uid']);
1251
            array_unshift($this->clearList_setup, $defaultTemplateInfo['uid']);
1252
            array_unshift($this->hierarchyInfo, $defaultTemplateInfo);
1253
1254
            $this->isDefaultTypoScriptAdded = true;
1255
        }
1256
    }
1257
1258
    /**
1259
     * @return TypoScriptFrontendController
1260
     */
1261
    protected function getTypoScriptFrontendController()
1262
    {
1263
        return $this->frontendController ?? $GLOBALS['TSFE'] ?? null;
1264
    }
1265
1266
    /**
1267
     * @return TimeTracker
1268
     */
1269
    protected function getTimeTracker()
1270
    {
1271
        return GeneralUtility::makeInstance(TimeTracker::class);
1272
    }
1273
1274
    /**
1275
     * Returns data stored for the hash string in the cache "cache_hash"
1276
     * used to store the parsed TypoScript template structures.
1277
     *
1278
     * @param string $identifier The hash-string which was used to store the data value
1279
     * @return mixed The data from the cache
1280
     */
1281
    protected function getCacheEntry($identifier)
1282
    {
1283
        return GeneralUtility::makeInstance(CacheManager::class)->getCache('hash')->get($identifier);
1284
    }
1285
1286
    /**
1287
     * Stores $data in the 'hash' cache with the hash key $identifier
1288
     *
1289
     * @param string $identifier 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
1290
     * @param mixed $data The data to store
1291
     * @param string $tag Is just a textual identification in order to inform about the content
1292
     */
1293
    protected function setCacheEntry($identifier, $data, $tag)
1294
    {
1295
        GeneralUtility::makeInstance(CacheManager::class)->getCache('hash')->set($identifier, $data, ['ident_' . $tag], 0);
1296
    }
1297
}
1298