Passed
Branch master (6c65a4)
by Christian
27:15 queued 11:09
created

mergeConstantsFromIncludedTsConfigFiles()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 12
nc 6
nop 2
dl 0
loc 23
rs 6.7272
c 0
b 0
f 0
1
<?php
2
namespace TYPO3\CMS\Core\TypoScript;
3
4
/*
5
 * This file is part of the TYPO3 CMS project.
6
 *
7
 * It is free software; you can redistribute it and/or modify it under
8
 * the terms of the GNU General Public License, either version 2
9
 * of the License, or any later version.
10
 *
11
 * For the full copyright and license information, please read the
12
 * LICENSE.txt file that was distributed with this source code.
13
 *
14
 * The TYPO3 project - inspiring people to share!
15
 */
16
17
use TYPO3\CMS\Backend\Utility\BackendUtility;
18
use TYPO3\CMS\Core\Cache\CacheManager;
19
use TYPO3\CMS\Core\Compatibility\PublicPropertyDeprecationTrait;
20
use TYPO3\CMS\Core\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\DeletedRestriction;
25
use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
26
use TYPO3\CMS\Core\TimeTracker\TimeTracker;
27
use TYPO3\CMS\Core\Utility\ArrayUtility;
28
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
29
use TYPO3\CMS\Core\Utility\GeneralUtility;
30
use TYPO3\CMS\Core\Utility\MathUtility;
31
use TYPO3\CMS\Core\Utility\PathUtility;
32
use TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher;
33
use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
34
use TYPO3\CMS\Frontend\Page\PageRepository;
35
36
/**
37
 * Template object that is responsible for generating the TypoScript template based on template records.
38
 * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser
39
 * @see \TYPO3\CMS\Core\Configuration\TypoScript\ConditionMatching\AbstractConditionMatcher
40
 */
41
class TemplateService
42
{
43
    use PublicPropertyDeprecationTrait;
44
45
    /**
46
     * Properties which have been moved to protected status from public
47
     * @var array
48
     */
49
    protected $deprecatedPublicProperties = [
50
        'matchAll' => 'Using $matchAll of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
51
        'whereClause' => 'Using $whereClause of class TemplateService is discouraged, as this has been superseeded by Doctrine DBAL API.',
52
        'debug' => 'Using $debug of class TemplateService is discouraged, as this option has no effect anymore.',
53
        'allowedPaths' => 'Using $allowedPaths of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
54
        'simulationHiddenOrTime' => 'Using $simulationHiddenOrTime of class TemplateService is discouraged, as this has been superseeded by Doctrine DBAL API.',
55
        'nextLevel' => 'Using $nextLevel of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
56
        'rootId' => 'Using $rootId of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
57
        'absoluteRootLine' => 'Using $absoluteRootLine of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
58
        'outermostRootlineIndexWithTemplate' => 'Using $outermostRootlineIndexWithTemplate of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
59
        'rowSum' => 'Using $rowSum of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
60
        'sitetitle' => 'Using $sitetitle of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
61
        'sectionsMatch' => 'Using $sectionsMatch of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
62
        'frames' => 'Using $frames of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
63
        'MPmap' => 'Using $MPmap of class TemplateService from the outside is discouraged, as this variable is only used for internal storage.',
64
    ];
65
66
    /**
67
     * option to enable logging, time-tracking (FE-only)
68
     * usually, this is only done when
69
     *  - in FE a BE_USER is logged-in
70
     *  - in BE when the BE_USER needs information about the template (TypoScript module)
71
     * @var bool
72
     */
73
    protected $verbose = false;
74
75
    /**
76
     * If set, the global tt-timeobject is used to log the performance.
77
     *
78
     * @var bool
79
     */
80
    public $tt_track = true;
81
82
    /**
83
     * If set, the template is always rendered. Used from Admin Panel.
84
     *
85
     * @var bool
86
     */
87
    public $forceTemplateParsing = false;
88
89
    /**
90
     * This array is passed on to matchObj by generateConfig().
91
     * If it holds elements, they are used for matching instead. See comment at the match-class.
92
     * Used for backend modules only. Never frontend!
93
     *
94
     * @var array
95
     */
96
    public $matchAlternative = [];
97
98
    /**
99
     * If set, the match-class matches everything! Used for backend modules only. Never frontend!
100
     *
101
     * @var bool
102
     */
103
    protected $matchAll = false;
104
105
    /**
106
     * Externally set breakpoints (used by Backend Modules)
107
     *
108
     * @var int
109
     */
110
    public $ext_constants_BRP = 0;
111
112
    /**
113
     * @var int
114
     */
115
    public $ext_config_BRP = 0;
116
117
    /**
118
     * @var bool
119
     */
120
    public $ext_regLinenumbers = false;
121
122
    /**
123
     * @var bool
124
     */
125
    public $ext_regComments = false;
126
127
    /**
128
     * This MUST be initialized by the init() function
129
     *
130
     * @var string
131
     */
132
    protected $whereClause = '';
133
134
    /**
135
     * @var bool
136
     */
137
    protected $debug = false;
138
139
    /**
140
     * This is the only paths (relative!!) that are allowed for resources in TypoScript.
141
     * Should all be appended with '/'. You can extend these by the global array TYPO3_CONF_VARS. See init() function.
142
     *
143
     * @var array
144
     */
145
    protected $allowedPaths = [];
146
147
    /**
148
     * See init(); Set if preview of some kind is enabled.
149
     *
150
     * @var int
151
     */
152
    protected $simulationHiddenOrTime = 0;
153
154
    /**
155
     * Set, if the TypoScript template structure is loaded and OK, see ->start()
156
     *
157
     * @var bool
158
     */
159
    public $loaded = false;
160
161
    /**
162
     * @var array Contains TypoScript setup part after parsing
163
     */
164
    public $setup = [];
165
166
    /**
167
     * @var array
168
     */
169
    public $flatSetup = [];
170
171
    /**
172
     * For fetching TypoScript code from template hierarchy before parsing it.
173
     * Each array contains code field values from template records/files:
174
     * Setup field
175
     *
176
     * @var array
177
     */
178
    public $config = [];
179
180
    /**
181
     * Constant field
182
     *
183
     * @var array
184
     */
185
    public $constants = [];
186
187
    /**
188
     * Holds the include paths of the templates (empty if from database)
189
     *
190
     * @var array
191
     */
192
    protected $templateIncludePaths = [];
193
194
    /**
195
     * For Template Analyser in backend
196
     *
197
     * @var array
198
     */
199
    public $hierarchyInfo = [];
200
201
    /**
202
     * For Template Analyser in backend (setup content only)
203
     *
204
     * @var array
205
     */
206
    protected $hierarchyInfoToRoot = [];
207
208
    /**
209
     * Next-level flag (see runThroughTemplates())
210
     *
211
     * @var int
212
     */
213
    protected $nextLevel = 0;
214
215
    /**
216
     * The Page UID of the root page
217
     *
218
     * @var int
219
     */
220
    protected $rootId;
221
222
    /**
223
     * The rootline from current page to the root page
224
     *
225
     * @var array
226
     */
227
    public $rootLine;
228
229
    /**
230
     * Rootline all the way to the root. Set but runThroughTemplates
231
     *
232
     * @var array
233
     */
234
    protected $absoluteRootLine;
235
236
    /**
237
     * A pointer to the last entry in the rootline where a template was found.
238
     *
239
     * @var int
240
     */
241
    protected $outermostRootlineIndexWithTemplate = 0;
242
243
    /**
244
     * Array of arrays with title/uid of templates in hierarchy
245
     *
246
     * @var array
247
     */
248
    protected $rowSum;
249
250
    /**
251
     * The current site title field.
252
     *
253
     * @var string
254
     */
255
    protected $sitetitle = '';
256
257
    /**
258
     * Tracking all conditions found during parsing of TypoScript. Used for the "all" key in currentPageData
259
     *
260
     * @var string
261
     */
262
    public $sections;
263
264
    /**
265
     * Tracking all matching conditions found
266
     *
267
     * @var array
268
     */
269
    protected $sectionsMatch;
270
271
    /**
272
     * Used by Backend only (Typoscript Template Analyzer)
273
     */
274
    public $clearList_const = [];
275
276
    /**
277
     * Used by Backend only (Typoscript Template Analyzer)
278
     *
279
     * @var array
280
     */
281
    public $clearList_setup = [];
282
283
    /**
284
     * @var array
285
     */
286
    public $parserErrors = [];
287
288
    /**
289
     * @var array
290
     */
291
    public $setup_constants = [];
292
293
    /**
294
     * Used by getFileName for caching of references to file resources
295
     *
296
     * @var array
297
     */
298
    public $fileCache = [];
299
300
    /**
301
     * Keys are frame names and values are type-values, which must be used to refer correctly to the content of the frames.
302
     *
303
     * @var array
304
     */
305
    protected $frames = [];
306
307
    /**
308
     * Contains mapping of Page id numbers to MP variables.
309
     *
310
     * @var string
311
     */
312
    protected $MPmap = '';
313
314
    /**
315
     * Indicator that extension statics are processed.
316
     *
317
     * These files are considered if either a root template
318
     * has been processed or the $processExtensionStatics
319
     * property has been set to TRUE.
320
     *
321
     * @var bool
322
     */
323
    protected $extensionStaticsProcessed = false;
324
325
    /**
326
     * Trigger value, to ensure that extension statics are processed.
327
     *
328
     * @var bool
329
     */
330
    protected $processExtensionStatics = false;
331
332
    /**
333
     * Set to TRUE after the default TypoScript was added during parsing.
334
     * This prevents double inclusion of the same TypoScript code.
335
     *
336
     * @see addDefaultTypoScript()
337
     * @var bool
338
     */
339
    protected $isDefaultTypoScriptAdded = false;
340
341
    /**
342
     * Set to TRUE after $this->config and $this->constants have processed all <INCLUDE_TYPOSCRIPT:> instructions.
343
     *
344
     * This prevents double processing of INCLUDES.
345
     *
346
     * @see processIncludes()
347
     * @var bool
348
     */
349
    protected $processIncludesHasBeenRun = false;
350
351
    /**
352
     * Contains the restrictions about deleted, and some frontend related topics
353
     * @var AbstractRestrictionContainer
354
     */
355
    protected $queryBuilderRestrictions;
356
357
    /**
358
     * @return bool
359
     */
360
    public function getProcessExtensionStatics()
361
    {
362
        return $this->processExtensionStatics;
363
    }
364
365
    /**
366
     * @param bool $processExtensionStatics
367
     */
368
    public function setProcessExtensionStatics($processExtensionStatics)
369
    {
370
        $this->processExtensionStatics = (bool)$processExtensionStatics;
371
    }
372
373
    /**
374
     * sets the verbose parameter
375
     * @param bool $verbose
376
     */
377
    public function setVerbose($verbose)
378
    {
379
        $this->verbose = (bool)$verbose;
380
    }
381
382
    /**
383
     * Initialize
384
     * MUST be called directly after creating a new template-object
385
     *
386
     * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::initTemplate()
387
     */
388
    public function init()
389
    {
390
        $this->initializeDatabaseQueryRestrictions();
391
392
        if ($this->getTypoScriptFrontendController()->showHiddenRecords || $GLOBALS['SIM_ACCESS_TIME'] !== $GLOBALS['ACCESS_TIME']) {
393
            // Set the simulation flag, if simulation is detected!
394
            $this->simulationHiddenOrTime = 1;
395
        }
396
397
        // Sets the paths from where TypoScript resources are allowed to be used:
398
        $this->allowedPaths = [
399
            $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'],
400
            // fileadmin/ path
401
            'uploads/',
402
            'typo3temp/',
403
            TYPO3_mainDir . 'ext/',
404
            TYPO3_mainDir . 'sysext/',
405
            'typo3conf/ext/'
406
        ];
407
        if ($GLOBALS['TYPO3_CONF_VARS']['FE']['addAllowedPaths']) {
408
            $pathArr = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['addAllowedPaths'], true);
409
            foreach ($pathArr as $p) {
410
                // Once checked for path, but as this may run from typo3/mod/web/ts/ dir, that'll not work!! So the paths ar uncritically included here.
411
                $this->allowedPaths[] = $p;
412
            }
413
        }
414
    }
