Completed
Push — master ( 5434e6...3e57ee )
by
unknown
22:28 queued 08:05
created

TemplateService::getRootlineLevel()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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