415
416
    /**
417
     * $this->whereclause is kept for backwards compatibility
418
     */
419
    protected function initializeDatabaseQueryRestrictions()
420
    {
421
        // $this->whereClause is used only to select templates from sys_template.
422
        // $GLOBALS['SIM_ACCESS_TIME'] is used so that we're able to simulate a later time as a test...
423
        $this->whereClause = 'AND deleted=0 ';
424
        if (!$this->getTypoScriptFrontendController()->showHiddenRecords) {
425
            $this->whereClause .= 'AND hidden=0 ';
426
        }
427
        $this->whereClause .= 'AND (starttime<=' . $GLOBALS['SIM_ACCESS_TIME'] . ') AND (endtime=0 OR endtime>' . $GLOBALS['SIM_ACCESS_TIME'] . ')';
428
429
        // set up the query builder restrictions
430
        $this->queryBuilderRestrictions = GeneralUtility::makeInstance(DefaultRestrictionContainer::class);
431
432
        if ($this->getTypoScriptFrontendController()->showHiddenRecords) {
433
            $this->queryBuilderRestrictions
434
                ->removeByType(HiddenRestriction::class);
435
        }
436
    }
437
438
    /**
439
     * Fetches the "currentPageData" array from cache
440
     *
441
     * NOTE about currentPageData:
442
     * It holds information about the TypoScript conditions along with the list
443
     * of template uid's which is used on the page. In the getFromCache() function
444
     * in TSFE, currentPageData is used to evaluate if there is a template and
445
     * if the matching conditions are alright. Unfortunately this does not take
446
     * into account if the templates in the rowSum of currentPageData has
447
     * changed composition, eg. due to hidden fields or start/end time. So if a
448
     * template is hidden or times out, it'll not be discovered unless the page
449
     * is regenerated - at least the this->start function must be called,
450
     * because this will make a new portion of data in currentPageData string.
451
     *
452
     * @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
453
     */
454
    public function getCurrentPageData()
455
    {
456
        return GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_pagesection')->get((int)$this->getTypoScriptFrontendController()->id . '_' . GeneralUtility::md5int($this->getTypoScriptFrontendController()->MP));
457
    }
458
459
    /**
460
     * Fetches data about which TypoScript-matches there are at this page. Then it performs a matchingtest.
461
     *
462
     * @param array $cc An array with three keys, "all", "rowSum" and "rootLine" - all coming from the "currentPageData" array
463
     * @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.
464
     */
465
    public function matching($cc)
466
    {
467
        if (is_array($cc['all'])) {
468
            /** @var $matchObj ConditionMatcher */
469
            $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
470
            $matchObj->setRootline((array)$cc['rootLine']);
471
            $sectionsMatch = [];
472
            foreach ($cc['all'] as $key => $pre) {
473
                if ($matchObj->match($pre)) {
474
                    $sectionsMatch[$key] = $pre;
475
                }
476
            }
477
            $cc['match'] = $sectionsMatch;
478
        }
479
        return $cc;
480
    }
481
482
    /**
483
     * This is all about fetching the right TypoScript template structure. If it's not cached then it must be generated and cached!
484
     * 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.
485
     * Sets $this->setup to the parsed TypoScript template array
486
     *
487
     * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
488
     * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::getConfigArray()
489
     */
490
    public function start($theRootLine)
491
    {
492
        if (is_array($theRootLine)) {
493
            $constantsData = [];
494
            $setupData = [];
495
            $cacheIdentifier = '';
496
            // Flag that indicates that the existing data in cache_pagesection
497
            // could be used (this is the case if $TSFE->all is set, and the
498
            // rowSum still matches). Based on this we decide if cache_pagesection
499
            // needs to be updated...
500
            $isCached = false;
501
            $this->runThroughTemplates($theRootLine);
502
            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...
503
                $cc = $this->getTypoScriptFrontendController()->all;
504
                // The two rowSums must NOT be different from each other - which they will be if start/endtime or hidden has changed!
505
                if (serialize($this->rowSum) !== serialize($cc['rowSum'])) {
506
                    unset($cc);
507
                } else {
508
                    // If $TSFE->all contains valid data, we don't need to update cache_pagesection (because this data was fetched from there already)
509
                    if (serialize($this->rootLine) === serialize($cc['rootLine'])) {
510
                        $isCached = true;
511
                    }
512
                    // 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)...
513
                    unset($cc['rootLine']);
514
                }
515
            }
516
            // This is about getting the hash string which is used to fetch the cached TypoScript template.
517
            // If there was some cached currentPageData ($cc) then that's good (it gives us the hash).
518
            if (isset($cc) && is_array($cc)) {
519
                // If currentPageData was actually there, we match the result (if this wasn't done already in $TSFE->getFromCache()...)
520
                if (!$cc['match']) {
521
                    // @todo check if this can ever be the case - otherwise remove
522
                    $cc = $this->matching($cc);
523
                    ksort($cc);
524
                }
525
                $cacheIdentifier = md5(serialize($cc));
526
            } else {
527
                // 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.
528
                $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
529
                $result = $this->getCacheEntry($rowSumHash);
530
                if (is_array($result)) {
531
                    $cc = [];
532
                    $cc['all'] = $result;
533
                    $cc['rowSum'] = $this->rowSum;
534
                    $cc = $this->matching($cc);
535
                    ksort($cc);
536
                    $cacheIdentifier = md5(serialize($cc));
537
                }
538
            }
539
            if ($cacheIdentifier) {
540
                // Get TypoScript setup array
541
                $cachedData = $this->getCacheEntry($cacheIdentifier);
542
                if (is_array($cachedData)) {
543
                    $constantsData = $cachedData['constants'];
544
                    $setupData = $cachedData['setup'];
545
                }
546
            }
547
            if (!empty($setupData) && !$this->forceTemplateParsing) {
548
                // TypoScript constants + setup are found in the cache
549
                $this->setup_constants = $constantsData;
550
                $this->setup = $setupData;
551
                if ($this->tt_track) {
552
                    $this->getTimeTracker()->setTSlogMessage('Using cached TS template data');
553
                }
554
            } else {
555
                if ($this->tt_track) {
556
                    $this->getTimeTracker()->setTSlogMessage('Not using any cached TS data');
557
                }
558
559
                // Make configuration
560
                $this->generateConfig();
561
                // This stores the template hash thing
562
                $cc = [];
563
                // All sections in the template at this point is found
564
                $cc['all'] = $this->sections;
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->sections of type array<mixed,mixed|string> is incompatible with the declared type string of property $sections.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
565
                // The line of templates is collected
566
                $cc['rowSum'] = $this->rowSum;
567
                $cc = $this->matching($cc);
568
                ksort($cc);
569
                $cacheIdentifier = md5(serialize($cc));
570
                // This stores the data.
571
                $this->setCacheEntry($cacheIdentifier, ['constants' => $this->setup_constants, 'setup' => $this->setup], 'TS_TEMPLATE');
572
                if ($this->tt_track) {
573
                    $this->getTimeTracker()->setTSlogMessage('TS template size, serialized: ' . strlen(serialize($this->setup)) . ' bytes');
574
                }
575
                $rowSumHash = md5('ROWSUM:' . serialize($this->rowSum));
576
                $this->setCacheEntry($rowSumHash, $cc['all'], 'TMPL_CONDITIONS_ALL');
577
            }
578
            // Add rootLine
579
            $cc['rootLine'] = $this->rootLine;
580
            ksort($cc);
581
            // Make global and save
582
            $this->getTypoScriptFrontendController()->all = $cc;
583
            // Matching must be executed for every request, so this must never be part of the pagesection cache!
584
            unset($cc['match']);
585
            if (!$isCached && !$this->simulationHiddenOrTime && !$this->getTypoScriptFrontendController()->no_cache) {
586
                // Only save the data if we're not simulating by hidden/starttime/endtime
587
                $mpvarHash = GeneralUtility::md5int($this->getTypoScriptFrontendController()->MP);
588
                /** @var $pageSectionCache \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface */
589
                $pageSectionCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_pagesection');
590
                $pageSectionCache->set((int)$this->getTypoScriptFrontendController()->id . '_' . $mpvarHash, $cc, [
591
                    'pageId_' . (int)$this->getTypoScriptFrontendController()->id,
592
                    'mpvarHash_' . $mpvarHash
593
                ]);
594
            }
595
            // If everything OK.
596
            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...
597
                $this->loaded = true;
598
            }
599
        }
600
    }
601
602
    /*******************************************************************
603
     *
604
     * Fetching TypoScript code text for the Template Hierarchy
605
     *
606
     *******************************************************************/
607
    /**
608
     * 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.
609
     * Resets and affects internal variables like $this->constants, $this->config and $this->rowSum
610
     * 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
611
     *
612
     * @param array $theRootLine The rootline of the current page (going ALL the way to tree root)
613
     * @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)
614
     * @see start()
615
     */
616
    public function runThroughTemplates($theRootLine, $start_template_uid = 0)
617
    {
618
        $this->constants = [];
619
        $this->config = [];
620
        $this->rowSum = [];
621
        $this->hierarchyInfoToRoot = [];
622
        $this->absoluteRootLine = $theRootLine;
623
        $this->isDefaultTypoScriptAdded = false;
624
625
        reset($this->absoluteRootLine);
626
        $c = count($this->absoluteRootLine);
627
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_template');
628
        for ($a = 0; $a < $c; $a++) {
629
            // If some template loaded before has set a template-id for the next level, then load this template first!
630
            if ($this->nextLevel) {
631
                $queryBuilder->setRestrictions($this->queryBuilderRestrictions);
632
                $queryResult = $queryBuilder
633
                    ->select('*')
634
                    ->from('sys_template')
635
                    ->where(
636
                        $queryBuilder->expr()->eq(
637
                            'uid',
638
                            $queryBuilder->createNamedParameter($this->nextLevel, \PDO::PARAM_INT)
639
                        )
640
                    )
641
                    ->execute();
642
                $this->nextLevel = 0;
643
                if ($row = $queryResult->fetch()) {
644
                    $this->versionOL($row);
645
                    if (is_array($row)) {
646
                        $this->processTemplate($row, 'sys_' . $row['uid'], $this->absoluteRootLine[$a]['uid'], 'sys_' . $row['uid']);
647
                        $this->outermostRootlineIndexWithTemplate = $a;
648
                    }
649
                }
650
            }
651
652
            $where = [
653
                $queryBuilder->expr()->eq(
654
                    'pid',
655
                    $queryBuilder->createNamedParameter($this->absoluteRootLine[$a]['uid'], \PDO::PARAM_INT)
656
                )
657
            ];
658
            // If first loop AND there is set an alternative template uid, use that
659
            if ($a === $c - 1 && $start_template_uid) {
660
                $where[] = $queryBuilder->expr()->eq(
661
                    'uid',
662
                    $queryBuilder->createNamedParameter($start_template_uid, \PDO::PARAM_INT)
663
                );
664
            }
665
            $queryBuilder->setRestrictions($this->queryBuilderRestrictions);
666
            $queryResult = $queryBuilder
667
                ->select('*')
668
                ->from('sys_template')
669
                ->where(...$where)
670
                ->orderBy('root', 'DESC')
671
                ->addOrderBy('sorting')
672
                ->setMaxResults(1)
673
                ->execute();
674
            if ($row = $queryResult->fetch()) {
675
                $this->versionOL($row);
676
                if (is_array($row)) {
677
                    $this->processTemplate($row, 'sys_' . $row['uid'], $this->absoluteRootLine[$a]['uid'], 'sys_' . $row['uid']);
678
                    $this->outermostRootlineIndexWithTemplate = $a;
679
                }
680
            }
681
            $this->rootLine[] = $this->absoluteRootLine[$a];
682
        }
683
684
        // Hook into the default TypoScript to add custom typoscript logic
685
        $hookParameters = [
686
            'extensionStaticsProcessed' => &$this->extensionStaticsProcessed,
687
            'isDefaultTypoScriptAdded'  => &$this->isDefaultTypoScriptAdded,
688
            'absoluteRootLine' => &$this->absoluteRootLine,
689
            'rootLine'         => &$this->rootLine,
690
            'startTemplateUid' => $start_template_uid,
691
        ];
692
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['Core/TypoScript/TemplateService']['runThroughTemplatesPostProcessing'] ?? [] as $listener) {
693
            GeneralUtility::callUserFunction($listener, $hookParameters, $this);
694
        }
695
696
        // Process extension static files if not done yet, but explicitly requested
697
        if (!$this->extensionStaticsProcessed && $this->processExtensionStatics) {
698
            $this->addExtensionStatics('sys_0', 'sys_0', 0, []);
699
        }
700
701
        // Add the global default TypoScript from the TYPO3_CONF_VARS
702
        $this->addDefaultTypoScript();
703
704
        $this->processIncludes();
705
    }
706
707
    /**
708
     * Checks if the template ($row) has some included templates and after including them it fills the arrays with the setup
709
     * Builds up $this->rowSum
710
     *
711
     * @param array $row A full TypoScript template record (sys_template/forged "dummy" record made from static template file)
712
     * @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.
713
     * @param int $pid The PID of the input template record
714
     * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
715
     * @param string $templateParent Parent template id (during recursive call); Same syntax as $idList ids, eg. "sys_123
716
     * @param string $includePath Specifies the path from which the template was included (used with static_includes)
717
     * @see runThroughTemplates()
718
     */
719
    public function processTemplate($row, $idList, $pid, $templateID = '', $templateParent = '', $includePath = '')
720
    {
721
        // Adding basic template record information to rowSum array
722
        $this->rowSum[] = [$row['uid'], $row['title'], $row['tstamp']];
723
        // Processing "Clear"-flags
724
        $clConst = 0;
725
        $clConf = 0;
726
        if ($row['clear']) {
727
            $clConst = $row['clear'] & 1;
728
            $clConf = $row['clear'] & 2;
729
            if ($clConst) {
730
                // Keep amount of items to stay in sync with $this->templateIncludePaths so processIncludes() does not break
731
                foreach ($this->constants as &$constantConfiguration) {
732
                    $constantConfiguration = '';
733
                }
734
                unset($constantConfiguration);
735
                $this->clearList_const = [];
736
            }
737
            if ($clConf) {
738
                // Keep amount of items to stay in sync with $this->templateIncludePaths so processIncludes() does not break
739
                foreach ($this->config as &$configConfiguration) {
740
                    $configConfiguration = '';
741
                }
742
                unset($configConfiguration);
743
                $this->hierarchyInfoToRoot = [];
744
                $this->clearList_setup = [];
745
            }
746
        }
747
        // Include files (from extensions) (#1/2)
748
        // NORMAL inclusion, The EXACT same code is found below the basedOn inclusion!!!
749
        if (!$row['includeStaticAfterBasedOn']) {
750
            $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
751
        }
752
        // Include "Based On" sys_templates:
753
        // 'basedOn' is a list of templates to include
754
        if (trim($row['basedOn'])) {
755
            // Normal Operation, which is to include the "based-on" sys_templates,
756
            // if they are not already included, and maintaining the sorting of the templates
757
            $basedOnIds = GeneralUtility::intExplode(',', $row['basedOn'], true);
758
            // skip template if it's already included
759
            foreach ($basedOnIds as $key => $basedOnId) {
760
                if (GeneralUtility::inList($idList, 'sys_' . $basedOnId)) {
761
                    unset($basedOnIds[$key]);
762
                }
763
            }
764
            if (!empty($basedOnIds)) {
765
                $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_template');
766
                $queryBuilder->setRestrictions($this->queryBuilderRestrictions);
767
                $queryResult = $queryBuilder
768
                    ->select('*')
769
                    ->from('sys_template')
770
                    ->where(
771
                        $queryBuilder->expr()->in(
772
                            'uid',
773
                            $queryBuilder->createNamedParameter($basedOnIds, Connection::PARAM_INT_ARRAY)
774
                        )
775
                    )
776
                    ->execute();
777
                // make it an associative array with the UID as key
778
                $subTemplates = [];
779
                while ($rowItem = $queryResult->fetch()) {
780
                    $subTemplates[(int)$rowItem['uid']] = $rowItem;
781
                }
782
                // Traversing list again to ensure the sorting of the templates
783
                foreach ($basedOnIds as $id) {
784
                    if (is_array($subTemplates[$id])) {
785
                        $this->versionOL($subTemplates[$id]);
786
                        $this->processTemplate($subTemplates[$id], $idList . ',sys_' . $id, $pid, 'sys_' . $id, $templateID);
787
                    }
788
                }
789
            }
790
        }
791
        // Include files (from extensions) (#2/2)
792
        if ($row['includeStaticAfterBasedOn']) {
793
            $this->includeStaticTypoScriptSources($idList, $templateID, $pid, $row);
794
        }
795
        // Creating hierarchy information; Used by backend analysis tools
796
        $this->hierarchyInfo[] = ($this->hierarchyInfoToRoot[] = [
797
            'root' => trim($row['root']),
798
            'next' => $row['nextLevel'],
799
            'clConst' => $clConst,
800
            'clConf' => $clConf,
801
            'templateID' => $templateID,
802
            'templateParent' => $templateParent,
803
            'title' => $row['title'],
804
            'uid' => $row['uid'],
805
            'pid' => $row['pid'],
806
            'configLines' => substr_count($row['config'], LF) + 1
807
        ]);
808
        // Adding the content of the fields constants (Constants) and config (Setup)
809
        $this->constants[] = $row['constants'];
810
        $this->config[] = $row['config'];
811
        $this->templateIncludePaths[] = $includePath;
812
        // For backend analysis (Template Analyser) provide the order of added constants/config template IDs
813
        $this->clearList_const[] = $templateID;
814
        $this->clearList_setup[] = $templateID;
815
        if (trim($row['sitetitle'])) {
816
            $this->sitetitle = $row['sitetitle'];
817
        }
818
        // If the template record is a Rootlevel record, set the flag and clear the template rootLine (so it starts over from this point)
819
        if (trim($row['root'])) {
820
            $this->rootId = $pid;
821
            $this->rootLine = [];
822
        }
823
        // If a template is set to be active on the next level set this internal value to point to this UID. (See runThroughTemplates())
824
        if ($row['nextLevel']) {
825
            $this->nextLevel = $row['nextLevel'];
826
        } else {
827
            $this->nextLevel = 0;
828
        }
829
    }
830
831
    /**
832
     * This function can be used to update the data of the current rootLine
833
     * e.g. when a different language is used.
834
     *
835
     * This function must not be used if there are different pages in the
836
     * rootline as before!
837
     *
838
     * @param array $fullRootLine Array containing the FULL rootline (up to the TYPO3 root)
839
     * @throws \RuntimeException If the given $fullRootLine does not contain all pages that are in the current template rootline
840
     */
841
    public function updateRootlineData($fullRootLine)
842
    {
843
        if (!is_array($this->rootLine) || empty($this->rootLine)) {
844
            return;
845
        }
846
847
        $fullRootLineByUid = [];
848
        foreach ($fullRootLine as $rootLineData) {
849
            $fullRootLineByUid[$rootLineData['uid']] = $rootLineData;
850
        }
851
852
        foreach ($this->rootLine as $level => $dataArray) {
853
            $currentUid = $dataArray['uid'];
854
855
            if (!array_key_exists($currentUid, $fullRootLineByUid)) {
856
                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);
857
            }
858
859
            $this->rootLine[$level] = $fullRootLineByUid[$currentUid];
860
        }
861
    }
862
863
    /**
864
     * Includes static template files (from extensions) for the input template record row.
865
     *
866
     * @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.
867
     * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
868
     * @param int $pid The PID of the input template record
869
     * @param array $row A full TypoScript template record
870
     * @see processTemplate()
871
     */
872
    public function includeStaticTypoScriptSources($idList, $templateID, $pid, $row)
873
    {
874
        // Call function for link rendering:
875
        $_params = [
876
            'idList' => &$idList,
877
            'templateId' => &$templateID,
878
            'pid' => &$pid,
879
            'row' => &$row
880
        ];
881
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSources'] ?? [] as $_funcRef) {
882
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
883
        }
884
        // If "Include before all static templates if root-flag is set" is set:
885
        if ($row['static_file_mode'] == 3 && strpos($templateID, 'sys_') === 0 && $row['root']) {
886
            $this->addExtensionStatics($idList, $templateID, $pid, $row);
887
        }
888
        // Static Template Files (Text files from extensions): include_static_file is a list of static files to include (from extensions)
889
        if (trim($row['include_static_file'])) {
890
            $include_static_fileArr = GeneralUtility::trimExplode(',', $row['include_static_file'], true);
891
            // Traversing list
892
            foreach ($include_static_fileArr as $ISF_file) {
893
                if (strpos($ISF_file, 'EXT:') === 0) {
894
                    list($ISF_extKey, $ISF_localPath) = explode('/', substr($ISF_file, 4), 2);
895
                    if ((string)$ISF_extKey !== '' && ExtensionManagementUtility::isLoaded($ISF_extKey) && (string)$ISF_localPath !== '') {
896
                        $ISF_localPath = rtrim($ISF_localPath, '/') . '/';
897
                        $ISF_filePath = ExtensionManagementUtility::extPath($ISF_extKey) . $ISF_localPath;
898
                        if (@is_dir($ISF_filePath)) {
899
                            $mExtKey = str_replace('_', '', $ISF_extKey . '/' . $ISF_localPath);
900
                            $subrow = [
901
                                'constants' => $this->getTypoScriptSourceFileContent($ISF_filePath, 'constants'),
902
                                'config' => $this->getTypoScriptSourceFileContent($ISF_filePath, 'setup'),
903
                                'include_static' => @file_exists(($ISF_filePath . 'include_static.txt')) ? implode(',', array_unique(GeneralUtility::intExplode(',', file_get_contents($ISF_filePath . 'include_static.txt')))) : '',
904
                                'include_static_file' => @file_exists(($ISF_filePath . 'include_static_file.txt')) ? implode(',', array_unique(explode(',', file_get_contents($ISF_filePath . 'include_static_file.txt')))) : '',
905
                                'title' => $ISF_file,
906
                                'uid' => $mExtKey
907
                            ];
908
                            $subrow = $this->prependStaticExtra($subrow);
909
                            $this->processTemplate($subrow, $idList . ',ext_' . $mExtKey, $pid, 'ext_' . $mExtKey, $templateID, $ISF_filePath);
910
                        }
911
                    }
912
                }
913
            }
914
        }
915
        // If "Default (include before if root flag is set)" is set OR
916
        // "Always include before this template record" AND root-flag are set
917
        if ($row['static_file_mode'] == 1 || $row['static_file_mode'] == 0 && substr($templateID, 0, 4) === 'sys_' && $row['root']) {
918
            $this->addExtensionStatics($idList, $templateID, $pid, $row);
919
        }
920
        // Include Static Template Records after all other TypoScript has been included.
921
        $_params = [
922
            'idList' => &$idList,
923
            'templateId' => &$templateID,
924
            'pid' => &$pid,
925
            'row' => &$row
926
        ];
927
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['includeStaticTypoScriptSourcesAtEnd'] ?? [] as $_funcRef) {
928
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
929
        }
930
    }
931
932
    /**
933
     * Retrieves the content of the first existing file by extension order.
934
     * Returns the empty string if no file is found.
935
     *
936
     * @param string $filePath The location of the file.
937
     * @param string $baseName The base file name. "constants" or "setup".
938
     * @return string
939
     */
940
    protected function getTypoScriptSourceFileContent($filePath, $baseName)
941
    {
942
        $extensions = ['.typoscript', '.ts', '.txt'];
943
        foreach ($extensions as $extension) {
944
            $fileName = $filePath . $baseName . $extension;
945
            if (@file_exists($fileName)) {
946
                return file_get_contents($fileName);
947
            }
948
        }
949
        return '';
950
    }
951
952
    /**
953
     * Adds the default TypoScript files for extensions if any.
954
     *
955
     * @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.
956
     * @param string $templateID The id of the current template. Same syntax as $idList ids, eg. "sys_123
957
     * @param int $pid The PID of the input template record
958
     * @param array $row A full TypoScript template record
959
     * @access private
960
     * @see includeStaticTypoScriptSources()
961
     */
962
    public function addExtensionStatics($idList, $templateID, $pid, $row)
0 ignored issues
show
Unused Code introduced by
The parameter $row is not used and could be removed. ( Ignorable by Annotation )

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

962
    public function addExtensionStatics($idList, $templateID, $pid, /** @scrutinizer ignore-unused */ $row)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
963
    {
964
        $this->extensionStaticsProcessed = true;
965
966
        // @todo Change to use new API
967
        foreach ($GLOBALS['TYPO3_LOADED_EXT'] as $extKey => $files) {
968
            if ((is_array($files) || $files instanceof \ArrayAccess)
969
                && (
970
                    !empty($files['ext_typoscript_constants.txt'])
971
                    || !empty($files['ext_typoscript_constants.typoscript'])
972
                    || !empty($files['ext_typoscript_setup.txt'])
973
                    || !empty($files['ext_typoscript_setup.typoscript'])
974
                )
975
            ) {
976
                $mExtKey = str_replace('_', '', $extKey);
977
                $constants = '';
978
                $config = '';
979
980
                if (!empty($files['ext_typoscript_constants.typoscript'])) {
981
                    $constants = @file_get_contents($files['ext_typoscript_constants.typoscript']);
982
                } elseif (!empty($files['ext_typoscript_constants.txt'])) {
983
                    $constants = @file_get_contents($files['ext_typoscript_constants.txt']);
984
                }
985
986
                if (!empty($files['ext_typoscript_setup.typoscript'])) {
987
                    $config = @file_get_contents($files['ext_typoscript_setup.typoscript']);
988
                } elseif (!empty($files['ext_typoscript_setup.txt'])) {
989
                    $config = @file_get_contents($files['ext_typoscript_setup.txt']);
990
                }
991
992
                $this->processTemplate(
993
                    $this->prependStaticExtra([
994
                        'constants' => $constants,
995
                        'config' => $config,
996
                        'title' => $extKey,
997
                        'uid' => $mExtKey
998
                    ]),
999
                    $idList . ',ext_' . $mExtKey,
1000
                    $pid,
1001
                    'ext_' . $mExtKey,
1002
                    $templateID,
1003
                    ExtensionManagementUtility::extPath($extKey)
1004
                );
1005
            }
1006
        }
1007
    }
1008
1009
    /**
1010
     * Appends (not prepends) additional TypoScript code to static template records/files as set in TYPO3_CONF_VARS
1011
     * 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
1012
     *
1013
     * @param array $subrow Static template record/file
1014
     * @return array Returns the input array where the values for keys "config" and "constants" may have been modified with prepended code.
1015
     * @access private
1016
     * @see addExtensionStatics(), includeStaticTypoScriptSources()
1017
     */
1018
    public function prependStaticExtra($subrow)
1019
    {
1020
        // the identifier can be "43" if coming from "static template" extension or a path like "cssstyledcontent/static/"
1021
        $identifier = $subrow['uid'];
1022
        $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.'][$identifier];
1023
        $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.'][$identifier];
1024
        // 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
1025
        if (in_array($identifier, $GLOBALS['TYPO3_CONF_VARS']['FE']['contentRenderingTemplates'], true)) {
1026
            $subrow['config'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup.']['defaultContentRendering'];
1027
            $subrow['constants'] .= $GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants.']['defaultContentRendering'];
1028
        }
1029
        return $subrow;
1030
    }
1031
1032
    /**
1033
     * Creating versioning overlay of a sys_template record.
1034
     * This will use either frontend or backend overlay functionality depending on environment.
1035
     *
1036
     * @param array $row Row to overlay (passed by reference)
1037
     */
1038
    public function versionOL(&$row)
1039
    {
1040
        // Distinguish frontend and backend call:
1041
        // To do the fronted call a full frontend is required, just checking for
1042
        // TYPO3_MODE === 'FE' is not enough. This could otherwise lead to fatals in
1043
        // eId scripts that run in frontend scope, but do not have a full blown frontend.
1044
        if (is_object($this->getTypoScriptFrontendController()) && property_exists($this->getTypoScriptFrontendController(), 'sys_page') && method_exists($this->getTypoScriptFrontendController()->sys_page, 'versionOL')) {
1045
            // Frontend
1046
            $this->getTypoScriptFrontendController()->sys_page->versionOL('sys_template', $row);
1047
        } else {
1048
            // Backend
1049
            BackendUtility::workspaceOL('sys_template', $row);
1050
        }
1051
    }
1052
1053
    /*******************************************************************
1054
     *
1055
     * Parsing TypoScript code text from Template Records into PHP array
1056
     *
1057
     *******************************************************************/
1058
    /**
1059
     * Generates the configuration array by replacing constants and parsing the whole thing.
1060
     * Depends on $this->config and $this->constants to be set prior to this! (done by processTemplate/runThroughTemplates)
1061
     *
1062
     * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser, start()
1063
     */
1064
    public function generateConfig()
1065
    {
1066
        // Add default TS for all code types
1067
        $this->addDefaultTypoScript();
1068
1069
        // Parse the TypoScript code text for include-instructions!
1070
        $this->processIncludes();
1071
        // These vars are also set lateron...
1072
        $this->setup['sitetitle'] = $this->sitetitle;
1073
        // ****************************
1074
        // Parse TypoScript Constants
1075
        // ****************************
1076
        // Initialize parser and match-condition classes:
1077
        /** @var $constants Parser\TypoScriptParser */
1078
        $constants = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
1079
        $constants->breakPointLN = (int)$this->ext_constants_BRP;
1080
        $constants->setup = $this->mergeConstantsFromPageTSconfig([]);
1081
        /** @var $matchObj ConditionMatcher */
1082
        $matchObj = GeneralUtility::makeInstance(ConditionMatcher::class);
1083
        $matchObj->setSimulateMatchConditions($this->matchAlternative);
1084
        $matchObj->setSimulateMatchResult((bool)$this->matchAll);
1085
        // Traverse constants text fields and parse them
1086
        foreach ($this->constants as $str) {
1087
            $constants->parse($str, $matchObj);
1088
        }
1089
        // Read out parse errors if any
1090
        $this->parserErrors['constants'] = $constants->errors;
1091
        // 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)
1092
        $this->flatSetup = [];
1093
        $this->flattenSetup($constants->setup, '');
1094
        // ***********************************************
1095
        // Parse TypoScript Setup (here called "config")
1096
        // ***********************************************
1097
        // Initialize parser and match-condition classes:
1098
        /** @var $config Parser\TypoScriptParser */
1099
        $config = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
1100
        $config->breakPointLN = (int)$this->ext_config_BRP;
1101
        $config->regLinenumbers = $this->ext_regLinenumbers;
1102
        $config->regComments = $this->ext_regComments;
1103
        $config->setup = $this->setup;
1104
        // Transfer information about conditions found in "Constants" and which of them returned TRUE.
1105
        $config->sections = $constants->sections;
1106
        $config->sectionsMatch = $constants->sectionsMatch;
1107
        // Traverse setup text fields and concatenate them into one, single string separated by a [GLOBAL] condition
1108
        $all = '';
1109
        foreach ($this->config as $str) {
1110
            $all .= '
1111
[GLOBAL]
1112
' . $str;
1113
        }
1114
        // Substitute constants in the Setup code:
1115
        if ($this->tt_track) {
1116
            $this->getTimeTracker()->push('Substitute Constants (' . count($this->flatSetup) . ')');
1117
        }
1118
        $all = $this->substituteConstants($all);
1119
        if ($this->tt_track) {
1120
            $this->getTimeTracker()->pull();
1121
        }
1122
1123
        // Searching for possible unsubstituted constants left (only for information)
1124
        if ($this->verbose) {
1125
            if (preg_match_all('/\\{\\$.[^}]*\\}/', $all, $constantList) > 0) {
1126
                if ($this->tt_track) {
1127
                    $this->getTimeTracker()->setTSlogMessage(implode(', ', $constantList[0]) . ': Constants may remain un-substituted!!', 2);
1128
                }
1129
            }
1130
        }
1131
1132
        // Logging the textual size of the TypoScript Setup field text with all constants substituted:
1133
        if ($this->tt_track) {
1134
            $this->getTimeTracker()->setTSlogMessage('TypoScript template size as textfile: ' . strlen($all) . ' bytes');
1135
        }
1136
        // Finally parse the Setup field TypoScript code (where constants are now substituted)
1137
        $config->parse($all, $matchObj);
1138
        // Read out parse errors if any
1139
        $this->parserErrors['config'] = $config->errors;
1140
        // Transfer the TypoScript array from the parser object to the internal $this->setup array:
1141
        $this->setup = $config->setup;
1142
        // Do the same for the constants
1143
        $this->setup_constants = $constants->setup;
1144
        // ****************************************************************
1145
        // Final processing of the $this->setup TypoScript Template array
1146
        // Basically: This is unsetting/setting of certain reserved keys.
1147
        // ****************************************************************
1148
        // 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!
1149
        unset($this->setup['sitetitle']);
1150
        unset($this->setup['sitetitle.']);
1151
        $this->setup['sitetitle'] = $this->sitetitle;
1152
        // Unsetting some vars...
1153
        unset($this->setup['types.']);
1154
        unset($this->setup['types']);
1155
        if (is_array($this->setup)) {
1156
            foreach ($this->setup as $key => $value) {
1157
                if ($value === 'PAGE') {
1158
                    // Set the typeNum of the current page object:
1159
                    if (isset($this->setup[$key . '.']['typeNum'])) {
1160
                        $typeNum = $this->setup[$key . '.']['typeNum'];
1161
                        $this->setup['types.'][$typeNum] = $key;
1162
                    } elseif (!isset($this->setup['types.'][0]) || !$this->setup['types.'][0]) {
1163
                        $this->setup['types.'][0] = $key;
1164
                    }
1165
                }
1166
            }
1167
        }
1168
        unset($this->setup['temp.']);
1169
        unset($constants);
1170
        // Storing the conditions found/matched information:
1171
        $this->sections = $config->sections;
0 ignored issues
show
Documentation Bug introduced by
It seems like $config->sections of type array<mixed,mixed|string> is incompatible with the declared type string of property $sections.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
1172
        $this->sectionsMatch = $config->sectionsMatch;
1173
    }
1174
1175
    /**
1176
     * Searching TypoScript code text (for constants and config (Setup))
1177
     * for include instructions and does the inclusion of external TypoScript files
1178
     * if needed.
1179
     *
1180
     * @see \TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser, generateConfig()
1181
     */
1182
    public function processIncludes()
1183
    {
1184
        if ($this->processIncludesHasBeenRun) {
1185
            return;
1186
        }
1187
1188
        $paths = $this->templateIncludePaths;
1189
        $files = [];
1190
        foreach ($this->constants as &$value) {
1191
            $includeData = Parser\TypoScriptParser::checkIncludeLines($value, 1, true, array_shift($paths));
1192
            $files = array_merge($files, $includeData['files']);
1193
            $value = $includeData['typoscript'];
1194
        }
1195
        unset($value);
1196
        $paths = $this->templateIncludePaths;
1197
        foreach ($this->config as &$value) {
1198
            $includeData = Parser\TypoScriptParser::checkIncludeLines($value, 1, true, array_shift($paths));
1199
            $files = array_merge($files, $includeData['files']);
1200
            $value = $includeData['typoscript'];
1201
        }
1202
        unset($value);
1203
1204
        if (!empty($files)) {
1205
            $files = array_unique($files);
1206
            foreach ($files as $file) {
1207
                $this->rowSum[] = [$file, filemtime($file)];
1208
            }
1209
        }
1210
1211
        $this->processIncludesHasBeenRun = true;
1212
    }
1213
1214
    /**
1215
     * Loads Page TSconfig until the outermost template record and parses the configuration - if TSFE.constants object path is found it is merged with the default data in here!
1216
     *
1217
     * @param array $constArray Constants array, default input.
1218
     * @return array Constants array, modified
1219
     * @todo Apply caching to the parsed Page TSconfig. This is done in the other similar functions for both frontend and backend. However, since this functions works for BOTH frontend and backend we will have to either write our own local caching function or (more likely) detect if we are in FE or BE and use caching functions accordingly. Not having caching affects mostly the backend modules inside the "Template" module since the overhead in the frontend is only seen when TypoScript templates are parsed anyways (after which point they are cached anyways...)
1220
     */
1221
    public function mergeConstantsFromPageTSconfig($constArray)
1222
    {
1223
        $TSdataArray = [];
1224
        // Setting default configuration:
1225
        $TSdataArray[] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];
1226
        for ($a = 0; $a <= $this->outermostRootlineIndexWithTemplate; $a++) {
1227
            if (trim($this->absoluteRootLine[$a]['tsconfig_includes'])) {
1228
                $includeTsConfigFileList = GeneralUtility::trimExplode(
1229
                    ',',
1230
                    $this->absoluteRootLine[$a]['tsconfig_includes'],
1231
                    true
1232
                );
1233
1234
                $TSdataArray = $this->mergeConstantsFromIncludedTsConfigFiles($includeTsConfigFileList, $TSdataArray);
1235
            }
1236
            $TSdataArray[] = $this->absoluteRootLine[$a]['TSconfig'];
1237
        }
1238
        // Parsing the user TS (or getting from cache)
1239
        $TSdataArray = Parser\TypoScriptParser::checkIncludeLines_array($TSdataArray);
1240
        $userTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
1241
        /** @var $parseObj Parser\TypoScriptParser */
1242
        $parseObj = GeneralUtility::makeInstance(Parser\TypoScriptParser::class);
1243
        $parseObj->parse($userTS);
1244
        if (is_array($parseObj->setup['TSFE.']['constants.'])) {
1245
            ArrayUtility::mergeRecursiveWithOverrule($constArray, $parseObj->setup['TSFE.']['constants.']);
1246
        }
1247
1248
        return $constArray;
1249
    }
1250
1251
    /**
1252
     * Reads TSconfig defined in external files and appends it to the given TSconfig array (in this case only constants)
1253
     *
1254
     * @param array $filesToInclude The files to read constants from
1255
     * @param array $TSdataArray The TSconfig array the constants should be appended to
1256
     * @return array The TSconfig with the included constants appended
1257
     */
1258
    protected function mergeConstantsFromIncludedTsConfigFiles($filesToInclude, $TSdataArray)
1259
    {
1260
        foreach ($filesToInclude as $key => $file) {
1261
            if (strpos($file, 'EXT:') !== 0) {
1262
                continue;
1263
            }
1264
1265
            list($extensionKey, $filePath) = explode('/', substr($file, 4), 2);
1266
1267
            if ((string)$extensionKey === '' || !ExtensionManagementUtility::isLoaded($extensionKey)) {
1268
                continue;
1269
            }
1270
            if ((string)$filePath == '') {
1271
                continue;
1272
            }
1273
1274
            $tsConfigFile = ExtensionManagementUtility::extPath($extensionKey) . $filePath;
1275
            if (file_exists($tsConfigFile)) {
1276
                $TSdataArray[] = file_get_contents($tsConfigFile);
1277
            }
1278
        }
1279
1280
        return $TSdataArray;
1281
    }
1282
1283
    /**
1284
     * This flattens a hierarchical TypoScript array to $this->flatSetup
1285
     *
1286
     * @param array $setupArray TypoScript array
1287
     * @param string $prefix Prefix to the object path. Used for recursive calls to this function.
1288
     * @see generateConfig()
1289
     */
1290
    public function flattenSetup($setupArray, $prefix)
1291
    {
1292
        if (is_array($setupArray)) {
1293
            foreach ($setupArray as $key => $val) {
1294
                if (is_array($val)) {
1295
                    $this->flattenSetup($val, $prefix . $key);
1296
                } else {
1297
                    $this->flatSetup[$prefix . $key] = $val;
1298
                }
1299
            }
1300
        }
1301
    }
1302
1303
    /**
1304
     * Substitutes the constants from $this->flatSetup in the text string $all
1305
     *
1306
     * @param string $all TypoScript code text string
1307
     * @return string The processed string with all constants found in $this->flatSetup as key/value pairs substituted.
1308
     * @see generateConfig(), flattenSetup()
1309
     */
1310
    public function substituteConstants($all)
1311
    {
1312
        if ($this->tt_track) {
1313
            $this->getTimeTracker()->setTSlogMessage('Constants to substitute: ' . count($this->flatSetup));
1314
        }
1315
        $noChange = false;
1316
        // Recursive substitution of constants (up to 10 nested levels)
1317
        for ($i = 0; $i < 10 && !$noChange; $i++) {
1318
            $old_all = $all;
1319
            $all = preg_replace_callback('/\\{\\$(.[^}]*)\\}/', [$this, 'substituteConstantsCallBack'], $all);
1320
            if ($old_all == $all) {
1321
                $noChange = true;
1322
            }
1323
        }
1324
        return $all;
1325
    }
1326
1327
    /**
1328
     * Call back method for preg_replace_callback in substituteConstants
1329
     *
1330
     * @param array $matches Regular expression matches
1331
     * @return string Replacement
1332
     * @see substituteConstants()
1333
     */
1334
    public function substituteConstantsCallBack($matches)
1335
    {
1336
        // Replace {$CONST} if found in $this->flatSetup, else leave unchanged
1337
        return isset($this->flatSetup[$matches[1]]) && !is_array($this->flatSetup[$matches[1]]) ? $this->flatSetup[$matches[1]] : $matches[0];
1338
    }
1339
1340
    /*******************************************************************
1341
     *
1342
     * Various API functions, used from elsewhere in the frontend classes
1343
     *
1344
     *******************************************************************/
1345
1346
    /**
1347
     * Returns the reference used for the frontend inclusion, checks against allowed paths for inclusion.
1348
     *
1349
     * @param string $fileFromSetup TypoScript "resource" data type value.
1350
     * @return string|null Resulting filename, is either a full absolute URL or a relative path. Returns NULL if invalid filename or a directory is given
1351
     */
1352
    public function getFileName($fileFromSetup)
1353
    {
1354
        $file = trim($fileFromSetup);
1355
        if (!$file) {
1356
            return null;
1357
        }
1358
        if (strpos($file, '../') !== false) {
1359
            if ($this->tt_track) {
1360
                $this->getTimeTracker()->setTSlogMessage('File path "' . $file . '" contained illegal string "../"!', 3);
1361
            }
1362
            return null;
1363
        }
1364
        // Cache
1365
        $hash = md5($file);
1366
        if (isset($this->fileCache[$hash])) {
1367
            return $this->fileCache[$hash];
1368
        }
1369
1370
        // if this is an URL, it can be returned directly
1371
        $urlScheme = parse_url($file, PHP_URL_SCHEME);
1372
        if ($urlScheme === 'https' || $urlScheme === 'http' || is_file(PATH_site . $file)) {
1373
            return $file;
1374
        }
1375
1376
        // this call also resolves EXT:myext/ files
1377
        $file = GeneralUtility::getFileAbsFileName($file);
1378
        if (!$file) {
1379
            if ($this->tt_track) {
1380
                $this->getTimeTracker()->setTSlogMessage('File "' . $fileFromSetup . '" was not found!', 3);
1381
            }
1382
            return null;
1383
        }
1384
1385
        $file = PathUtility::stripPathSitePrefix($file);
1386
1387
        // Check if the found file is in the allowed paths
1388
        foreach ($this->allowedPaths as $val) {
1389
            if (GeneralUtility::isFirstPartOfStr($file, $val)) {
1390
                $this->fileCache[$hash] = $file;
1391
                return $file;
1392
            }
1393
        }
1394
1395
        if ($this->tt_track) {
1396
            $this->getTimeTracker()->setTSlogMessage('"' . $file . '" was not located in the allowed paths: (' . implode(',', $this->allowedPaths) . ')', 3);
1397
        }
1398
        return null;
1399
    }
1400
1401
    /**
1402
     * Compiles the content for the page <title> tag.
1403
     *
1404
     * @param string $pageTitle The input title string, typically the "title" field of a page's record.
1405
     * @param bool $noTitle If set, then only the site title is outputted (from $this->setup['sitetitle'])
1406
     * @param bool $showTitleFirst If set, then "sitetitle" and $title is swapped
1407
     * @param string $pageTitleSeparator an alternative to the ": " as the separator between site title and page title
1408
     * @return string The page title on the form "[sitetitle]: [input-title]". Not htmlspecialchar()'ed.
1409
     * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::tempPageCacheContent(), \TYPO3\CMS\Frontend\Page\PageGenerator::renderContentWithHeader()
1410
     * @deprecated since TYPO3 v9, will be removed in TYPO3 v10, use $TSFE->generatePageTitle() instead.
1411
     */
1412
    public function printTitle($pageTitle, $noTitle = false, $showTitleFirst = false, $pageTitleSeparator = '')
1413
    {
1414
        trigger_error('This method will be removed in TYPO3 v10. Title tag generation has been moved into TSFE itself, re-implement this method if you need to, otherwise use TSFE->generatePageTitle() for full usage.', E_USER_DEPRECATED);
1415
        $siteTitle = trim($this->setup['sitetitle']);
1416
        $pageTitle = $noTitle ? '' : $pageTitle;
1417
        if ($showTitleFirst) {
1418
            $temp = $siteTitle;
1419
            $siteTitle = $pageTitle;
1420
            $pageTitle = $temp;
1421
        }
1422
        // only show a separator if there are both site title and page title
1423
        if ($pageTitle === '' || $siteTitle === '') {
1424
            $pageTitleSeparator = '';
1425
        } elseif (empty($pageTitleSeparator)) {
1426
            // use the default separator if non given
1427
            $pageTitleSeparator = ': ';
1428
        }
1429
        return $siteTitle . $pageTitleSeparator . $pageTitle;
1430
    }
1431
1432
    /**
1433
     * Returns the level of the given page in the rootline - Multiple pages can be given by separating the UIDs by comma.
1434
     *
1435
     * @param string $list A list of UIDs for which the rootline-level should get returned
1436
     * @return int The level in the rootline. If more than one page was given the lowest level will get returned.
1437
     */
1438
    public function getRootlineLevel($list)
1439
    {
1440
        $idx = 0;
1441
        foreach ($this->rootLine as $page) {
1442
            if (GeneralUtility::inList($list, $page['uid'])) {
1443
                return $idx;
1444
            }
1445
            $idx++;
1446
        }
1447
        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...
1448
    }
1449
1450
    /*******************************************************************
1451
     *
1452
     * Functions for creating links
1453
     *
1454
     *******************************************************************/
1455
    /**
1456
     * The mother of all functions creating links/URLs etc in a TypoScript environment.
1457
     * See the references below.
1458
     * Basically this function takes care of issues such as type,id,alias and Mount Points, URL rewriting (through hooks), M5/B6 encoded parameters etc.
1459
     * It is important to pass all links created through this function since this is the guarantee that globally configured settings for link creating are observed and that your applications will conform to the various/many configuration options in TypoScript Templates regarding this.
1460
     *
1461
     * @param array $page The page record of the page to which we are creating a link. Needed due to fields like uid, alias, target, title and sectionIndex_uid.
1462
     * @param string $oTarget Default target string to use IF not $page['target'] is set.
1463
     * @param bool $no_cache If set, then the "&no_cache=1" parameter is included in the URL.
1464
     * @param string $_ not in use anymore
1465
     * @param array $overrideArray Array with overriding values for the $page array.
1466
     * @param string $addParams Additional URL parameters to set in the URL. Syntax is "&foo=bar&foo2=bar2" etc. Also used internally to add parameters if needed.
1467
     * @param string $typeOverride If you set this value to something else than a blank string, then the typeNumber used in the link will be forced to this value. Normally the typeNum is based on the target set OR on $this->getTypoScriptFrontendController()->config['config']['forceTypeValue'] if found.
1468
     * @param string $targetDomain The target Doamin, if any was detected in typolink
1469
     * @return array Contains keys like "totalURL", "url", "sectionIndex", "linkVars", "no_cache", "type", "target" of which "totalURL" is normally the value you would use while the other keys contains various parts that was used to construct "totalURL
1470
     * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::typoLink(), \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject::link()
1471
     */
1472
    public function linkData($page, $oTarget, $no_cache, $_ = null, $overrideArray = null, $addParams = '', $typeOverride = '', $targetDomain = '')
1473
    {
1474
        $LD = [];
1475
        // Overriding some fields in the page record and still preserves the values by adding them as parameters. Little strange function.
1476
        if (is_array($overrideArray)) {
1477
            foreach ($overrideArray as $theKey => $theNewVal) {
1478
                $addParams .= '&real_' . $theKey . '=' . rawurlencode($page[$theKey]);
1479
                $page[$theKey] = $theNewVal;
1480
            }
1481
        }
1482
        // Adding Mount Points, "&MP=", parameter for the current page if any is set:
1483
        if (!strstr($addParams, '&MP=')) {
1484
            // Looking for hardcoded defaults:
1485
            if (trim($this->getTypoScriptFrontendController()->MP_defaults[$page['uid']])) {
1486
                $addParams .= '&MP=' . rawurlencode(trim($this->getTypoScriptFrontendController()->MP_defaults[$page['uid']]));
1487
            } elseif ($this->getTypoScriptFrontendController()->config['config']['MP_mapRootPoints']) {
1488
                // Else look in automatically created map:
1489
                $m = $this->getFromMPmap($page['uid']);
1490
                if ($m) {
1491
                    $addParams .= '&MP=' . rawurlencode($m);
1492
                }
1493
            }
1494
        }
1495
        // Setting ID/alias:
1496
        $script = 'index.php';
1497
        if ($page['alias']) {
1498
            $LD['url'] = $script . '?id=' . rawurlencode($page['alias']);
1499
        } else {
1500
            $LD['url'] = $script . '?id=' . $page['uid'];
1501
        }
1502
        // Setting target
1503
        $LD['target'] = trim($page['target']) ?: $oTarget;
1504
        // typeNum
1505
        $typeNum = $this->setup[$LD['target'] . '.']['typeNum'];
1506
        if (!MathUtility::canBeInterpretedAsInteger($typeOverride) && (int)$this->getTypoScriptFrontendController()->config['config']['forceTypeValue']) {
1507
            $typeOverride = (int)$this->getTypoScriptFrontendController()->config['config']['forceTypeValue'];
1508
        }
1509
        if ((string)$typeOverride !== '') {
1510
            $typeNum = $typeOverride;
1511
        }
1512
        // Override...
1513
        if ($typeNum) {
1514
            $LD['type'] = '&type=' . (int)$typeNum;
1515
        } else {
1516
            $LD['type'] = '';
1517
        }
1518
        // Preserving the type number.
1519
        $LD['orig_type'] = $LD['type'];
1520
        // noCache
1521
        $LD['no_cache'] = $no_cache ? '&no_cache=1' : '';
1522
        // linkVars
1523
        if ($addParams) {
1524
            $LD['linkVars'] = GeneralUtility::implodeArrayForUrl('', GeneralUtility::explodeUrl2Array($this->getTypoScriptFrontendController()->linkVars . $addParams), '', false, true);
1525
        } else {
1526
            $LD['linkVars'] = $this->getTypoScriptFrontendController()->linkVars;
1527
        }
1528
        // Add absRefPrefix if exists.
1529
        $LD['url'] = $this->getTypoScriptFrontendController()->absRefPrefix . $LD['url'];
1530
        // If the special key 'sectionIndex_uid' (added 'manually' in tslib/menu.php to the page-record) is set, then the link jumps directly to a section on the page.
1531
        $LD['sectionIndex'] = $page['sectionIndex_uid'] ? '#c' . $page['sectionIndex_uid'] : '';
1532
        // Compile the normal total url
1533
        $LD['totalURL'] = rtrim($LD['url'] . $LD['type'] . $LD['no_cache'] . $LD['linkVars'] . $this->getTypoScriptFrontendController()->getMethodUrlIdToken, '?') . $LD['sectionIndex'];
1534
        // Call post processing function for link rendering:
1535
        $_params = [
1536
            'LD' => &$LD,
1537
            'args' => ['page' => $page, 'oTarget' => $oTarget, 'no_cache' => $no_cache, 'script' => $script, 'overrideArray' => $overrideArray, 'addParams' => $addParams, 'typeOverride' => $typeOverride, 'targetDomain' => $targetDomain],
1538
            'typeNum' => $typeNum
1539
        ];
1540
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_tstemplate.php']['linkData-PostProc'] ?? [] as $_funcRef) {
1541
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1542
        }
1543
        // Return the LD-array
1544
        return $LD;
1545
    }
1546
1547
    /**
1548
     * Initializes the automatically created MPmap coming from the "config.MP_mapRootPoints" setting
1549
     * Can be called many times with overhead only the first time since then the map is generated and cached in memory.
1550
     *
1551
     * @param int $pageId Page id to return MPvar value for.
1552
     * @return string
1553
     * @see initMPmap_create()
1554
     * @todo Implement some caching of the result between hits. (more than just the memory caching used here)
1555
     */
1556
    public function getFromMPmap($pageId = 0)
1557
    {
1558
        // Create map if not found already:
1559
        if (!is_array($this->MPmap)) {
1560
            $this->MPmap = [];
0 ignored issues
show
Documentation Bug introduced by
It seems like array() of type array is incompatible with the declared type string of property $MPmap.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
1561
            $rootPoints = GeneralUtility::trimExplode(',', strtolower($this->getTypoScriptFrontendController()->config['config']['MP_mapRootPoints']), true);
1562
            // Traverse rootpoints:
1563
            foreach ($rootPoints as $p) {
1564
                $initMParray = [];
1565
                if ($p === 'root') {
1566
                    $p = $this->rootLine[0]['uid'];
1567
                    if ($this->rootLine[0]['_MOUNT_OL'] && $this->rootLine[0]['_MP_PARAM']) {
1568
                        $initMParray[] = $this->rootLine[0]['_MP_PARAM'];
1569
                    }
1570
                }
1571
                $this->initMPmap_create($p, $initMParray);
1572
            }
1573
        }
1574
        // Finding MP var for Page ID:
1575
        if ($pageId) {
1576
            if (is_array($this->MPmap[$pageId]) && !empty($this->MPmap[$pageId])) {
1577
                return implode(',', $this->MPmap[$pageId]);
1578
            }
1579
        }
1580
        return '';
1581
    }
1582
1583
    /**
1584
     * Creating MPmap for a certain ID root point.
1585
     *
1586
     * @param int $id Root id from which to start map creation.
1587
     * @param array $MP_array MP_array passed from root page.
1588
     * @param int $level Recursion brake. Incremented for each recursive call. 20 is the limit.
1589
     * @see getFromMPvar()
1590
     */
1591
    public function initMPmap_create($id, $MP_array = [], $level = 0)
1592
    {
1593
        $id = (int)$id;
1594
        if ($id <= 0) {
1595
            return;
1596
        }
1597
        // First level, check id
1598
        if (!$level) {
1599
            // Find mount point if any:
1600
            $mount_info = $this->getTypoScriptFrontendController()->sys_page->getMountPointInfo($id);
1601
            // Overlay mode:
1602
            if (is_array($mount_info) && $mount_info['overlay']) {
1603
                $MP_array[] = $mount_info['MPvar'];
1604
                $id = $mount_info['mount_pid'];
1605
            }
1606
            // Set mapping information for this level:
1607
            $this->MPmap[$id] = $MP_array;
1608
            // Normal mode:
1609
            if (is_array($mount_info) && !$mount_info['overlay']) {
1610
                $MP_array[] = $mount_info['MPvar'];
1611
                $id = $mount_info['mount_pid'];
1612
            }
1613
        }
1614
        if ($id && $level < 20) {
1615
            $nextLevelAcc = [];
1616
            // Select and traverse current level pages:
1617
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('pages');
1618
            $queryBuilder->getRestrictions()
1619
                ->removeAll()
1620
                ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1621
            $queryResult = $queryBuilder
1622
                ->select('uid', 'pid', 'doktype', 'mount_pid', 'mount_pid_ol')
1623
                ->from('pages')
1624
                ->where(
1625
                    $queryBuilder->expr()->eq(
1626
                        'pid',
1627
                        $queryBuilder->createNamedParameter($id, \PDO::PARAM_INT)
1628
                    ),
1629
                    $queryBuilder->expr()->neq(
1630
                        'doktype',
1631
                        $queryBuilder->createNamedParameter(PageRepository::DOKTYPE_RECYCLER, \PDO::PARAM_INT)
1632
                    ),
1633
                    $queryBuilder->expr()->neq(
1634
                        'doktype',
1635
                        $queryBuilder->createNamedParameter(PageRepository::DOKTYPE_BE_USER_SECTION, \PDO::PARAM_INT)
1636
                    )
1637
                )->execute();
1638
            while ($row = $queryResult->fetch()) {
1639
                // Find mount point if any:
1640
                $next_id = $row['uid'];
1641
                $next_MP_array = $MP_array;
1642
                $mount_info = $this->getTypoScriptFrontendController()->sys_page->getMountPointInfo($next_id, $row);
1643
                // Overlay mode:
1644
                if (is_array($mount_info) && $mount_info['overlay']) {
1645
                    $next_MP_array[] = $mount_info['MPvar'];
1646
                    $next_id = $mount_info['mount_pid'];
1647
                }
1648
                if (!isset($this->MPmap[$next_id])) {
1649
                    // Set mapping information for this level:
1650
                    $this->MPmap[$next_id] = $next_MP_array;
1651
                    // Normal mode:
1652
                    if (is_array($mount_info) && !$mount_info['overlay']) {
1653
                        $next_MP_array[] = $mount_info['MPvar'];
1654
                        $next_id = $mount_info['mount_pid'];
1655
                    }
1656
                    // Register recursive call
1657
                    // (have to do it this way since ALL of the current level should be registered BEFORE the sublevel at any time)
1658
                    $nextLevelAcc[] = [$next_id, $next_MP_array];
1659
                }
1660
            }
1661
            // Call recursively, if any:
1662
            foreach ($nextLevelAcc as $pSet) {
1663
                $this->initMPmap_create($pSet[0], $pSet[1], $level + 1);
1664
            }
1665
        }
1666
    }
1667
1668
    /**
1669
     * Adds the TypoScript from the global array.
1670
     * The class property isDefaultTypoScriptAdded ensures
1671
     * that the adding only happens once.
1672
     *
1673
     * @see isDefaultTypoScriptAdded
1674
     */
1675
    protected function addDefaultTypoScript()
1676
    {
1677
        // Add default TS for all code types, if not done already
1678
        if (!$this->isDefaultTypoScriptAdded) {
1679
            // adding default setup and constants
1680
            // defaultTypoScript_setup is *very* unlikely to be empty
1681
            // the count of elements in ->constants, ->config and ->templateIncludePaths have to be in sync
1682
            array_unshift($this->constants, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_constants']);
1683
            array_unshift($this->config, (string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup']);
1684
            array_unshift($this->templateIncludePaths, '');
1685
            // prepare a proper entry to hierachyInfo (used by TemplateAnalyzer in BE)
1686
            $rootTemplateId = $this->hierarchyInfo[count($this->hierarchyInfo)-1]['templateID'];
1687
            $defaultTemplateInfo = [
1688
                'root' => '',
1689
                'next' => '',
1690
                'clConst' => '',
1691
                'clConf' => '',
1692
                'templateID' => '_defaultTypoScript_',
1693
                'templateParent' => $rootTemplateId,
1694
                'title' => 'SYS:TYPO3_CONF_VARS:FE:defaultTypoScript',
1695
                'uid' => '_defaultTypoScript_',
1696
                'pid' => '',
1697
                'configLines' => substr_count((string)$GLOBALS['TYPO3_CONF_VARS']['FE']['defaultTypoScript_setup'], LF) + 1
1698
            ];
1699
            // push info to information arrays used in BE by TemplateTools (Analyzer)
1700
            array_unshift($this->clearList_const, $defaultTemplateInfo['uid']);
1701
            array_unshift($this->clearList_setup, $defaultTemplateInfo['uid']);
1702
            array_unshift($this->hierarchyInfo, $defaultTemplateInfo);
1703
            $this->isDefaultTypoScriptAdded = true;
1704
        }
1705
    }
1706
1707
    /**
1708
     * @return TypoScriptFrontendController
1709
     */
1710
    protected function getTypoScriptFrontendController()
1711
    {
1712
        return $GLOBALS['TSFE'];
1713
    }
1714
1715
    /**
1716
     * @return TimeTracker
1717
     */
1718
    protected function getTimeTracker()
1719
    {
1720
        return GeneralUtility::makeInstance(TimeTracker::class);
1721
    }
1722
1723
    /**
1724
     * Returns data stored for the hash string in the cache "cache_hash"
1725
     * used to store the parsed TypoScript template structures.
1726
     *
1727
     * @param string $identifier The hash-string which was used to store the data value
1728
     * @return mixed The data from the cache
1729
     */
1730
    protected function getCacheEntry($identifier)
1731
    {
1732
        return GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash')->get($identifier);
1733
    }
1734
1735
    /**
1736
     * Stores $data in the 'cache_hash' cache with the hash key $identifier
1737
     *
1738
     * @param string $identifier 32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
1739
     * @param mixed $data The data to store
1740
     * @param string $tag Is just a textual identification in order to inform about the content
1741
     */
1742
    protected function setCacheEntry($identifier, $data, $tag)
1743
    {
1744
        GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash')->set($identifier, $data, ['ident_' . $tag], 0);
1745
    }
1746
}
1747