Completed
Push — master ( 2ae98b...5fe071 )
by
unknown
18:27
created

getFromCache_queryRow()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 0
dl 0
loc 6
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\Frontend\Controller;
17
18
use Psr\Http\Message\ResponseInterface;
19
use Psr\Http\Message\ServerRequestInterface;
20
use Psr\Log\LoggerAwareInterface;
21
use Psr\Log\LoggerAwareTrait;
22
use TYPO3\CMS\Backend\FrontendBackendUserAuthentication;
23
use TYPO3\CMS\Core\Cache\CacheManager;
24
use TYPO3\CMS\Core\Charset\CharsetConverter;
25
use TYPO3\CMS\Core\Charset\UnknownCharsetException;
26
use TYPO3\CMS\Core\Configuration\Loader\PageTsConfigLoader;
27
use TYPO3\CMS\Core\Configuration\Parser\PageTsConfigParser;
28
use TYPO3\CMS\Core\Context\Context;
29
use TYPO3\CMS\Core\Context\DateTimeAspect;
30
use TYPO3\CMS\Core\Context\LanguageAspect;
31
use TYPO3\CMS\Core\Context\LanguageAspectFactory;
32
use TYPO3\CMS\Core\Context\UserAspect;
33
use TYPO3\CMS\Core\Context\VisibilityAspect;
34
use TYPO3\CMS\Core\Context\WorkspaceAspect;
35
use TYPO3\CMS\Core\Core\Environment;
36
use TYPO3\CMS\Core\Database\Connection;
37
use TYPO3\CMS\Core\Database\ConnectionPool;
38
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
39
use TYPO3\CMS\Core\Database\Query\Restriction\EndTimeRestriction;
40
use TYPO3\CMS\Core\Database\Query\Restriction\StartTimeRestriction;
41
use TYPO3\CMS\Core\Domain\Repository\PageRepository;
42
use TYPO3\CMS\Core\Error\Http\PageNotFoundException;
43
use TYPO3\CMS\Core\Error\Http\ServiceUnavailableException;
44
use TYPO3\CMS\Core\Error\Http\ShortcutTargetPageNotFoundException;
45
use TYPO3\CMS\Core\Exception\Page\RootLineException;
46
use TYPO3\CMS\Core\Http\ImmediateResponseException;
47
use TYPO3\CMS\Core\Http\ServerRequestFactory;
48
use TYPO3\CMS\Core\Localization\LanguageService;
49
use TYPO3\CMS\Core\Locking\Exception\LockAcquireWouldBlockException;
50
use TYPO3\CMS\Core\Locking\LockFactory;
51
use TYPO3\CMS\Core\Locking\LockingStrategyInterface;
52
use TYPO3\CMS\Core\Page\AssetCollector;
53
use TYPO3\CMS\Core\Page\PageRenderer;
54
use TYPO3\CMS\Core\PageTitle\PageTitleProviderManager;
55
use TYPO3\CMS\Core\Resource\Exception;
56
use TYPO3\CMS\Core\Resource\StorageRepository;
57
use TYPO3\CMS\Core\Routing\PageArguments;
58
use TYPO3\CMS\Core\Site\Entity\Site;
59
use TYPO3\CMS\Core\Site\Entity\SiteInterface;
60
use TYPO3\CMS\Core\Site\Entity\SiteLanguage;
61
use TYPO3\CMS\Core\TimeTracker\TimeTracker;
62
use TYPO3\CMS\Core\Type\Bitmask\Permission;
63
use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
64
use TYPO3\CMS\Core\TypoScript\TemplateService;
65
use TYPO3\CMS\Core\Utility\ArrayUtility;
66
use TYPO3\CMS\Core\Utility\GeneralUtility;
67
use TYPO3\CMS\Core\Utility\HttpUtility;
68
use TYPO3\CMS\Core\Utility\MathUtility;
69
use TYPO3\CMS\Core\Utility\PathUtility;
70
use TYPO3\CMS\Core\Utility\RootlineUtility;
71
use TYPO3\CMS\Frontend\Aspect\PreviewAspect;
72
use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
73
use TYPO3\CMS\Frontend\Configuration\TypoScript\ConditionMatching\ConditionMatcher;
74
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
75
use TYPO3\CMS\Frontend\Page\CacheHashCalculator;
76
use TYPO3\CMS\Frontend\Page\PageAccessFailureReasons;
77
use TYPO3\CMS\Frontend\Resource\FilePathSanitizer;
78
79
/**
80
 * Class for the built TypoScript based frontend. Instantiated in
81
 * \TYPO3\CMS\Frontend\Http\RequestHandler as the global object TSFE.
82
 *
83
 * Main frontend class, instantiated in \TYPO3\CMS\Frontend\Http\RequestHandler
84
 * as the global object TSFE.
85
 *
86
 * This class has a lot of functions and internal variable which are used from
87
 * \TYPO3\CMS\Frontend\Http\RequestHandler
88
 *
89
 * The class is instantiated as $GLOBALS['TSFE'] in \TYPO3\CMS\Frontend\Http\RequestHandler.
90
 *
91
 * The use of this class should be inspired by the order of function calls as
92
 * found in \TYPO3\CMS\Frontend\Http\RequestHandler.
93
 */
94
class TypoScriptFrontendController implements LoggerAwareInterface
95
{
96
    use LoggerAwareTrait;
97
98
    /**
99
     * The page id (int)
100
     * @var string
101
     */
102
    public $id = '';
103
104
    /**
105
     * The type (read-only)
106
     * @var int|string
107
     */
108
    public $type = '';
109
110
    /**
111
     * @var Site
112
     */
113
    protected $site;
114
115
    /**
116
     * @var SiteLanguage
117
     */
118
    protected $language;
119
120
    /**
121
     * @var PageArguments
122
     * @internal
123
     */
124
    protected $pageArguments;
125
126
    /**
127
     * Page will not be cached. Write only TRUE. Never clear value (some other
128
     * code might have reasons to set it TRUE).
129
     * @var bool
130
     */
131
    public $no_cache = false;
132
133
    /**
134
     * The rootLine (all the way to tree root, not only the current site!)
135
     * @var array
136
     */
137
    public $rootLine = [];
138
139
    /**
140
     * The pagerecord
141
     * @var array
142
     */
143
    public $page = [];
144
145
    /**
146
     * This will normally point to the same value as id, but can be changed to
147
     * point to another page from which content will then be displayed instead.
148
     * @var int
149
     */
150
    public $contentPid = 0;
151
152
    /**
153
     * Gets set when we are processing a page of type mounpoint with enabled overlay in getPageAndRootline()
154
     * Used later in checkPageForMountpointRedirect() to determine the final target URL where the user
155
     * should be redirected to.
156
     *
157
     * @var array|null
158
     */
159
    protected $originalMountPointPage;
160
161
    /**
162
     * Gets set when we are processing a page of type shortcut in the early stages
163
     * of the request when we do not know about languages yet, used later in the request
164
     * to determine the correct shortcut in case a translation changes the shortcut
165
     * target
166
     * @var array|null
167
     * @see checkTranslatedShortcut()
168
     */
169
    protected $originalShortcutPage;
170
171
    /**
172
     * sys_page-object, pagefunctions
173
     *
174
     * @var PageRepository|string
175
     */
176
    public $sys_page = '';
177
178
    /**
179
     * Is set to 1 if a pageNotFound handler could have been called.
180
     * @var int
181
     * @internal
182
     */
183
    public $pageNotFound = 0;
184
185
    /**
186
     * Array containing a history of why a requested page was not accessible.
187
     * @var array
188
     */
189
    protected $pageAccessFailureHistory = [];
190
191
    /**
192
     * @var string
193
     * @internal
194
     */
195
    public $MP = '';
196
197
    /**
198
     * The frontend user
199
     *
200
     * @var FrontendUserAuthentication
201
     */
202
    public $fe_user;
203
204
    /**
205
     * Shows whether logins are allowed in branch
206
     * @var bool
207
     */
208
    protected $loginAllowedInBranch = true;
209
210
    /**
211
     * Shows specific mode (all or groups)
212
     * @var string
213
     * @internal
214
     */
215
    protected $loginAllowedInBranch_mode = '';
216
217
    /**
218
     * Value that contains the simulated usergroup if any
219
     * @var int
220
     * @internal only to be used in AdminPanel, and within TYPO3 Core
221
     */
222
    public $simUserGroup = 0;
223
224
    /**
225
     * "CONFIG" object from TypoScript. Array generated based on the TypoScript
226
     * configuration of the current page. Saved with the cached pages.
227
     * @var array
228
     */
229
    public $config = [];
230
231
    /**
232
     * The TypoScript template object. Used to parse the TypoScript template
233
     *
234
     * @var TemplateService
235
     */
236
    public $tmpl;
237
238
    /**
239
     * Is set to the time-to-live time of cached pages. Default is 60*60*24, which is 24 hours.
240
     *
241
     * @var int
242
     * @internal
243
     */
244
    protected $cacheTimeOutDefault = 86400;
245
246
    /**
247
     * Set internally if cached content is fetched from the database.
248
     *
249
     * @var bool
250
     * @internal
251
     */
252
    protected $cacheContentFlag = false;
253
254
    /**
255
     * Set to the expire time of cached content
256
     * @var int
257
     * @internal
258
     */
259
    protected $cacheExpires = 0;
260
261
    /**
262
     * Set if cache headers allowing caching are sent.
263
     * @var bool
264
     * @internal
265
     */
266
    protected $isClientCachable = false;
267
268
    /**
269
     * Used by template fetching system. This array is an identification of
270
     * the template. If $this->all is empty it's because the template-data is not
271
     * cached, which it must be.
272
     * @var array
273
     * @internal
274
     */
275
    public $all = [];
276
277
    /**
278
     * Toplevel - objArrayName, eg 'page'
279
     * @var string
280
     * @internal should only be used by TYPO3 Core
281
     */
282
    public $sPre = '';
283
284
    /**
285
     * TypoScript configuration of the page-object pointed to by sPre.
286
     * $this->tmpl->setup[$this->sPre.'.']
287
     * @var array|string
288
     * @internal should only be used by TYPO3 Core
289
     */
290
    public $pSetup = '';
291
292
    /**
293
     * This hash is unique to the template, the $this->id and $this->type vars and
294
     * the list of groups. Used to get and later store the cached data
295
     * @var string
296
     * @internal
297
     */
298
    public $newHash = '';
299
300
    /**
301
     * This flag is set before the page is generated IF $this->no_cache is set. If this
302
     * flag is set after the page content was generated, $this->no_cache is forced to be set.
303
     * This is done in order to make sure that PHP code from Plugins / USER scripts does not falsely
304
     * clear the no_cache flag.
305
     * @var bool
306
     * @internal
307
     */
308
    protected $no_cacheBeforePageGen = false;
309
310
    /**
311
     * May be set to the pagesTSconfig
312
     * @var array|string
313
     * @internal
314
     */
315
    protected $pagesTSconfig = '';
316
317
    /**
318
     * Eg. insert JS-functions in this array ($additionalHeaderData) to include them
319
     * once. Use associative keys.
320
     *
321
     * Keys in use:
322
     *
323
     * used to accumulate additional HTML-code for the header-section,
324
     * <head>...</head>. Insert either associative keys (like
325
     * additionalHeaderData['myStyleSheet'], see reserved keys above) or num-keys
326
     * (like additionalHeaderData[] = '...')
327
     *
328
     * @var array
329
     */
330
    public $additionalHeaderData = [];
331
332
    /**
333
     * Used to accumulate additional HTML-code for the footer-section of the template
334
     * @var array
335
     */
336
    public $additionalFooterData = [];
337
338
    /**
339
     * Default internal target
340
     * @var string
341
     */
342
    public $intTarget = '';
343
344
    /**
345
     * Default external target
346
     * @var string
347
     */
348
    public $extTarget = '';
349
350
    /**
351
     * Default file link target
352
     * @var string
353
     */
354
    public $fileTarget = '';
355
356
    /**
357
     * If set, typolink() function encrypts email addresses.
358
     * @var string|int
359
     */
360
    public $spamProtectEmailAddresses = 0;
361
362
    /**
363
     * Absolute Reference prefix
364
     * @var string
365
     */
366
    public $absRefPrefix = '';
367
368
    /**
369
     * <A>-tag parameters
370
     * @var string
371
     */
372
    public $ATagParams = '';
373
374
    /**
375
     * Search word regex, calculated if there has been search-words send. This is
376
     * used to mark up the found search words on a page when jumped to from a link
377
     * in a search-result.
378
     * @var string
379
     * @internal
380
     */
381
    public $sWordRegEx = '';
382
383
    /**
384
     * Is set to the incoming array sword_list in case of a page-view jumped to from
385
     * a search-result.
386
     * @var string
387
     * @internal
388
     */
389
    public $sWordList = '';
390
391
    /**
392
     * A string prepared for insertion in all links on the page as url-parameters.
393
     * Based on configuration in TypoScript where you defined which GET_VARS you
394
     * would like to pass on.
395
     * @var string
396
     */
397
    public $linkVars = '';
398
399
    /**
400
     * If set, edit icons are rendered aside content records. Must be set only if
401
     * the ->beUserLogin flag is set and set_no_cache() must be called as well.
402
     * @var string
403
     */
404
    public $displayEditIcons = '';
405
406
    /**
407
     * If set, edit icons are rendered aside individual fields of content. Must be
408
     * set only if the ->beUserLogin flag is set and set_no_cache() must be called as
409
     * well.
410
     * @var string
411
     */
412
    public $displayFieldEditIcons = '';
413
414
    /**
415
     * 'Global' Storage for various applications. Keys should be 'tx_'.extKey for
416
     * extensions.
417
     * @var array
418
     */
419
    public $applicationData = [];
420
421
    /**
422
     * @var array
423
     */
424
    public $register = [];
425
426
    /**
427
     * Stack used for storing array and retrieving register arrays (see
428
     * LOAD_REGISTER and RESTORE_REGISTER)
429
     * @var array
430
     */
431
    public $registerStack = [];
432
433
    /**
434
     * Checking that the function is not called eternally. This is done by
435
     * interrupting at a depth of 50
436
     * @var int
437
     */
438
    public $cObjectDepthCounter = 50;
439
440
    /**
441
     * Used by RecordContentObject and ContentContentObject to ensure the a records is NOT
442
     * rendered twice through it!
443
     * @var array
444
     */
445
    public $recordRegister = [];
446
447
    /**
448
     * This is set to the [table]:[uid] of the latest record rendered. Note that
449
     * class ContentObjectRenderer has an equal value, but that is pointing to the
450
     * record delivered in the $data-array of the ContentObjectRenderer instance, if
451
     * the cObjects CONTENT or RECORD created that instance
452
     * @var string
453
     */
454
    public $currentRecord = '';
455
456
    /**
457
     * Used by class \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject
458
     * to keep track of access-keys.
459
     * @var array
460
     */
461
    public $accessKey = [];
462
463
    /**
464
     * Used to generate page-unique keys. Point is that uniqid() functions is very
465
     * slow, so a unikey key is made based on this, see function uniqueHash()
466
     * @var int
467
     * @internal
468
     */
469
    protected $uniqueCounter = 0;
470
471
    /**
472
     * @var string
473
     * @internal
474
     */
475
    protected $uniqueString = '';
476
477
    /**
478
     * This value will be used as the title for the page in the indexer (if
479
     * indexing happens)
480
     * @var string
481
     * @internal only used by TYPO3 Core, use PageTitle API instead.
482
     */
483
    public $indexedDocTitle = '';
484
485
    /**
486
     * The base URL set for the page header.
487
     * @var string
488
     */
489
    public $baseUrl = '';
490
491
    /**
492
     * Page content render object
493
     *
494
     * @var ContentObjectRenderer
495
     */
496
    public $cObj;
497
498
    /**
499
     * All page content is accumulated in this variable. See RequestHandler
500
     * @var string
501
     */
502
    public $content = '';
503
504
    /**
505
     * Output charset of the websites content. This is the charset found in the
506
     * header, meta tag etc. If different than utf-8 a conversion
507
     * happens before output to browser. Defaults to utf-8.
508
     * @var string
509
     */
510
    public $metaCharset = 'utf-8';
511
512
    /**
513
     * Internal calculations for labels
514
     *
515
     * @var LanguageService
516
     */
517
    protected $languageService;
518
519
    /**
520
     * @var LockingStrategyInterface[][]
521
     */
522
    protected $locks = [];
523
524
    /**
525
     * @var PageRenderer
526
     */
527
    protected $pageRenderer;
528
529
    /**
530
     * The page cache object, use this to save pages to the cache and to
531
     * retrieve them again
532
     *
533
     * @var \TYPO3\CMS\Core\Cache\Frontend\FrontendInterface
534
     */
535
    protected $pageCache;
536
537
    /**
538
     * @var array
539
     */
540
    protected $pageCacheTags = [];
541
542
    /**
543
     * Content type HTTP header being sent in the request.
544
     * @todo Ticket: #63642 Should be refactored to a request/response model later
545
     * @internal Should only be used by TYPO3 core for now
546
     *
547
     * @var string
548
     */
549
    protected $contentType = 'text/html';
550
551
    /**
552
     * Doctype to use
553
     *
554
     * @var string
555
     */
556
    public $xhtmlDoctype = '';
557
558
    /**
559
     * @var int
560
     */
561
    public $xhtmlVersion;
562
563
    /**
564
     * Originally requested id from the initial $_GET variable
565
     *
566
     * @var int
567
     */
568
    protected $requestedId;
569
570
    /**
571
     * The context for keeping the current state, mostly related to current page information,
572
     * backend user / frontend user access, workspaceId
573
     *
574
     * @var Context
575
     */
576
    protected $context;
577
578
    /**
579
     * Since TYPO3 v10.0, TSFE is composed out of
580
     *  - Context
581
     *  - Site
582
     *  - SiteLanguage
583
     *  - PageArguments (containing ID, Type, cHash and MP arguments)
584
     *
585
     * Also sets a unique string (->uniqueString) for this script instance; A md5 hash of the microtime()
586
     *
587
     * @param Context $context the Context object to work with
588
     * @param SiteInterface $site The resolved site to work with
589
     * @param SiteLanguage $siteLanguage The resolved language to work with
590
     * @param PageArguments $pageArguments The PageArguments object containing Page ID, type and GET parameters
591
     * @param FrontendUserAuthentication $frontendUser a FrontendUserAuthentication object
592
     */
593
    public function __construct(Context $context, SiteInterface $site, SiteLanguage $siteLanguage, PageArguments $pageArguments, FrontendUserAuthentication $frontendUser)
594
    {
595
        $this->initializeContext($context);
596
        $this->site = $site;
0 ignored issues
show
Documentation Bug introduced by
$site is of type TYPO3\CMS\Core\Site\Entity\SiteInterface, but the property $site was declared to be of type TYPO3\CMS\Core\Site\Entity\Site. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
597
        $this->language = $siteLanguage;
598
        $this->setPageArguments($pageArguments);
599
        $this->fe_user = $frontendUser;
600
        $this->uniqueString = md5(microtime());
601
        $this->initPageRenderer();
602
        $this->initCaches();
603
        // Initialize LLL behaviour
604
        $this->setOutputLanguage();
605
    }
606
607
    private function initializeContext(Context $context): void
608
    {
609
        $this->context = $context;
610
        if (!$this->context->hasAspect('frontend.preview')) {
611
            $this->context->setAspect('frontend.preview', GeneralUtility::makeInstance(PreviewAspect::class));
612
        }
613
    }
614
615
    /**
616
     * Initializes the page renderer object
617
     */
618
    protected function initPageRenderer()
619
    {
620
        if ($this->pageRenderer !== null) {
621
            return;
622
        }
623
        $this->pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
624
        $this->pageRenderer->setTemplateFile('EXT:frontend/Resources/Private/Templates/MainPage.html');
625
        // As initPageRenderer could be called in constructor and for USER_INTs, this information is only set
626
        // once - in order to not override any previous settings of PageRenderer.
627
        if ($this->language instanceof SiteLanguage) {
0 ignored issues
show
introduced by
$this->language is always a sub-type of TYPO3\CMS\Core\Site\Entity\SiteLanguage.
Loading history...
628
            $this->pageRenderer->setLanguage($this->language->getTypo3Language());
629
        }
630
    }
631
632
    /**
633
     * @param string $contentType
634
     * @internal Should only be used by TYPO3 core for now
635
     */
636
    public function setContentType($contentType)
637
    {
638
        $this->contentType = $contentType;
639
    }
640
641
    /********************************************
642
     *
643
     * Initializing, resolving page id
644
     *
645
     ********************************************/
646
    /**
647
     * Initializes the caching system.
648
     */
649
    protected function initCaches()
650
    {
651
        $this->pageCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('pages');
652
    }
653
654
    /**
655
     * Initializes the front-end user groups.
656
     * Sets frontend.user aspect based on front-end user status.
657
     */
658
    public function initUserGroups()
659
    {
660
        $userGroups = [0];
661
        // no matter if we have an active user we try to fetch matching groups which can be set without an user (simulation for instance!)
662
        $this->fe_user->fetchGroupData();
663
        $isUserAndGroupSet = is_array($this->fe_user->user) && !empty($this->fe_user->groupData['uid']);
664
        if ($isUserAndGroupSet) {
665
            // group -2 is not an existing group, but denotes a 'default' group when a user IS logged in.
666
            // This is used to let elements be shown for all logged in users!
667
            $userGroups[] = -2;
668
            $groupsFromUserRecord = $this->fe_user->groupData['uid'];
669
        } else {
670
            // group -1 is not an existing group, but denotes a 'default' group when not logged in.
671
            // This is used to let elements be hidden, when a user is logged in!
672
            $userGroups[] = -1;
673
            if ($this->loginAllowedInBranch) {
674
                // For cases where logins are not banned from a branch usergroups can be set based on IP masks so we should add the usergroups uids.
675
                $groupsFromUserRecord = $this->fe_user->groupData['uid'];
676
            } else {
677
                // Set to blank since we will NOT risk any groups being set when no logins are allowed!
678
                $groupsFromUserRecord = [];
679
            }
680
        }
681
        // Clean up.
682
        // Make unique and sort the groups
683
        $groupsFromUserRecord = array_unique($groupsFromUserRecord);
684
        if (!empty($groupsFromUserRecord) && !$this->loginAllowedInBranch_mode) {
685
            sort($groupsFromUserRecord);
686
            $userGroups = array_merge($userGroups, array_map('intval', $groupsFromUserRecord));
687
        }
688
689
        $this->context->setAspect('frontend.user', GeneralUtility::makeInstance(UserAspect::class, $this->fe_user, $userGroups));
690
691
        // For every 60 seconds the is_online timestamp for a logged-in user is updated
692
        if ($isUserAndGroupSet) {
693
            $this->fe_user->updateOnlineTimestamp();
694
        }
695
696
        $this->logger->debug('Valid usergroups for TSFE: ' . implode(',', $userGroups));
697
    }
698
699
    /**
700
     * Checking if a user is logged in or a group constellation different from "0,-1"
701
     *
702
     * @return bool TRUE if either a login user is found (array fe_user->user) OR if the gr_list is set to something else than '0,-1' (could be done even without a user being logged in!)
703
     */
704
    public function isUserOrGroupSet()
705
    {
706
        /** @var UserAspect $userAspect */
707
        $userAspect = $this->context->getAspect('frontend.user');
708
        return $userAspect->isUserOrGroupSet();
709
    }
710
711
    /**
712
     * Clears the preview-flags, sets sim_exec_time to current time.
713
     * Hidden pages must be hidden as default, $GLOBALS['SIM_EXEC_TIME'] is set to $GLOBALS['EXEC_TIME']
714
     * in bootstrap initializeGlobalTimeVariables(). Alter it by adding or subtracting seconds.
715
     */
716
    public function clear_preview()
717
    {
718
        if ($this->context->getPropertyFromAspect('frontend.preview', 'isPreview')
719
            || $GLOBALS['EXEC_TIME'] !== $GLOBALS['SIM_EXEC_TIME']
720
            || $this->context->getPropertyFromAspect('visibility', 'includeHiddenPages', false)
721
            || $this->context->getPropertyFromAspect('visibility', 'includeHiddenContent', false)
722
        ) {
723
            $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
724
            $GLOBALS['SIM_ACCESS_TIME'] = $GLOBALS['ACCESS_TIME'];
725
            $this->context->setAspect('frontend.preview', GeneralUtility::makeInstance(PreviewAspect::class));
726
            $this->context->setAspect('date', GeneralUtility::makeInstance(DateTimeAspect::class, new \DateTimeImmutable('@' . $GLOBALS['SIM_EXEC_TIME'])));
727
            $this->context->setAspect('visibility', GeneralUtility::makeInstance(VisibilityAspect::class));
728
        }
729
    }
730
731
    /**
732
     * Checks if a backend user is logged in
733
     *
734
     * @return bool whether a backend user is logged in
735
     */
736
    public function isBackendUserLoggedIn()
737
    {
738
        return (bool)$this->context->getPropertyFromAspect('backend.user', 'isLoggedIn', false);
739
    }
740
741
    /**
742
     * Determines the id and evaluates any preview settings
743
     * Basically this function is about determining whether a backend user is logged in,
744
     * if he has read access to the page and if he's previewing the page.
745
     * That all determines which id to show and how to initialize the id.
746
     *
747
     * @param ServerRequestInterface|null $request
748
     */
749
    public function determineId(ServerRequestInterface $request = null)
750
    {
751
        $request = $request ?? $GLOBALS['TYPO3_REQUEST'] ?? ServerRequestFactory::fromGlobals();
752
        // Call pre processing function for id determination
753
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PreProcessing'] ?? [] as $functionReference) {
754
            $parameters = ['parentObject' => $this];
755
            GeneralUtility::callUserFunction($functionReference, $parameters, $this);
756
        }
757
        // If there is a Backend login we are going to check for any preview settings
758
        $originalFrontendUserGroups = $this->applyPreviewSettings($this->getBackendUser());
0 ignored issues
show
Bug introduced by
The method getBackendUser() does not exist on null. ( Ignorable by Annotation )

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

758
        $originalFrontendUserGroups = $this->applyPreviewSettings($this->/** @scrutinizer ignore-call */ getBackendUser());

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

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

Loading history...
759
        // If the front-end is showing a preview, caching MUST be disabled.
760
        $isPreview = $this->context->getPropertyFromAspect('frontend.preview', 'isPreview');
761
        if ($isPreview) {
762
            $this->disableCache();
763
        }
764
        // Now, get the id, validate access etc:
765
        $this->fetch_the_id($request);
766
        // Check if backend user has read access to this page. If not, recalculate the id.
767
        if ($this->isBackendUserLoggedIn() && $isPreview && !$this->getBackendUser()->doesUserHaveAccess($this->page, Permission::PAGE_SHOW)) {
768
            $this->unsetBackendUser();
769
            // Resetting
770
            $this->clear_preview();
771
            $this->fe_user->user[$this->fe_user->usergroup_column] = $originalFrontendUserGroups;
772
            // Fetching the id again, now with the preview settings reset.
773
            $this->fetch_the_id($request);
774
        }
775
        // Checks if user logins are blocked for a certain branch and if so, will unset user login and re-fetch ID.
776
        $this->loginAllowedInBranch = $this->checkIfLoginAllowedInBranch();
777
        // Logins are not allowed, but there is a login, so will we run this.
778
        if (!$this->loginAllowedInBranch && $this->isUserOrGroupSet()) {
779
            if ($this->loginAllowedInBranch_mode === 'all') {
780
                // Clear out user and group:
781
                $this->fe_user->hideActiveLogin();
782
                $userGroups = [0, -1];
783
            } else {
784
                $userGroups = [0, -2];
785
            }
786
            $this->context->setAspect('frontend.user', GeneralUtility::makeInstance(UserAspect::class, $this->fe_user, $userGroups));
787
            // Fetching the id again, now with the preview settings reset.
788
            $this->fetch_the_id($request);
789
        }
790
        // Final cleaning.
791
        // Make sure it's an integer
792
        $this->id = ($this->contentPid = (int)$this->id);
793
        // Make sure it's an integer
794
        $this->type = (int)$this->type;
795
        // Setting language and fetch translated page
796
        $this->settingLanguage($request);
797
        // Call post processing function for id determination:
798
        $_params = ['pObj' => &$this];
799
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'] ?? [] as $_funcRef) {
800
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
801
        }
802
    }
803
804
    protected function unsetBackendUser(): void
805
    {
806
        // Register an empty backend user as aspect
807
        unset($GLOBALS['BE_USER']);
808
        $this->context->setAspect('backend.user', GeneralUtility::makeInstance(UserAspect::class));
809
        $this->context->setAspect('workspace', GeneralUtility::makeInstance(WorkspaceAspect::class));
810
    }
811
812
    /**
813
     * Evaluates admin panel or workspace settings to see if
814
     * visibility settings like
815
     * - Preview Aspect: isPreview
816
     * - Visibility Aspect: includeHiddenPages
817
     * - Visibility Aspect: includeHiddenContent
818
     * - $simUserGroup
819
     * should be applied to the current object.
820
     *
821
     * @param FrontendBackendUserAuthentication $backendUser
822
     * @return string|null null if no changes to the current frontend usergroups have been made, otherwise the original list of frontend usergroups
823
     * @internal
824
     */
825
    protected function applyPreviewSettings($backendUser = null)
826
    {
827
        if (!$backendUser) {
828
            return null;
829
        }
830
        $originalFrontendUserGroup = null;
831
        if ($this->fe_user->user) {
832
            $originalFrontendUserGroup = $this->context->getPropertyFromAspect('frontend.user', 'groupIds');
833
        }
834
835
        // The preview flag is set if the current page turns out to be hidden
836
        if ($this->id && $this->determineIdIsHiddenPage()) {
837
            $this->context->setAspect('frontend.preview', GeneralUtility::makeInstance(PreviewAspect::class, true));
838
            /** @var VisibilityAspect $aspect */
839
            $aspect = $this->context->getAspect('visibility');
840
            $newAspect = GeneralUtility::makeInstance(VisibilityAspect::class, true, $aspect->includeHiddenContent(), $aspect->includeDeletedRecords());
841
            $this->context->setAspect('visibility', $newAspect);
842
        }
843
        // The preview flag will be set if an offline workspace will be previewed
844
        if ($this->whichWorkspace() > 0) {
845
            $this->context->setAspect('frontend.preview', GeneralUtility::makeInstance(PreviewAspect::class, true));
846
        }
847
        return $this->context->getPropertyFromAspect('frontend.preview', 'preview', false) ? $originalFrontendUserGroup : null;
848
    }
849
850
    /**
851
     * Checks if the page is hidden in the active workspace.
852
     * If it is hidden, preview flags will be set.
853
     *
854
     * @return bool
855
     */
856
    protected function determineIdIsHiddenPage()
857
    {
858
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
859
            ->getQueryBuilderForTable('pages');
860
        $queryBuilder
861
            ->getRestrictions()
862
            ->removeAll()
863
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
864
865
        $queryBuilder
866
            ->select('uid', 'hidden', 'starttime', 'endtime')
867
            ->from('pages')
868
            ->where(
869
                $queryBuilder->expr()->gte('pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
870
            )
871
            ->setMaxResults(1);
872
873
        // $this->id always points to the ID of the default language page, so we check
874
        // the current site language to determine if we need to fetch a translation but consider fallbacks
875
        if ($this->language->getLanguageId() > 0) {
876
            $languagesToCheck = array_merge([$this->language->getLanguageId()], $this->language->getFallbackLanguageIds());
877
            // Check for the language and all its fallbacks
878
            $constraint = $queryBuilder->expr()->andX(
879
                $queryBuilder->expr()->eq('l10n_parent', $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)),
880
                $queryBuilder->expr()->in('sys_language_uid', $queryBuilder->createNamedParameter(array_filter($languagesToCheck), Connection::PARAM_INT_ARRAY))
881
            );
882
            // If the fallback language Ids also contains the default language, this needs to be considered
883
            if (in_array(0, $languagesToCheck, true)) {
884
                $constraint = $queryBuilder->expr()->orX(
885
                    $constraint,
886
                    // Ensure to also fetch the default record
887
                    $queryBuilder->expr()->andX(
888
                        $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)),
889
                        $queryBuilder->expr()->in('sys_language_uid', 0)
890
                    )
891
                );
892
            }
893
            // Ensure that the translated records are shown first (maxResults is set to 1)
894
            $queryBuilder->orderBy('sys_language_uid', 'DESC');
895
        } else {
896
            $constraint = $queryBuilder->expr()->eq('uid', $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT));
897
        }
898
        $queryBuilder->andWhere($constraint);
899
900
        $page = $queryBuilder->execute()->fetch();
901
902
        if ($this->whichWorkspace() > 0) {
903
            // Fetch overlay of page if in workspace and check if it is hidden
904
            $customContext = clone $this->context;
905
            $customContext->setAspect('workspace', GeneralUtility::makeInstance(WorkspaceAspect::class, $this->whichWorkspace()));
906
            $customContext->setAspect('visibility', GeneralUtility::makeInstance(VisibilityAspect::class));
907
            $pageSelectObject = GeneralUtility::makeInstance(PageRepository::class, $customContext);
908
            $targetPage = $pageSelectObject->getWorkspaceVersionOfRecord($this->whichWorkspace(), 'pages', $page['uid']);
909
            // Also checks if the workspace version is NOT hidden but the live version is in fact still hidden
910
            $result = $targetPage === -1 || $targetPage === -2 || (is_array($targetPage) && $targetPage['hidden'] == 0 && $page['hidden'] == 1);
911
        } else {
912
            $result = is_array($page) && ($page['hidden'] || $page['starttime'] > $GLOBALS['SIM_EXEC_TIME'] || $page['endtime'] != 0 && $page['endtime'] <= $GLOBALS['SIM_EXEC_TIME']);
913
        }
914
        return $result;
915
    }
916
917
    /**
918
     * Resolves the page id and sets up several related properties.
919
     *
920
     * If $this->id is not set at all or is not a plain integer, the method
921
     * does it's best to set the value to an integer. Resolving is based on
922
     * this options:
923
     *
924
     * - Splitting $this->id if it contains an additional type parameter.
925
     * - Finding the domain record start page
926
     * - First visible page
927
     * - Relocating the id below the domain record if outside
928
     *
929
     * The following properties may be set up or updated:
930
     *
931
     * - id
932
     * - requestedId
933
     * - type
934
     * - sys_page
935
     * - sys_page->where_groupAccess
936
     * - sys_page->where_hid_del
937
     * - Context: FrontendUser Aspect
938
     * - no_cache
939
     * - register['SYS_LASTCHANGED']
940
     * - pageNotFound
941
     *
942
     * Via getPageAndRootlineWithDomain()
943
     *
944
     * - rootLine
945
     * - page
946
     * - MP
947
     * - originalShortcutPage
948
     * - originalMountPointPage
949
     * - pageAccessFailureHistory['direct_access']
950
     * - pageNotFound
951
     *
952
     * @todo:
953
     *
954
     * On the first impression the method does to much. This is increased by
955
     * the fact, that is is called repeated times by the method determineId.
956
     * The reasons are manifold.
957
     *
958
     * 1.) The first part, the creation of sys_page and the type
959
     * resolution don't need to be repeated. They could be separated to be
960
     * called only once.
961
     *
962
     * 2.) The user group setup could be done once on a higher level.
963
     *
964
     * 3.) The workflow of the resolution could be elaborated to be less
965
     * tangled. Maybe the check of the page id to be below the domain via the
966
     * root line doesn't need to be done each time, but for the final result
967
     * only.
968
     *
969
     * 4.) The root line does not need to be directly addressed by this class.
970
     * A root line is always related to one page. The rootline could be handled
971
     * indirectly by page objects. Page objects still don't exist.
972
     *
973
     * @internal
974
     * @param ServerRequestInterface|null $request
975
     */
976
    public function fetch_the_id(ServerRequestInterface $request = null)
977
    {
978
        $request = $request ?? $GLOBALS['TYPO3_REQUEST'] ?? ServerRequestFactory::fromGlobals();
979
        $timeTracker = $this->getTimeTracker();
980
        $timeTracker->push('fetch_the_id initialize/');
981
        // Set the valid usergroups for FE
982
        $this->initUserGroups();
983
        // Initialize the PageRepository has to be done after the frontend usergroups are initialized / resolved, as
984
        // frontend group aspect is modified before
985
        $this->sys_page = GeneralUtility::makeInstance(PageRepository::class, $this->context);
986
        // The id and type is set to the integer-value - just to be sure...
987
        $this->id = (int)$this->id;
988
        $this->type = (int)$this->type;
989
        $timeTracker->pull();
990
        // We find the first page belonging to the current domain
991
        $timeTracker->push('fetch_the_id domain/');
992
        if (!$this->id) {
993
            // If the id was not previously set, set it to the root page id of the site.
994
            $this->id = $this->site->getRootPageId();
995
        }
996
        $timeTracker->pull();
997
        $timeTracker->push('fetch_the_id rootLine/');
998
        // We store the originally requested id
999
        $this->requestedId = $this->id;
1000
        try {
1001
            $this->getPageAndRootlineWithDomain($this->site->getRootPageId(), $request);
1002
        } catch (ShortcutTargetPageNotFoundException $e) {
1003
            $this->pageNotFound = 1;
1004
        }
1005
        $timeTracker->pull();
1006
        if ($this->pageNotFound) {
1007
            switch ($this->pageNotFound) {
1008
                case 1:
1009
                    $response = GeneralUtility::makeInstance(ErrorController::class)->accessDeniedAction(
1010
                        $request,
1011
                        'ID was not an accessible page',
1012
                        $this->getPageAccessFailureReasons(PageAccessFailureReasons::ACCESS_DENIED_PAGE_NOT_RESOLVED)
1013
                    );
1014
                    break;
1015
                case 2:
1016
                    $response = GeneralUtility::makeInstance(ErrorController::class)->accessDeniedAction(
1017
                        $request,
1018
                        'Subsection was found and not accessible',
1019
                        $this->getPageAccessFailureReasons(PageAccessFailureReasons::ACCESS_DENIED_SUBSECTION_NOT_RESOLVED)
1020
                    );
1021
                    break;
1022
                case 3:
1023
                    $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
1024
                        $request,
1025
                        'ID was outside the domain',
1026
                        $this->getPageAccessFailureReasons(PageAccessFailureReasons::ACCESS_DENIED_HOST_PAGE_MISMATCH)
1027
                    );
1028
                    break;
1029
                default:
1030
                    $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
1031
                        $request,
1032
                        'Unspecified error',
1033
                        $this->getPageAccessFailureReasons()
1034
                    );
1035
            }
1036
            throw new ImmediateResponseException($response, 1533931329);
1037
        }
1038
1039
        $this->setRegisterValueForSysLastChanged($this->page);
1040
1041
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['fetchPageId-PostProcessing'] ?? [] as $functionReference) {
1042
            $parameters = ['parentObject' => $this];
1043
            GeneralUtility::callUserFunction($functionReference, $parameters, $this);
1044
        }
1045
    }
1046
1047
    /**
1048
     * Loads the page and root line records based on $this->id
1049
     *
1050
     * A final page and the matching root line are determined and loaded by
1051
     * the algorithm defined by this method.
1052
     *
1053
     * First it loads the initial page from the page repository for $this->id.
1054
     * If that can't be loaded directly, it gets the root line for $this->id.
1055
     * It walks up the root line towards the root page until the page
1056
     * repository can deliver a page record. (The loading restrictions of
1057
     * the root line records are more liberal than that of the page record.)
1058
     *
1059
     * Now the page type is evaluated and handled if necessary. If the page is
1060
     * a short cut, it is replaced by the target page. If the page is a mount
1061
     * point in overlay mode, the page is replaced by the mounted page.
1062
     *
1063
     * After this potential replacements are done, the root line is loaded
1064
     * (again) for this page record. It walks up the root line up to
1065
     * the first viewable record.
1066
     *
1067
     * (While upon the first accessibility check of the root line it was done
1068
     * by loading page by page from the page repository, this time the method
1069
     * checkRootlineForIncludeSection() is used to find the most distant
1070
     * accessible page within the root line.)
1071
     *
1072
     * Having found the final page id, the page record and the root line are
1073
     * loaded for last time by this method.
1074
     *
1075
     * Exceptions may be thrown for DOKTYPE_SPACER and not loadable page records
1076
     * or root lines.
1077
     *
1078
     * May set or update this properties:
1079
     *
1080
     * @see TypoScriptFrontendController::$id
1081
     * @see TypoScriptFrontendController::$MP
1082
     * @see TypoScriptFrontendController::$page
1083
     * @see TypoScriptFrontendController::$pageNotFound
1084
     * @see TypoScriptFrontendController::$pageAccessFailureHistory
1085
     * @see TypoScriptFrontendController::$originalMountPointPage
1086
     * @see TypoScriptFrontendController::$originalShortcutPage
1087
     *
1088
     * @throws ServiceUnavailableException
1089
     * @throws PageNotFoundException
1090
     */
1091
    protected function getPageAndRootline(ServerRequestInterface $request)
1092
    {
1093
        $requestedPageRowWithoutGroupCheck = [];
1094
        $this->resolveTranslatedPageId();
1095
        if (empty($this->page)) {
1096
            // If no page, we try to find the page before in the rootLine.
1097
            // Page is 'not found' in case the id itself was not an accessible page. code 1
1098
            $this->pageNotFound = 1;
1099
            $requestedPageIsHidden = false;
1100
            try {
1101
                $hiddenField = $GLOBALS['TCA']['pages']['ctrl']['enablecolumns']['disabled'] ?? '';
1102
                $includeHiddenPages = $this->context->getPropertyFromAspect('visibility', 'includeHiddenPages') || $this->isBackendUserLoggedIn();
1103
                if (!empty($hiddenField) && !$includeHiddenPages) {
1104
                    // Page is "hidden" => 404 (deliberately done in default language, as this cascades to language overlays)
1105
                    $rawPageRecord = $this->sys_page->getPage_noCheck($this->id);
1106
                    $requestedPageIsHidden = (bool)$rawPageRecord[$hiddenField];
1107
                }
1108
1109
                $requestedPageRowWithoutGroupCheck = $this->sys_page->getPage($this->id, true);
1110
                if (!empty($requestedPageRowWithoutGroupCheck)) {
1111
                    $this->pageAccessFailureHistory['direct_access'][] = $requestedPageRowWithoutGroupCheck;
1112
                }
1113
                $this->rootLine = GeneralUtility::makeInstance(RootlineUtility::class, $this->id, $this->MP, $this->context)->get();
1114
                if (!empty($this->rootLine)) {
1115
                    $c = count($this->rootLine) - 1;
1116
                    while ($c > 0) {
1117
                        // Add to page access failure history:
1118
                        $this->pageAccessFailureHistory['direct_access'][] = $this->rootLine[$c];
1119
                        // Decrease to next page in rootline and check the access to that, if OK, set as page record and ID value.
1120
                        $c--;
1121
                        $this->id = $this->rootLine[$c]['uid'];
1122
                        $this->page = $this->sys_page->getPage($this->id);
1123
                        if (!empty($this->page)) {
1124
                            break;
1125
                        }
1126
                    }
1127
                }
1128
            } catch (RootLineException $e) {
1129
                $this->rootLine = [];
1130
            }
1131
            // If still no page...
1132
            if ($requestedPageIsHidden || (empty($requestedPageRowWithoutGroupCheck) && empty($this->page))) {
1133
                $message = 'The requested page does not exist!';
1134
                $this->logger->error($message);
1135
                try {
1136
                    $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
1137
                        $request,
1138
                        $message,
1139
                        $this->getPageAccessFailureReasons(PageAccessFailureReasons::PAGE_NOT_FOUND)
1140
                    );
1141
                    throw new ImmediateResponseException($response, 1533931330);
1142
                } catch (PageNotFoundException $e) {
1143
                    throw new PageNotFoundException($message, 1301648780);
1144
                }
1145
            }
1146
        }
1147
        // Spacer and sysfolders is not accessible in frontend
1148
        if ($this->page['doktype'] == PageRepository::DOKTYPE_SPACER || $this->page['doktype'] == PageRepository::DOKTYPE_SYSFOLDER) {
1149
            $message = 'The requested page does not exist!';
1150
            $this->logger->error($message);
1151
            try {
1152
                $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
1153
                    $request,
1154
                    $message,
1155
                    $this->getPageAccessFailureReasons(PageAccessFailureReasons::ACCESS_DENIED_INVALID_PAGETYPE)
1156
                );
1157
                throw new ImmediateResponseException($response, 1533931343);
1158
            } catch (PageNotFoundException $e) {
1159
                throw new PageNotFoundException($message, 1301648781);
1160
            }
1161
        }
1162
        // Is the ID a link to another page??
1163
        if ($this->page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1164
            // We need to clear MP if the page is a shortcut. Reason is if the short cut goes to another page, then we LEAVE the rootline which the MP expects.
1165
            $this->MP = '';
1166
            // saving the page so that we can check later - when we know
1167
            // about languages - whether we took the correct shortcut or
1168
            // whether a translation of the page overwrites the shortcut
1169
            // target and we need to follow the new target
1170
            $this->originalShortcutPage = $this->page;
1171
            $this->page = $this->sys_page->getPageShortcut($this->page['shortcut'], $this->page['shortcut_mode'], $this->page['uid']);
1172
            $this->id = $this->page['uid'];
1173
        }
1174
        // If the page is a mountpoint which should be overlaid with the contents of the mounted page,
1175
        // it must never be accessible directly, but only in the mountpoint context. Therefore we change
1176
        // the current ID and the user is redirected by checkPageForMountpointRedirect().
1177
        if ($this->page['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT && $this->page['mount_pid_ol']) {
1178
            $this->originalMountPointPage = $this->page;
1179
            $this->page = $this->sys_page->getPage($this->page['mount_pid']);
1180
            if (empty($this->page)) {
1181
                $message = 'This page (ID ' . $this->originalMountPointPage['uid'] . ') is of type "Mount point" and '
1182
                    . 'mounts a page which is not accessible (ID ' . $this->originalMountPointPage['mount_pid'] . ').';
1183
                throw new PageNotFoundException($message, 1402043263);
1184
            }
1185
            // If the current page is a shortcut, the MP parameter will be replaced
1186
            if ($this->MP === '' || !empty($this->originalShortcutPage)) {
1187
                $this->MP = $this->page['uid'] . '-' . $this->originalMountPointPage['uid'];
1188
            } else {
1189
                $this->MP .= ',' . $this->page['uid'] . '-' . $this->originalMountPointPage['uid'];
1190
            }
1191
            $this->id = $this->page['uid'];
1192
        }
1193
        // Gets the rootLine
1194
        try {
1195
            $this->rootLine = GeneralUtility::makeInstance(RootlineUtility::class, $this->id, $this->MP, $this->context)->get();
1196
        } catch (RootLineException $e) {
1197
            $this->rootLine = [];
1198
        }
1199
        // If not rootline we're off...
1200
        if (empty($this->rootLine)) {
1201
            $message = 'The requested page didn\'t have a proper connection to the tree-root!';
1202
            $this->logger->error($message);
1203
            try {
1204
                $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction(
1205
                    $request,
1206
                    $message,
1207
                    $this->getPageAccessFailureReasons(PageAccessFailureReasons::ROOTLINE_BROKEN)
1208
                );
1209
                throw new ImmediateResponseException($response, 1533931350);
1210
            } catch (ServiceUnavailableException $e) {
1211
                throw new ServiceUnavailableException($message, 1301648167);
1212
            }
1213
        }
1214
        // Checking for include section regarding the hidden/starttime/endtime/fe_user (that is access control of a whole subbranch!)
1215
        if ($this->checkRootlineForIncludeSection()) {
1216
            if (empty($this->rootLine)) {
1217
                $message = 'The requested page was not accessible!';
1218
                try {
1219
                    $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction(
1220
                        $request,
1221
                        $message,
1222
                        $this->getPageAccessFailureReasons(PageAccessFailureReasons::ACCESS_DENIED_GENERAL)
1223
                    );
1224
                    throw new ImmediateResponseException($response, 1533931351);
1225
                } catch (ServiceUnavailableException $e) {
1226
                    $this->logger->warning($message);
1227
                    throw new ServiceUnavailableException($message, 1301648234);
1228
                }
1229
            } else {
1230
                $el = reset($this->rootLine);
1231
                $this->id = $el['uid'];
1232
                $this->page = $this->sys_page->getPage($this->id);
1233
                try {
1234
                    $this->rootLine = GeneralUtility::makeInstance(RootlineUtility::class, $this->id, $this->MP, $this->context)->get();
1235
                } catch (RootLineException $e) {
1236
                    $this->rootLine = [];
1237
                }
1238
            }
1239
        }
1240
    }
1241
1242
    /**
1243
     * If $this->id contains a translated page record, this needs to be resolved to the default language
1244
     * in order for all rootline functionality and access restrictions to be in place further on.
1245
     *
1246
     * Additionally, if a translated page is found, LanguageAspect is set as well.
1247
     */
1248
    protected function resolveTranslatedPageId()
1249
    {
1250
        $this->page = $this->sys_page->getPage($this->id);
0 ignored issues
show
Bug introduced by
$this->id of type string is incompatible with the type integer expected by parameter $uid of TYPO3\CMS\Core\Domain\Re...geRepository::getPage(). ( Ignorable by Annotation )

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

1250
        $this->page = $this->sys_page->getPage(/** @scrutinizer ignore-type */ $this->id);
Loading history...
1251
        // Accessed a default language page record, nothing to resolve
1252
        if (empty($this->page) || (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']] === 0) {
1253
            return;
1254
        }
1255
        $languageId = (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
1256
        $this->page = $this->sys_page->getPage($this->page[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']]);
1257
        $this->context->setAspect('language', GeneralUtility::makeInstance(LanguageAspect::class, $languageId));
1258
        $this->id = $this->page['uid'];
1259
    }
1260
1261
    /**
1262
     * Checks if visibility of the page is blocked upwards in the root line.
1263
     *
1264
     * If any page in the root line is blocking visibility, true is returned.
1265
     *
1266
     * All pages from the blocking page downwards are removed from the root
1267
     * line, so that the remaining pages can be used to relocate the page up
1268
     * to lowest visible page.
1269
     *
1270
     * The blocking feature of a page must be turned on by setting the page
1271
     * record field 'extendToSubpages' to 1 in case of hidden, starttime,
1272
     * endtime or fe_group restrictions.
1273
     *
1274
     * Additionally this method checks for backend user sections in root line
1275
     * and if found evaluates if a backend user is logged in and has access.
1276
     *
1277
     * Recyclers are also checked and trigger page not found if found in root
1278
     * line.
1279
     *
1280
     * @todo Find a better name, i.e. checkVisibilityByRootLine
1281
     * @todo Invert boolean return value. Return true if visible.
1282
     *
1283
     * @return bool
1284
     */
1285
    protected function checkRootlineForIncludeSection(): bool
1286
    {
1287
        $c = count($this->rootLine);
1288
        $removeTheRestFlag = false;
1289
        for ($a = 0; $a < $c; $a++) {
1290
            if (!$this->checkPagerecordForIncludeSection($this->rootLine[$a])) {
1291
                // Add to page access failure history and mark the page as not found
1292
                // Keep the rootline however to trigger an access denied error instead of a service unavailable error
1293
                $this->pageAccessFailureHistory['sub_section'][] = $this->rootLine[$a];
1294
                $this->pageNotFound = 2;
1295
            }
1296
1297
            if ((int)$this->rootLine[$a]['doktype'] === PageRepository::DOKTYPE_BE_USER_SECTION) {
1298
                // If there is a backend user logged in, check if they have read access to the page:
1299
                if ($this->isBackendUserLoggedIn()) {
1300
                    $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1301
                        ->getQueryBuilderForTable('pages');
1302
1303
                    $queryBuilder
1304
                        ->getRestrictions()
1305
                        ->removeAll();
1306
1307
                    $row = $queryBuilder
1308
                        ->select('uid')
1309
                        ->from('pages')
1310
                        ->where(
1311
                            $queryBuilder->expr()->eq(
1312
                                'uid',
1313
                                $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
1314
                            ),
1315
                            $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW)
1316
                        )
1317
                        ->execute()
1318
                        ->fetch();
1319
1320
                    // versionOL()?
1321
                    if (!$row) {
1322
                        // If there was no page selected, the user apparently did not have read access to the current PAGE (not position in rootline) and we set the remove-flag...
1323
                        $removeTheRestFlag = true;
1324
                    }
1325
                } else {
1326
                    // Don't go here, if there is no backend user logged in.
1327
                    $removeTheRestFlag = true;
1328
                }
1329
            } elseif ((int)$this->rootLine[$a]['doktype'] === PageRepository::DOKTYPE_RECYCLER) {
1330
                // page is in a recycler
1331
                $removeTheRestFlag = true;
1332
            }
1333
            if ($removeTheRestFlag) {
1334
                // Page is 'not found' in case a subsection was found and not accessible, code 2
1335
                $this->pageNotFound = 2;
1336
                unset($this->rootLine[$a]);
1337
            }
1338
        }
1339
        return $removeTheRestFlag;
1340
    }
1341
1342
    /**
1343
     * Checks page record for enableFields
1344
     * Returns TRUE if enableFields does not disable the page record.
1345
     * Takes notice of the includeHiddenPages visibility aspect flag and uses SIM_ACCESS_TIME for start/endtime evaluation
1346
     *
1347
     * @param array $row The page record to evaluate (needs fields: hidden, starttime, endtime, fe_group)
1348
     * @param bool $bypassGroupCheck Bypass group-check
1349
     * @return bool TRUE, if record is viewable.
1350
     * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList()
1351
     * @see checkPagerecordForIncludeSection()
1352
     */
1353
    public function checkEnableFields($row, $bypassGroupCheck = false)
1354
    {
1355
        $_params = ['pObj' => $this, 'row' => &$row, 'bypassGroupCheck' => &$bypassGroupCheck];
1356
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_checkEnableFields'] ?? [] as $_funcRef) {
1357
            // Call hooks: If one returns FALSE, method execution is aborted with result "This record is not available"
1358
            $return = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1359
            if ($return === false) {
1360
                return false;
1361
            }
1362
        }
1363
        if ((!$row['hidden'] || $this->context->getPropertyFromAspect('visibility', 'includeHiddenPages', false))
1364
            && $row['starttime'] <= $GLOBALS['SIM_ACCESS_TIME']
1365
            && ($row['endtime'] == 0 || $row['endtime'] > $GLOBALS['SIM_ACCESS_TIME'])
1366
            && ($bypassGroupCheck || $this->checkPageGroupAccess($row))) {
1367
            return true;
1368
        }
1369
        return false;
1370
    }
1371
1372
    /**
1373
     * Check group access against a page record
1374
     *
1375
     * @param array $row The page record to evaluate (needs field: fe_group)
1376
     * @return bool TRUE, if group access is granted.
1377
     * @internal
1378
     */
1379
    public function checkPageGroupAccess($row)
1380
    {
1381
        /** @var UserAspect $userAspect */
1382
        $userAspect = $this->context->getAspect('frontend.user');
1383
        $pageGroupList = explode(',', $row['fe_group'] ?: 0);
1384
        return count(array_intersect($userAspect->getGroupIds(), $pageGroupList)) > 0;
1385
    }
1386
1387
    /**
1388
     * Checks if the current page of the root line is visible.
1389
     *
1390
     * If the field extendToSubpages is 0, access is granted,
1391
     * else the fields hidden, starttime, endtime, fe_group are evaluated.
1392
     *
1393
     * @todo Find a better name, i.e. isVisibleRecord()
1394
     *
1395
     * @param array $row The page record
1396
     * @return bool true if visible
1397
     * @internal
1398
     * @see checkEnableFields()
1399
     * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList()
1400
     * @see checkRootlineForIncludeSection()
1401
     */
1402
    public function checkPagerecordForIncludeSection(array $row): bool
1403
    {
1404
        return !$row['extendToSubpages'] || $this->checkEnableFields($row);
1405
    }
1406
1407
    /**
1408
     * Checks if logins are allowed in the current branch of the page tree. Traverses the full root line and returns TRUE if logins are OK, otherwise FALSE (and then the login user must be unset!)
1409
     *
1410
     * @return bool returns TRUE if logins are OK, otherwise FALSE (and then the login user must be unset!)
1411
     */
1412
    public function checkIfLoginAllowedInBranch()
1413
    {
1414
        // Initialize:
1415
        $c = count($this->rootLine);
1416
        $loginAllowed = true;
1417
        // Traverse root line from root and outwards:
1418
        for ($a = 0; $a < $c; $a++) {
1419
            // If a value is set for login state:
1420
            if ($this->rootLine[$a]['fe_login_mode'] > 0) {
1421
                // Determine state from value:
1422
                if ((int)$this->rootLine[$a]['fe_login_mode'] === 1) {
1423
                    $loginAllowed = false;
1424
                    $this->loginAllowedInBranch_mode = 'all';
1425
                } elseif ((int)$this->rootLine[$a]['fe_login_mode'] === 3) {
1426
                    $loginAllowed = false;
1427
                    $this->loginAllowedInBranch_mode = 'groups';
1428
                } else {
1429
                    $loginAllowed = true;
1430
                }
1431
            }
1432
        }
1433
        return $loginAllowed;
1434
    }
1435
1436
    /**
1437
     * Analysing $this->pageAccessFailureHistory into a summary array telling which features disabled display and on which pages and conditions. That data can be used inside a page-not-found handler
1438
     *
1439
     * @param string $failureReasonCode the error code to be attached (optional), see PageAccessFailureReasons list for details
1440
     * @return array Summary of why page access was not allowed.
1441
     */
1442
    public function getPageAccessFailureReasons(string $failureReasonCode = null)
1443
    {
1444
        $output = [];
1445
        if ($failureReasonCode) {
1446
            $output['code'] = $failureReasonCode;
1447
        }
1448
        $combinedRecords = array_merge(is_array($this->pageAccessFailureHistory['direct_access']) ? $this->pageAccessFailureHistory['direct_access'] : [['fe_group' => 0]], is_array($this->pageAccessFailureHistory['sub_section']) ? $this->pageAccessFailureHistory['sub_section'] : []);
1449
        if (!empty($combinedRecords)) {
1450
            foreach ($combinedRecords as $k => $pagerec) {
1451
                // If $k=0 then it is the very first page the original ID was pointing at and that will get a full check of course
1452
                // If $k>0 it is parent pages being tested. They are only significant for the access to the first page IF they had the extendToSubpages flag set, hence checked only then!
1453
                if (!$k || $pagerec['extendToSubpages']) {
1454
                    if ($pagerec['hidden']) {
1455
                        $output['hidden'][$pagerec['uid']] = true;
1456
                    }
1457
                    if ($pagerec['starttime'] > $GLOBALS['SIM_ACCESS_TIME']) {
1458
                        $output['starttime'][$pagerec['uid']] = $pagerec['starttime'];
1459
                    }
1460
                    if ($pagerec['endtime'] != 0 && $pagerec['endtime'] <= $GLOBALS['SIM_ACCESS_TIME']) {
1461
                        $output['endtime'][$pagerec['uid']] = $pagerec['endtime'];
1462
                    }
1463
                    if (!$this->checkPageGroupAccess($pagerec)) {
1464
                        $output['fe_group'][$pagerec['uid']] = $pagerec['fe_group'];
1465
                    }
1466
                }
1467
            }
1468
        }
1469
        return $output;
1470
    }
1471
1472
    /**
1473
     * Gets ->page and ->rootline information based on ->id. ->id may change during this operation.
1474
     * If not inside a site, then default to first page in site.
1475
     *
1476
     * @param int $rootPageId Page uid of the page where the found site is located
1477
     * @internal
1478
     */
1479
    public function getPageAndRootlineWithDomain($rootPageId, ServerRequestInterface $request)
1480
    {
1481
        $this->getPageAndRootline($request);
1482
        // Checks if the $domain-startpage is in the rootLine. This is necessary so that references to page-id's via ?id=123 from other sites are not possible.
1483
        if (is_array($this->rootLine) && $this->rootLine !== []) {
1484
            $idFound = false;
1485
            foreach ($this->rootLine as $key => $val) {
1486
                if ($val['uid'] == $rootPageId) {
1487
                    $idFound = true;
1488
                    break;
1489
                }
1490
            }
1491
            if (!$idFound) {
1492
                // Page is 'not found' in case the id was outside the domain, code 3
1493
                $this->pageNotFound = 3;
1494
                $this->id = $rootPageId;
1495
                // re-get the page and rootline if the id was not found.
1496
                $this->getPageAndRootline($request);
1497
            }
1498
        }
1499
    }
1500
1501
    /********************************************
1502
     *
1503
     * Template and caching related functions.
1504
     *
1505
     *******************************************/
1506
1507
    protected function setPageArguments(PageArguments $pageArguments): void
1508
    {
1509
        $this->pageArguments = $pageArguments;
1510
        $this->id = $pageArguments->getPageId();
1511
        $this->type = $pageArguments->getPageType() ?: 0;
1512
        if ($GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids']) {
1513
            $this->MP = (string)($pageArguments->getArguments()['MP'] ?? '');
1514
        }
1515
    }
1516
1517
    /**
1518
     * Fetches the arguments that are relevant for creating the hash base from the given PageArguments object.
1519
     * Excluded parameters are not taken into account when calculating the hash base.
1520
     *
1521
     * @param PageArguments $pageArguments
1522
     * @return array
1523
     */
1524
    protected function getRelevantParametersForCachingFromPageArguments(PageArguments $pageArguments): array
1525
    {
1526
        $queryParams = $pageArguments->getDynamicArguments();
1527
        if (!empty($queryParams) && $pageArguments->getArguments()['cHash'] ?? false) {
1528
            $queryParams['id'] = $pageArguments->getPageId();
1529
            return GeneralUtility::makeInstance(CacheHashCalculator::class)
1530
                ->getRelevantParameters(HttpUtility::buildQueryString($queryParams));
1531
        }
1532
        return [];
1533
    }
1534
1535
    /**
1536
     * See if page is in cache and get it if so
1537
     * Stores the page content in $this->content if something is found.
1538
     *
1539
     * @param ServerRequestInterface|null $request if given this is used to determine values in headerNoCache() instead of the superglobal $_SERVER
1540
     * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
1541
     */
1542
    public function getFromCache(ServerRequestInterface $request = null)
1543
    {
1544
        // clearing the content-variable, which will hold the pagecontent
1545
        $this->content = '';
1546
        // Unsetting the lowlevel config
1547
        $this->config = [];
1548
        $this->cacheContentFlag = false;
1549
1550
        if ($this->no_cache) {
1551
            return;
1552
        }
1553
1554
        if (!$this->tmpl instanceof TemplateService) {
0 ignored issues
show
introduced by
$this->tmpl is always a sub-type of TYPO3\CMS\Core\TypoScript\TemplateService.
Loading history...
1555
            $this->tmpl = GeneralUtility::makeInstance(TemplateService::class, $this->context, null, $this);
1556
        }
1557
1558
        $pageSectionCacheContent = $this->tmpl->getCurrentPageData((int)$this->id, (string)$this->MP);
1559
        if (!is_array($pageSectionCacheContent)) {
0 ignored issues
show
introduced by
The condition is_array($pageSectionCacheContent) is always true.
Loading history...
1560
            // Nothing in the cache, we acquire an "exclusive lock" for the key now.
1561
            // We use the Registry to store this lock centrally,
1562
            // but we protect the access again with a global exclusive lock to avoid race conditions
1563
1564
            $this->acquireLock('pagesection', $this->id . '::' . $this->MP);
1565
            //
1566
            // from this point on we're the only one working on that page ($key)
1567
            //
1568
1569
            // query the cache again to see if the page data are there meanwhile
1570
            $pageSectionCacheContent = $this->tmpl->getCurrentPageData((int)$this->id, (string)$this->MP);
1571
            if (is_array($pageSectionCacheContent)) {
1572
                // we have the content, nice that some other process did the work for us already
1573
                $this->releaseLock('pagesection');
1574
            }
1575
            // We keep the lock set, because we are the ones generating the page now and filling the cache.
1576
            // This indicates that we have to release the lock later in releaseLocks()
1577
        }
1578
1579
        if (is_array($pageSectionCacheContent)) {
0 ignored issues
show
introduced by
The condition is_array($pageSectionCacheContent) is always true.
Loading history...
1580
            // BE CAREFUL to change the content of the cc-array. This array is serialized and an md5-hash based on this is used for caching the page.
1581
            // If this hash is not the same in here in this section and after page-generation, then the page will not be properly cached!
1582
            // This array is an identification of the template. If $this->all is empty it's because the template-data is not cached, which it must be.
1583
            $pageSectionCacheContent = $this->tmpl->matching($pageSectionCacheContent);
1584
            ksort($pageSectionCacheContent);
1585
            $this->all = $pageSectionCacheContent;
1586
        }
1587
1588
        // Look for page in cache only if a shift-reload is not sent to the server.
1589
        $lockHash = $this->getLockHash();
1590
        if (!$this->headerNoCache($request) && $this->all) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->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...
1591
            // we got page section information (TypoScript), so lets see if there is also a cached version
1592
            // of this page in the pages cache.
1593
            $this->newHash = $this->getHash();
1594
            $this->getTimeTracker()->push('Cache Row');
1595
            $row = $this->getFromCache_queryRow();
1596
            if (!is_array($row)) {
0 ignored issues
show
introduced by
The condition is_array($row) is always true.
Loading history...
1597
                // nothing in the cache, we acquire an exclusive lock now
1598
                $this->acquireLock('pages', $lockHash);
1599
                //
1600
                // from this point on we're the only one working on that page ($lockHash)
1601
                //
1602
1603
                // query the cache again to see if the data are there meanwhile
1604
                $row = $this->getFromCache_queryRow();
1605
                if (is_array($row)) {
1606
                    // we have the content, nice that some other process did the work for us
1607
                    $this->releaseLock('pages');
1608
                }
1609
                // We keep the lock set, because we are the ones generating the page now and filling the cache.
1610
                // This indicates that we have to release the lock later in releaseLocks()
1611
            }
1612
            if (is_array($row)) {
0 ignored issues
show
introduced by
The condition is_array($row) is always true.
Loading history...
1613
                $this->populatePageDataFromCache($row);
1614
            }
1615
            $this->getTimeTracker()->pull();
1616
        } else {
1617
            // the user forced rebuilding the page cache or there was no pagesection information
1618
            // get a lock for the page content so other processes will not interrupt the regeneration
1619
            $this->acquireLock('pages', $lockHash);
1620
        }
1621
    }
1622
1623
    /**
1624
     * Returning the cached version of page with hash = newHash
1625
     *
1626
     * @return array Cached row, if any. Otherwise void.
1627
     */
1628
    public function getFromCache_queryRow()
1629
    {
1630
        $this->getTimeTracker()->push('Cache Query');
1631
        $row = $this->pageCache->get($this->newHash);
1632
        $this->getTimeTracker()->pull();
1633
        return $row;
1634
    }
1635
1636
    /**
1637
     * This method properly sets the values given from the pages cache into the corresponding
1638
     * TSFE variables. The counterpart is setPageCacheContent() where all relevant information is fetched.
1639
     * This also contains all data that could be cached, even for pages that are partially cached, as they
1640
     * have non-cacheable content still to be rendered.
1641
     *
1642
     * @see getFromCache()
1643
     * @see setPageCacheContent()
1644
     * @param array $cachedData
1645
     */
1646
    protected function populatePageDataFromCache(array $cachedData): void
1647
    {
1648
        // Call hook when a page is retrieved from cache
1649
        $_params = ['pObj' => &$this, 'cache_pages_row' => &$cachedData];
1650
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'] ?? [] as $_funcRef) {
1651
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1652
        }
1653
        // Fetches the lowlevel config stored with the cached data
1654
        $this->config = $cachedData['cache_data'];
1655
        // Getting the content
1656
        $this->content = $cachedData['content'];
1657
        // Setting flag, so we know, that some cached content has been loaded
1658
        $this->cacheContentFlag = true;
1659
        $this->cacheExpires = $cachedData['expires'];
1660
        // Restore the current tags as they can be retrieved by getPageCacheTags()
1661
        $this->pageCacheTags = $cachedData['cacheTags'] ?? [];
1662
1663
        // Restore page title information, this is needed to generate the page title for
1664
        // partially cached pages.
1665
        $this->page['title'] = $cachedData['pageTitleInfo']['title'];
1666
        $this->indexedDocTitle = $cachedData['pageTitleInfo']['indexedDocTitle'];
1667
1668
        if (isset($this->config['config']['debug'])) {
1669
            $debugCacheTime = (bool)$this->config['config']['debug'];
1670
        } else {
1671
            $debugCacheTime = !empty($GLOBALS['TYPO3_CONF_VARS']['FE']['debug']);
1672
        }
1673
        if ($debugCacheTime) {
1674
            $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
1675
            $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
1676
            $this->content .= LF . '<!-- Cached page generated ' . date($dateFormat . ' ' . $timeFormat, $cachedData['tstamp']) . '. Expires ' . date($dateFormat . ' ' . $timeFormat, $cachedData['expires']) . ' -->';
1677
        }
1678
    }
1679
1680
    /**
1681
     * Detecting if shift-reload has been clicked
1682
     * Will not be called if re-generation of page happens by other reasons (for instance that the page is not in cache yet!)
1683
     * Also, a backend user MUST be logged in for the shift-reload to be detected due to DoS-attack-security reasons.
1684
     *
1685
     * @param ServerRequestInterface|null $request
1686
     * @return bool If shift-reload in client browser has been clicked, disable getting cached page (and regenerate it).
1687
     */
1688
    public function headerNoCache(ServerRequestInterface $request = null)
1689
    {
1690
        if ($request instanceof ServerRequestInterface) {
1691
            $serverParams = $request->getServerParams();
1692
        } else {
1693
            $serverParams = $_SERVER;
1694
        }
1695
        $disableAcquireCacheData = false;
1696
        if ($this->isBackendUserLoggedIn()) {
1697
            if (strtolower($serverParams['HTTP_CACHE_CONTROL']) === 'no-cache' || strtolower($serverParams['HTTP_PRAGMA']) === 'no-cache') {
1698
                $disableAcquireCacheData = true;
1699
            }
1700
        }
1701
        // Call hook for possible by-pass of requiring of page cache (for recaching purpose)
1702
        $_params = ['pObj' => &$this, 'disableAcquireCacheData' => &$disableAcquireCacheData];
1703
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'] ?? [] as $_funcRef) {
1704
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1705
        }
1706
        return $disableAcquireCacheData;
1707
    }
1708
1709
    /**
1710
     * Calculates the cache-hash
1711
     * This hash is unique to the template, the variables ->id, ->type, list of fe user groups, ->MP (Mount Points) and cHash array
1712
     * Used to get and later store the cached data.
1713
     *
1714
     * @return string MD5 hash of serialized hash base from createHashBase()
1715
     * @see getFromCache()
1716
     * @see getLockHash()
1717
     */
1718
    protected function getHash()
1719
    {
1720
        return md5($this->createHashBase(false));
1721
    }
1722
1723
    /**
1724
     * Calculates the lock-hash
1725
     * This hash is unique to the above hash, except that it doesn't contain the template information in $this->all.
1726
     *
1727
     * @return string MD5 hash
1728
     * @see getFromCache()
1729
     * @see getHash()
1730
     */
1731
    protected function getLockHash()
1732
    {
1733
        $lockHash = $this->createHashBase(true);
1734
        return md5($lockHash);
1735
    }
1736
1737
    /**
1738
     * Calculates the cache-hash (or the lock-hash)
1739
     * This hash is unique to the template,
1740
     * the variables ->id, ->type, list of frontend user groups,
1741
     * ->MP (Mount Points) and cHash array
1742
     * Used to get and later store the cached data.
1743
     *
1744
     * @param bool $createLockHashBase Whether to create the lock hash, which doesn't contain the "this->all" (the template information)
1745
     * @return string the serialized hash base
1746
     */
1747
    protected function createHashBase($createLockHashBase = false)
1748
    {
1749
        // Fetch the list of user groups
1750
        /** @var UserAspect $userAspect */
1751
        $userAspect = $this->context->getAspect('frontend.user');
1752
        $hashParameters = [
1753
            'id' => (int)$this->id,
1754
            'type' => (int)$this->type,
1755
            'groupIds' => (string)implode(',', $userAspect->getGroupIds()),
1756
            'MP' => (string)$this->MP,
1757
            'site' => $this->site->getIdentifier(),
1758
            // Ensure the language base is used for the hash base calculation as well, otherwise TypoScript and page-related rendering
1759
            // is not cached properly as we don't have any language-specific conditions anymore
1760
            'siteBase' => (string)$this->language->getBase(),
1761
            // additional variation trigger for static routes
1762
            'staticRouteArguments' => $this->pageArguments->getStaticArguments(),
1763
            // dynamic route arguments (if route was resolved)
1764
            'dynamicArguments' => $this->getRelevantParametersForCachingFromPageArguments($this->pageArguments),
1765
        ];
1766
        // Include the template information if we shouldn't create a lock hash
1767
        if (!$createLockHashBase) {
1768
            $hashParameters['all'] = $this->all;
1769
        }
1770
        // Call hook to influence the hash calculation
1771
        $_params = [
1772
            'hashParameters' => &$hashParameters,
1773
            'createLockHashBase' => $createLockHashBase
1774
        ];
1775
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['createHashBase'] ?? [] as $_funcRef) {
1776
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1777
        }
1778
        return serialize($hashParameters);
1779
    }
1780
1781
    /**
1782
     * Checks if config-array exists already but if not, gets it
1783
     *
1784
     * @param ServerRequestInterface|null $request
1785
     * @throws ServiceUnavailableException
1786
     */
1787
    public function getConfigArray(ServerRequestInterface $request = null)
1788
    {
1789
        $request = $request ?? $GLOBALS['TYPO3_REQUEST'] ?? ServerRequestFactory::fromGlobals();
1790
        if (!$this->tmpl instanceof TemplateService) {
0 ignored issues
show
introduced by
$this->tmpl is always a sub-type of TYPO3\CMS\Core\TypoScript\TemplateService.
Loading history...
1791
            $this->tmpl = GeneralUtility::makeInstance(TemplateService::class, $this->context, null, $this);
1792
        }
1793
1794
        // If config is not set by the cache (which would be a major mistake somewhere) OR if INTincScripts-include-scripts have been registered, then we must parse the template in order to get it
1795
        if (empty($this->config) || $this->isINTincScript() || $this->context->getPropertyFromAspect('typoscript', 'forcedTemplateParsing')) {
1796
            $timeTracker = $this->getTimeTracker();
1797
            $timeTracker->push('Parse template');
1798
            // Start parsing the TS template. Might return cached version.
1799
            $this->tmpl->start($this->rootLine);
1800
            $timeTracker->pull();
1801
            // At this point we have a valid pagesection_cache (generated in $this->tmpl->start()),
1802
            // so let all other processes proceed now. (They are blocked at the pagessection_lock in getFromCache())
1803
            $this->releaseLock('pagesection');
1804
            if ($this->tmpl->loaded) {
1805
                $timeTracker->push('Setting the config-array');
1806
                // toplevel - objArrayName
1807
                $typoScriptPageTypeName = $this->tmpl->setup['types.'][$this->type];
1808
                $this->sPre = $typoScriptPageTypeName;
1809
                $this->pSetup = $this->tmpl->setup[$typoScriptPageTypeName . '.'];
1810
                if (!is_array($this->pSetup)) {
1811
                    $message = 'The page is not configured! [type=' . $this->type . '][' . $typoScriptPageTypeName . '].';
1812
                    $this->logger->alert($message);
1813
                    try {
1814
                        $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
1815
                            $request,
1816
                            $message,
1817
                            ['code' => PageAccessFailureReasons::RENDERING_INSTRUCTIONS_NOT_CONFIGURED]
1818
                        );
1819
                        throw new ImmediateResponseException($response, 1533931374);
1820
                    } catch (PageNotFoundException $e) {
1821
                        $explanation = 'This means that there is no TypoScript object of type PAGE with typeNum=' . $this->type . ' configured.';
1822
                        throw new ServiceUnavailableException($message . ' ' . $explanation, 1294587217);
1823
                    }
1824
                } else {
1825
                    if (!isset($this->config['config'])) {
1826
                        $this->config['config'] = [];
1827
                    }
1828
                    // Filling the config-array, first with the main "config." part
1829
                    if (is_array($this->tmpl->setup['config.'])) {
1830
                        ArrayUtility::mergeRecursiveWithOverrule($this->tmpl->setup['config.'], $this->config['config']);
1831
                        $this->config['config'] = $this->tmpl->setup['config.'];
1832
                    }
1833
                    // override it with the page/type-specific "config."
1834
                    if (is_array($this->pSetup['config.'])) {
1835
                        ArrayUtility::mergeRecursiveWithOverrule($this->config['config'], $this->pSetup['config.']);
1836
                    }
1837
                    // Set default values for removeDefaultJS and inlineStyle2TempFile so CSS and JS are externalized if compatversion is higher than 4.0
1838
                    if (!isset($this->config['config']['removeDefaultJS'])) {
1839
                        $this->config['config']['removeDefaultJS'] = 'external';
1840
                    }
1841
                    if (!isset($this->config['config']['inlineStyle2TempFile'])) {
1842
                        $this->config['config']['inlineStyle2TempFile'] = 1;
1843
                    }
1844
1845
                    if (!isset($this->config['config']['compressJs'])) {
1846
                        $this->config['config']['compressJs'] = 0;
1847
                    }
1848
                    // Rendering charset of HTML page.
1849
                    if (isset($this->config['config']['metaCharset']) && $this->config['config']['metaCharset'] !== 'utf-8') {
1850
                        $this->metaCharset = $this->config['config']['metaCharset'];
1851
                    }
1852
                    // Setting default cache_timeout
1853
                    if (isset($this->config['config']['cache_period'])) {
1854
                        $this->set_cache_timeout_default((int)$this->config['config']['cache_period']);
1855
                    }
1856
1857
                    // Processing for the config_array:
1858
                    $this->config['rootLine'] = $this->tmpl->rootLine;
1859
                    // Class for render Header and Footer parts
1860
                    if ($this->pSetup['pageHeaderFooterTemplateFile']) {
1861
                        try {
1862
                            $file = GeneralUtility::makeInstance(FilePathSanitizer::class)
1863
                                ->sanitize((string)$this->pSetup['pageHeaderFooterTemplateFile']);
1864
                            $this->pageRenderer->setTemplateFile($file);
1865
                        } catch (Exception $e) {
1866
                            // do nothing
1867
                        }
1868
                    }
1869
                }
1870
                $timeTracker->pull();
1871
            } else {
1872
                $message = 'No TypoScript template found!';
1873
                $this->logger->alert($message);
1874
                try {
1875
                    $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction(
1876
                        $request,
1877
                        $message,
1878
                        ['code' => PageAccessFailureReasons::RENDERING_INSTRUCTIONS_NOT_FOUND]
1879
                    );
1880
                    throw new ImmediateResponseException($response, 1533931380);
1881
                } catch (ServiceUnavailableException $e) {
1882
                    throw new ServiceUnavailableException($message, 1294587218);
1883
                }
1884
            }
1885
        }
1886
1887
        // No cache
1888
        // Set $this->no_cache TRUE if the config.no_cache value is set!
1889
        if ($this->config['config']['no_cache']) {
1890
            $this->set_no_cache('config.no_cache is set', true);
1891
        }
1892
1893
        // Auto-configure settings when a site is configured
1894
        $this->config['config']['absRefPrefix'] = $this->config['config']['absRefPrefix'] ?? 'auto';
1895
1896
        // Hook for postProcessing the configuration array
1897
        $params = ['config' => &$this->config['config']];
1898
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'] ?? [] as $funcRef) {
1899
            GeneralUtility::callUserFunction($funcRef, $params, $this);
1900
        }
1901
    }
1902
1903
    /********************************************
1904
     *
1905
     * Further initialization and data processing
1906
     *
1907
     *******************************************/
1908
    /**
1909
     * Setting the language key that will be used by the current page.
1910
     * In this function it should be checked, 1) that this language exists, 2) that a page_overlay_record exists, .. and if not the default language, 0 (zero), should be set.
1911
     *
1912
     * @param ServerRequestInterface|null $request
1913
     * @internal
1914
     */
1915
    public function settingLanguage(ServerRequestInterface $request = null)
1916
    {
1917
        $request = $request ?? $GLOBALS['TYPO3_REQUEST'] ?? ServerRequestFactory::fromGlobals();
1918
        $_params = [];
1919
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'] ?? [] as $_funcRef) {
1920
            $ref = $this; // introduced for phpstan to not lose type information when passing $this into callUserFunction
1921
            GeneralUtility::callUserFunction($_funcRef, $_params, $ref);
1922
        }
1923
1924
        // Get values from site language
1925
        $languageAspect = LanguageAspectFactory::createFromSiteLanguage($this->language);
1926
1927
        $languageId = $languageAspect->getId();
1928
        $languageContentId = $languageAspect->getContentId();
1929
1930
        // If sys_language_uid is set to another language than default:
1931
        if ($languageAspect->getId() > 0) {
1932
            // check whether a shortcut is overwritten by a translated page
1933
            // we can only do this now, as this is the place where we get
1934
            // to know about translations
1935
            $this->checkTranslatedShortcut($languageAspect->getId(), $request);
1936
            // Request the overlay record for the sys_language_uid:
1937
            $olRec = $this->sys_page->getPageOverlay($this->id, $languageAspect->getId());
1938
            if (empty($olRec)) {
1939
                // If requested translation is not available:
1940
                if (GeneralUtility::hideIfNotTranslated($this->page['l18n_cfg'])) {
1941
                    $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
1942
                        $request,
1943
                        'Page is not available in the requested language.',
1944
                        ['code' => PageAccessFailureReasons::LANGUAGE_NOT_AVAILABLE]
1945
                    );
1946
                    throw new ImmediateResponseException($response, 1533931388);
1947
                }
1948
                switch ((string)$languageAspect->getLegacyLanguageMode()) {
1949
                    case 'strict':
1950
                        $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
1951
                            $request,
1952
                            'Page is not available in the requested language (strict).',
1953
                            ['code' => PageAccessFailureReasons::LANGUAGE_NOT_AVAILABLE_STRICT_MODE]
1954
                        );
1955
                        throw new ImmediateResponseException($response, 1533931395);
1956
                    case 'fallback':
1957
                    case 'content_fallback':
1958
                        // Setting content uid (but leaving the sys_language_uid) when a content_fallback
1959
                        // value was found.
1960
                        foreach ($languageAspect->getFallbackChain() ?? [] as $orderValue) {
1961
                            if ($orderValue === '0' || $orderValue === 0 || $orderValue === '') {
1962
                                $languageContentId = 0;
1963
                                break;
1964
                            }
1965
                            if (MathUtility::canBeInterpretedAsInteger($orderValue) && !empty($this->sys_page->getPageOverlay($this->id, (int)$orderValue))) {
1966
                                $languageContentId = (int)$orderValue;
1967
                                break;
1968
                            }
1969
                            if ($orderValue === 'pageNotFound') {
1970
                                // The existing fallbacks have not been found, but instead of continuing
1971
                                // page rendering with default language, a "page not found" message should be shown
1972
                                // instead.
1973
                                $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
1974
                                    $request,
1975
                                    'Page is not available in the requested language (fallbacks did not apply).',
1976
                                    ['code' => PageAccessFailureReasons::LANGUAGE_AND_FALLBACKS_NOT_AVAILABLE]
1977
                                );
1978
                                throw new ImmediateResponseException($response, 1533931402);
1979
                            }
1980
                        }
1981
                        break;
1982
                    case 'ignore':
1983
                        $languageContentId = $languageAspect->getId();
1984
                        break;
1985
                    default:
1986
                        // Default is that everything defaults to the default language...
1987
                        $languageId = ($languageContentId = 0);
1988
                }
1989
            }
1990
1991
            // Define the language aspect again now
1992
            $languageAspect = GeneralUtility::makeInstance(
1993
                LanguageAspect::class,
1994
                $languageId,
1995
                $languageContentId,
1996
                $languageAspect->getOverlayType(),
1997
                $languageAspect->getFallbackChain()
1998
            );
1999
2000
            // Setting sys_language if an overlay record was found (which it is only if a language is used)
2001
            // We'll do this every time since the language aspect might have changed now
2002
            // Doing this ensures that page properties like the page title are returned in the correct language
2003
            $this->page = $this->sys_page->getPageOverlay($this->page, $languageAspect->getContentId());
2004
2005
            // Update SYS_LASTCHANGED for localized page record
2006
            $this->setRegisterValueForSysLastChanged($this->page);
2007
        }
2008
2009
        // Set the language aspect
2010
        $this->context->setAspect('language', $languageAspect);
2011
2012
        // Setting sys_language_uid inside sys-page by creating a new page repository
2013
        $this->sys_page = GeneralUtility::makeInstance(PageRepository::class, $this->context);
2014
        // If default language is not available:
2015
        if ((!$languageAspect->getContentId() || !$languageAspect->getId())
2016
            && GeneralUtility::hideIfDefaultLanguage($this->page['l18n_cfg'] ?? 0)
2017
        ) {
2018
            $message = 'Page is not available in default language.';
2019
            $this->logger->error($message);
2020
            $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction(
2021
                $request,
2022
                $message,
2023
                ['code' => PageAccessFailureReasons::LANGUAGE_DEFAULT_NOT_AVAILABLE]
2024
            );
2025
            throw new ImmediateResponseException($response, 1533931423);
2026
        }
2027
2028
        if ($languageAspect->getId() > 0) {
2029
            $this->updateRootLinesWithTranslations();
2030
        }
2031
2032
        $_params = [];
2033
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'] ?? [] as $_funcRef) {
2034
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2035
        }
2036
    }
2037
2038
    /**
2039
     * Updating content of the two rootLines IF the language key is set!
2040
     */
2041
    protected function updateRootLinesWithTranslations()
2042
    {
2043
        try {
2044
            $this->rootLine = GeneralUtility::makeInstance(RootlineUtility::class, $this->id, $this->MP, $this->context)->get();
2045
        } catch (RootLineException $e) {
2046
            $this->rootLine = [];
2047
        }
2048
    }
2049
2050
    /**
2051
     * Checks whether a translated shortcut page has a different shortcut
2052
     * target than the original language page.
2053
     * If that is the case, things get corrected to follow that alternative
2054
     * shortcut
2055
     * @param int $languageId
2056
     * @param ServerRequestInterface $request
2057
     */
2058
    protected function checkTranslatedShortcut(int $languageId, ServerRequestInterface $request)
2059
    {
2060
        if (!is_null($this->originalShortcutPage)) {
2061
            $originalShortcutPageOverlay = $this->sys_page->getPageOverlay($this->originalShortcutPage['uid'], $languageId);
2062
            if (!empty($originalShortcutPageOverlay['shortcut']) && $originalShortcutPageOverlay['shortcut'] != $this->id) {
2063
                // the translation of the original shortcut page has a different shortcut target!
2064
                // set the correct page and id
2065
                $shortcut = $this->sys_page->getPageShortcut($originalShortcutPageOverlay['shortcut'], $originalShortcutPageOverlay['shortcut_mode'], $originalShortcutPageOverlay['uid']);
2066
                $this->id = ($this->contentPid = $shortcut['uid']);
2067
                $this->page = $this->sys_page->getPage($this->id);
2068
                // Fix various effects on things like menus f.e.
2069
                $this->fetch_the_id($request);
2070
                $this->tmpl->rootLine = array_reverse($this->rootLine);
2071
            }
2072
        }
2073
    }
2074
2075
    /**
2076
     * Calculates and sets the internal linkVars based upon the current request parameters
2077
     * and the setting "config.linkVars".
2078
     *
2079
     * @param array $queryParams $_GET (usually called with a PSR-7 $request->getQueryParams())
2080
     */
2081
    public function calculateLinkVars(array $queryParams)
2082
    {
2083
        $this->linkVars = '';
2084
        $adminCommand = $queryParams['ADMCMD_prev'] ?? '';
2085
        if (($adminCommand === 'LIVE' || $adminCommand === 'IGNORE') && $this->isBackendUserLoggedIn()) {
2086
            $this->config['config']['linkVars'] = ltrim(($this->config['config']['linkVars'] ?? '') . ',ADMCMD_prev', ',');
2087
        }
2088
        if (empty($this->config['config']['linkVars'])) {
2089
            return;
2090
        }
2091
2092
        $linkVars = $this->splitLinkVarsString((string)$this->config['config']['linkVars']);
2093
2094
        if (empty($linkVars)) {
2095
            return;
2096
        }
2097
        foreach ($linkVars as $linkVar) {
2098
            $test = $value = '';
2099
            if (preg_match('/^(.*)\\((.+)\\)$/', $linkVar, $match)) {
2100
                $linkVar = trim($match[1]);
2101
                $test = trim($match[2]);
2102
            }
2103
2104
            $keys = explode('|', $linkVar);
2105
            $numberOfLevels = count($keys);
2106
            $rootKey = trim($keys[0]);
2107
            if (!isset($queryParams[$rootKey])) {
2108
                continue;
2109
            }
2110
            $value = $queryParams[$rootKey];
2111
            for ($i = 1; $i < $numberOfLevels; $i++) {
2112
                $currentKey = trim($keys[$i]);
2113
                if (isset($value[$currentKey])) {
2114
                    $value = $value[$currentKey];
2115
                } else {
2116
                    $value = false;
2117
                    break;
2118
                }
2119
            }
2120
            if ($value !== false) {
2121
                $parameterName = $keys[0];
2122
                for ($i = 1; $i < $numberOfLevels; $i++) {
2123
                    $parameterName .= '[' . $keys[$i] . ']';
2124
                }
2125
                if (!is_array($value)) {
2126
                    $temp = rawurlencode($value);
2127
                    if ($test !== '' && !$this->isAllowedLinkVarValue($temp, $test)) {
2128
                        // Error: This value was not allowed for this key
2129
                        continue;
2130
                    }
2131
                    $value = '&' . $parameterName . '=' . $temp;
2132
                } else {
2133
                    if ($test !== '' && $test !== 'array') {
2134
                        // Error: This key must not be an array!
2135
                        continue;
2136
                    }
2137
                    $value = HttpUtility::buildQueryString([$parameterName => $value], '&');
2138
                }
2139
                $this->linkVars .= $value;
2140
            }
2141
        }
2142
    }
2143
2144
    /**
2145
     * Split the link vars string by "," but not if the "," is inside of braces
2146
     *
2147
     * @param string $string
2148
     *
2149
     * @return array
2150
     */
2151
    protected function splitLinkVarsString(string $string): array
2152
    {
2153
        $tempCommaReplacementString = '###KASPER###';
2154
2155
        // replace every "," wrapped in "()" by a "unique" string
2156
        $string = preg_replace_callback('/\((?>[^()]|(?R))*\)/', function ($result) use ($tempCommaReplacementString) {
2157
            return str_replace(',', $tempCommaReplacementString, $result[0]);
2158
        }, $string) ?? '';
2159
2160
        $string = GeneralUtility::trimExplode(',', $string);
2161
2162
        // replace all "unique" strings back to ","
2163
        return str_replace($tempCommaReplacementString, ',', $string);
2164
    }
2165
2166
    /**
2167
     * Checks if the value defined in "config.linkVars" contains an allowed value.
2168
     * Otherwise, return FALSE which means the value will not be added to any links.
2169
     *
2170
     * @param string $haystack The string in which to find $needle
2171
     * @param string $needle The string to find in $haystack
2172
     * @return bool Returns TRUE if $needle matches or is found in $haystack
2173
     */
2174
    protected function isAllowedLinkVarValue(string $haystack, string $needle): bool
2175
    {
2176
        $isAllowed = false;
2177
        // Integer
2178
        if ($needle === 'int' || $needle === 'integer') {
2179
            if (MathUtility::canBeInterpretedAsInteger($haystack)) {
2180
                $isAllowed = true;
2181
            }
2182
        } elseif (preg_match('/^\\/.+\\/[imsxeADSUXu]*$/', $needle)) {
2183
            // Regular expression, only "//" is allowed as delimiter
2184
            if (@preg_match($needle, $haystack)) {
2185
                $isAllowed = true;
2186
            }
2187
        } elseif (strpos($needle, '-') !== false) {
2188
            // Range
2189
            if (MathUtility::canBeInterpretedAsInteger($haystack)) {
2190
                $range = explode('-', $needle);
2191
                if ($range[0] <= $haystack && $range[1] >= $haystack) {
2192
                    $isAllowed = true;
2193
                }
2194
            }
2195
        } elseif (strpos($needle, '|') !== false) {
2196
            // List
2197
            // Trim the input
2198
            $haystack = str_replace(' ', '', $haystack);
2199
            if (strpos('|' . $needle . '|', '|' . $haystack . '|') !== false) {
2200
                $isAllowed = true;
2201
            }
2202
        } elseif ((string)$needle === (string)$haystack) {
2203
            // String comparison
2204
            $isAllowed = true;
2205
        }
2206
        return $isAllowed;
2207
    }
2208
2209
    /**
2210
     * Returns URI of target page, if the current page is an overlaid mountpoint.
2211
     *
2212
     * If the current page is of type mountpoint and should be overlaid with the contents of the mountpoint page
2213
     * and is accessed directly, the user will be redirected to the mountpoint context.
2214
     * @internal
2215
     * @param ServerRequestInterface $request
2216
     * @return string|null
2217
     */
2218
    public function getRedirectUriForMountPoint(ServerRequestInterface $request): ?string
2219
    {
2220
        if (!empty($this->originalMountPointPage) && (int)$this->originalMountPointPage['doktype'] === PageRepository::DOKTYPE_MOUNTPOINT) {
2221
            return $this->getUriToCurrentPageForRedirect($request);
2222
        }
2223
2224
        return null;
2225
    }
2226
2227
    /**
2228
     * Returns URI of target page, if the current page is a Shortcut.
2229
     *
2230
     * If the current page is of type shortcut and accessed directly via its URL,
2231
     * the user will be redirected to shortcut target.
2232
     *
2233
     * @internal
2234
     * @param ServerRequestInterface $request
2235
     * @return string|null
2236
     */
2237
    public function getRedirectUriForShortcut(ServerRequestInterface $request): ?string
2238
    {
2239
        if (!empty($this->originalShortcutPage) && $this->originalShortcutPage['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
2240
            return $this->getUriToCurrentPageForRedirect($request);
2241
        }
2242
2243
        return null;
2244
    }
2245
2246
    /**
2247
     * Instantiate \TYPO3\CMS\Frontend\ContentObject to generate the correct target URL
2248
     *
2249
     * @param ServerRequestInterface $request
2250
     * @return string
2251
     */
2252
    protected function getUriToCurrentPageForRedirect(ServerRequestInterface $request): string
2253
    {
2254
        $this->calculateLinkVars($request->getQueryParams());
2255
        $parameter = $this->page['uid'];
2256
        if ($this->type && MathUtility::canBeInterpretedAsInteger($this->type)) {
2257
            $parameter .= ',' . $this->type;
2258
        }
2259
        return GeneralUtility::makeInstance(ContentObjectRenderer::class, $this)->typoLink_URL([
2260
            'parameter' => $parameter,
2261
            'addQueryString' => true,
2262
            'addQueryString.' => ['exclude' => 'id'],
2263
            'forceAbsoluteUrl' => true
2264
        ]);
2265
    }
2266
2267
    /********************************************
2268
     *
2269
     * Page generation; cache handling
2270
     *
2271
     *******************************************/
2272
    /**
2273
     * Returns TRUE if the page should be generated.
2274
     * That is if no URL handler is active and the cacheContentFlag is not set.
2275
     *
2276
     * @return bool
2277
     */
2278
    public function isGeneratePage()
2279
    {
2280
        return !$this->cacheContentFlag;
2281
    }
2282
2283
    /**
2284
     * Set cache content to $this->content
2285
     */
2286
    protected function realPageCacheContent()
2287
    {
2288
        // seconds until a cached page is too old
2289
        $cacheTimeout = $this->get_cache_timeout();
2290
        $timeOutTime = $GLOBALS['EXEC_TIME'] + $cacheTimeout;
2291
        $usePageCache = true;
2292
        // Hook for deciding whether page cache should be written to the cache backend or not
2293
        // NOTE: as hooks are called in a loop, the last hook will have the final word (however each
2294
        // hook receives the current status of the $usePageCache flag)
2295
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['usePageCache'] ?? [] as $className) {
2296
            $usePageCache = GeneralUtility::makeInstance($className)->usePageCache($this, $usePageCache);
2297
        }
2298
        // Write the page to cache, if necessary
2299
        if ($usePageCache) {
2300
            $this->setPageCacheContent($this->content, $this->config, $timeOutTime);
2301
        }
2302
        // Hook for cache post processing (eg. writing static files!)
2303
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['insertPageIncache'] ?? [] as $className) {
2304
            GeneralUtility::makeInstance($className)->insertPageIncache($this, $timeOutTime);
2305
        }
2306
    }
2307
2308
    /**
2309
     * Sets cache content; Inserts the content string into the cache_pages cache.
2310
     *
2311
     * @param string $content The content to store in the HTML field of the cache table
2312
     * @param mixed $data The additional cache_data array, fx. $this->config
2313
     * @param int $expirationTstamp Expiration timestamp
2314
     * @see realPageCacheContent()
2315
     */
2316
    protected function setPageCacheContent($content, $data, $expirationTstamp)
2317
    {
2318
        $cacheData = [
2319
            'identifier' => $this->newHash,
2320
            'page_id' => $this->id,
2321
            'content' => $content,
2322
            'cache_data' => $data,
2323
            'expires' => $expirationTstamp,
2324
            'tstamp' => $GLOBALS['EXEC_TIME'],
2325
            'pageTitleInfo' => [
2326
                'title' => $this->page['title'],
2327
                'indexedDocTitle' => $this->indexedDocTitle
2328
            ]
2329
        ];
2330
        $this->cacheExpires = $expirationTstamp;
2331
        $this->pageCacheTags[] = 'pageId_' . $cacheData['page_id'];
2332
        // Respect the page cache when content of pid is shown
2333
        if ($this->id !== $this->contentPid) {
0 ignored issues
show
introduced by
The condition $this->id !== $this->contentPid is always true.
Loading history...
2334
            $this->pageCacheTags[] = 'pageId_' . $this->contentPid;
2335
        }
2336
        if (!empty($this->page['cache_tags'])) {
2337
            $tags = GeneralUtility::trimExplode(',', $this->page['cache_tags'], true);
2338
            $this->pageCacheTags = array_merge($this->pageCacheTags, $tags);
2339
        }
2340
        // Add the cache themselves as well, because they are fetched by getPageCacheTags()
2341
        $cacheData['cacheTags'] = $this->pageCacheTags;
2342
        $this->pageCache->set($this->newHash, $cacheData, $this->pageCacheTags, $expirationTstamp - $GLOBALS['EXEC_TIME']);
2343
    }
2344
2345
    /**
2346
     * Clears cache content (for $this->newHash)
2347
     */
2348
    public function clearPageCacheContent()
2349
    {
2350
        $this->pageCache->remove($this->newHash);
2351
    }
2352
2353
    /**
2354
     * Sets sys last changed
2355
     * Setting the SYS_LASTCHANGED value in the pagerecord: This value will thus be set to the highest tstamp of records rendered on the page. This includes all records with no regard to hidden records, userprotection and so on.
2356
     *
2357
     * @see ContentObjectRenderer::lastChanged()
2358
     */
2359
    protected function setSysLastChanged()
2360
    {
2361
        // We only update the info if browsing the live workspace
2362
        if ($this->page['SYS_LASTCHANGED'] < (int)$this->register['SYS_LASTCHANGED'] && !$this->doWorkspacePreview()) {
2363
            $connection = GeneralUtility::makeInstance(ConnectionPool::class)
2364
                ->getConnectionForTable('pages');
2365
            $pageId = $this->page['_PAGES_OVERLAY_UID'] ?? $this->id;
2366
            $connection->update(
2367
                'pages',
2368
                [
2369
                    'SYS_LASTCHANGED' => (int)$this->register['SYS_LASTCHANGED']
2370
                ],
2371
                [
2372
                    'uid' => (int)$pageId
2373
                ]
2374
            );
2375
        }
2376
    }
2377
2378
    /**
2379
     * Set the SYS_LASTCHANGED register value, is also called when a translated page is in use,
2380
     * so the register reflects the state of the translated page, not the page in the default language.
2381
     *
2382
     * @param array $page
2383
     * @internal
2384
     */
2385
    protected function setRegisterValueForSysLastChanged(array $page): void
2386
    {
2387
        $this->register['SYS_LASTCHANGED'] = (int)$page['tstamp'];
2388
        if ($this->register['SYS_LASTCHANGED'] < (int)$page['SYS_LASTCHANGED']) {
2389
            $this->register['SYS_LASTCHANGED'] = (int)$page['SYS_LASTCHANGED'];
2390
        }
2391
    }
2392
2393
    /**
2394
     * Release pending locks
2395
     *
2396
     * @internal
2397
     */
2398
    public function releaseLocks()
2399
    {
2400
        $this->releaseLock('pagesection');
2401
        $this->releaseLock('pages');
2402
    }
2403
2404
    /**
2405
     * Adds tags to this page's cache entry, you can then f.e. remove cache
2406
     * entries by tag
2407
     *
2408
     * @param array $tags An array of tag
2409
     */
2410
    public function addCacheTags(array $tags)
2411
    {
2412
        $this->pageCacheTags = array_merge($this->pageCacheTags, $tags);
2413
    }
2414
2415
    /**
2416
     * @return array
2417
     */
2418
    public function getPageCacheTags(): array
2419
    {
2420
        return $this->pageCacheTags;
2421
    }
2422
2423
    /********************************************
2424
     *
2425
     * Page generation; rendering and inclusion
2426
     *
2427
     *******************************************/
2428
    /**
2429
     * Does some processing BEFORE the page content is generated / built.
2430
     */
2431
    public function generatePage_preProcessing()
2432
    {
2433
        // Same codeline as in getFromCache(). But $this->all has been changed by
2434
        // \TYPO3\CMS\Core\TypoScript\TemplateService::start() in the meantime, so this must be called again!
2435
        $this->newHash = $this->getHash();
2436
2437
        // Used as a safety check in case a PHP script is falsely disabling $this->no_cache during page generation.
2438
        $this->no_cacheBeforePageGen = $this->no_cache;
2439
    }
2440
2441
    /**
2442
     * Check the value of "content_from_pid" of the current page record, and see if the current request
2443
     * should actually show content from another page.
2444
     *
2445
     * By using $TSFE->getPageAndRootline() on the cloned object, all rootline restrictions (extendToSubPages)
2446
     * are evaluated as well.
2447
     *
2448
     * @param ServerRequestInterface $request
2449
     * @return int the current page ID or another one if resolved properly - usually set to $this->contentPid
2450
     */
2451
    protected function resolveContentPid(ServerRequestInterface $request): int
2452
    {
2453
        if (!isset($this->page['content_from_pid']) || empty($this->page['content_from_pid'])) {
2454
            return (int)$this->id;
2455
        }
2456
        // make REAL copy of TSFE object - not reference!
2457
        $temp_copy_TSFE = clone $this;
2458
        // Set ->id to the content_from_pid value - we are going to evaluate this pid as was it a given id for a page-display!
2459
        $temp_copy_TSFE->id = $this->page['content_from_pid'];
2460
        $temp_copy_TSFE->MP = '';
2461
        $temp_copy_TSFE->getPageAndRootline($request);
2462
        return (int)$temp_copy_TSFE->id;
2463
    }
2464
    /**
2465
     * Sets up TypoScript "config." options and set properties in $TSFE.
2466
     *
2467
     * @param ServerRequestInterface $request
2468
     */
2469
    public function preparePageContentGeneration(ServerRequestInterface $request)
2470
    {
2471
        $this->getTimeTracker()->push('Prepare page content generation');
2472
        $this->contentPid = $this->resolveContentPid($request);
2473
        // Global vars...
2474
        $this->indexedDocTitle = $this->page['title'] ?? null;
2475
        // Base url:
2476
        if (isset($this->config['config']['baseURL'])) {
2477
            $this->baseUrl = $this->config['config']['baseURL'];
2478
        }
2479
        // Internal and External target defaults
2480
        $this->intTarget = (string)($this->config['config']['intTarget'] ?? '');
2481
        $this->extTarget = (string)($this->config['config']['extTarget'] ?? '');
2482
        $this->fileTarget = (string)($this->config['config']['fileTarget'] ?? '');
2483
        $this->spamProtectEmailAddresses = $this->config['config']['spamProtectEmailAddresses'] ?? 0;
2484
        if ($this->spamProtectEmailAddresses !== 'ascii') {
2485
            $this->spamProtectEmailAddresses = MathUtility::forceIntegerInRange($this->spamProtectEmailAddresses, -10, 10, 0);
2486
        }
2487
        // calculate the absolute path prefix
2488
        if (!empty($this->config['config']['absRefPrefix'])) {
2489
            $absRefPrefix = trim($this->config['config']['absRefPrefix']);
2490
            if ($absRefPrefix === 'auto') {
2491
                $this->absRefPrefix = GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
2492
            } else {
2493
                $this->absRefPrefix = $absRefPrefix;
2494
            }
2495
        } else {
2496
            $this->absRefPrefix = '';
2497
        }
2498
        $this->ATagParams = trim($this->config['config']['ATagParams'] ?? '') ? ' ' . trim($this->config['config']['ATagParams']) : '';
2499
        $this->initializeSearchWordData($request->getParsedBody()['sword_list'] ?? $request->getQueryParams()['sword_list'] ?? null);
2500
        // linkVars
2501
        $this->calculateLinkVars($request->getQueryParams());
2502
        // Setting XHTML-doctype from doctype
2503
        if (!isset($this->config['config']['xhtmlDoctype']) || !$this->config['config']['xhtmlDoctype']) {
2504
            $this->config['config']['xhtmlDoctype'] = $this->config['config']['doctype'] ?? '';
2505
        }
2506
        if ($this->config['config']['xhtmlDoctype']) {
2507
            $this->xhtmlDoctype = $this->config['config']['xhtmlDoctype'];
2508
            // Checking XHTML-docytpe
2509
            switch ((string)$this->config['config']['xhtmlDoctype']) {
2510
                case 'xhtml_trans':
2511
                case 'xhtml_strict':
2512
                    $this->xhtmlVersion = 100;
2513
                    break;
2514
                case 'xhtml_basic':
2515
                    $this->xhtmlVersion = 105;
2516
                    break;
2517
                case 'xhtml_11':
2518
                case 'xhtml+rdfa_10':
2519
                    $this->xhtmlVersion = 110;
2520
                    break;
2521
                default:
2522
                    $this->pageRenderer->setRenderXhtml(false);
2523
                    $this->xhtmlDoctype = '';
2524
                    $this->xhtmlVersion = 0;
2525
            }
2526
        } else {
2527
            $this->pageRenderer->setRenderXhtml(false);
2528
        }
2529
2530
        // Global content object
2531
        $this->newCObj();
2532
        $this->getTimeTracker()->pull();
2533
    }
2534
2535
    /**
2536
     * Fills the sWordList property and builds the regular expression in TSFE that can be used to split
2537
     * strings by the submitted search words.
2538
     *
2539
     * @param mixed $searchWords - usually an array, but we can't be sure (yet)
2540
     * @see sWordList
2541
     * @see sWordRegEx
2542
     */
2543
    protected function initializeSearchWordData($searchWords)
2544
    {
2545
        $this->sWordRegEx = '';
2546
        $this->sWordList = $searchWords ?? '';
2547
        if (is_array($this->sWordList)) {
2548
            $space = !empty($this->config['config']['sword_standAlone'] ?? null) ? '[[:space:]]' : '';
2549
            $regexpParts = [];
2550
            foreach ($this->sWordList as $val) {
2551
                if (trim($val) !== '') {
2552
                    $regexpParts[] = $space . preg_quote($val, '/') . $space;
2553
                }
2554
            }
2555
            $this->sWordRegEx = implode('|', $regexpParts);
2556
        }
2557
    }
2558
2559
    /**
2560
     * Does processing of the content after the page content was generated.
2561
     *
2562
     * This includes caching the page, indexing the page (if configured) and setting sysLastChanged
2563
     */
2564
    public function generatePage_postProcessing()
2565
    {
2566
        $this->setAbsRefPrefix();
2567
        // This is to ensure, that the page is NOT cached if the no_cache parameter was set before the page was generated. This is a safety precaution, as it could have been unset by some script.
2568
        if ($this->no_cacheBeforePageGen) {
2569
            $this->set_no_cache('no_cache has been set before the page was generated - safety check', true);
2570
        }
2571
        // Hook for post-processing of page content cached/non-cached:
2572
        $_params = ['pObj' => &$this];
2573
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-all'] ?? [] as $_funcRef) {
2574
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2575
        }
2576
        // Processing if caching is enabled:
2577
        if (!$this->no_cache) {
2578
            // Hook for post-processing of page content before being cached:
2579
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-cached'] ?? [] as $_funcRef) {
2580
                GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2581
            }
2582
        }
2583
        // Convert charset for output. Any hooks before (including indexed search) will have to convert from UTF-8 to the target
2584
        // charset as well.
2585
        $this->content = $this->convOutputCharset($this->content);
2586
        // Storing for cache:
2587
        if (!$this->no_cache) {
2588
            $this->realPageCacheContent();
2589
        }
2590
        // Sets sys-last-change:
2591
        $this->setSysLastChanged();
2592
    }
2593
2594
    /**
2595
     * Generate the page title, can be called multiple times,
2596
     * as PageTitleProvider might have been modified by an uncached plugin etc.
2597
     *
2598
     * @return string the generated page title
2599
     */
2600
    public function generatePageTitle(): string
2601
    {
2602
        // Check for a custom pageTitleSeparator, and perform stdWrap on it
2603
        $pageTitleSeparator = (string)$this->cObj->stdWrapValue('pageTitleSeparator', $this->config['config'] ?? []);
2604
        if ($pageTitleSeparator !== '' && $pageTitleSeparator === ($this->config['config']['pageTitleSeparator'] ?? '')) {
2605
            $pageTitleSeparator .= ' ';
2606
        }
2607
2608
        $titleProvider = GeneralUtility::makeInstance(PageTitleProviderManager::class);
2609
        if (!empty($this->config['config']['pageTitleCache'])) {
2610
            $titleProvider->setPageTitleCache($this->config['config']['pageTitleCache']);
2611
        }
2612
        $pageTitle = $titleProvider->getTitle();
2613
        $this->config['config']['pageTitleCache'] = $titleProvider->getPageTitleCache();
2614
2615
        if ($pageTitle !== '') {
2616
            $this->indexedDocTitle = $pageTitle;
2617
        }
2618
2619
        $titleTagContent = $this->printTitle(
2620
            $pageTitle,
2621
            (bool)($this->config['config']['noPageTitle'] ?? false),
2622
            (bool)($this->config['config']['pageTitleFirst'] ?? false),
2623
            $pageTitleSeparator
2624
        );
2625
        $this->config['config']['pageTitle'] = $titleTagContent;
2626
        // stdWrap around the title tag
2627
        $titleTagContent = $this->cObj->stdWrapValue('pageTitle', $this->config['config']);
2628
2629
        // config.noPageTitle = 2 - means do not render the page title
2630
        if (isset($this->config['config']['noPageTitle']) && (int)$this->config['config']['noPageTitle'] === 2) {
2631
            $titleTagContent = '';
2632
        }
2633
        if ($titleTagContent !== '') {
2634
            $this->pageRenderer->setTitle($titleTagContent);
2635
        }
2636
        return (string)$titleTagContent;
2637
    }
2638
2639
    /**
2640
     * Compiles the content for the page <title> tag.
2641
     *
2642
     * @param string $pageTitle The input title string, typically the "title" field of a page's record.
2643
     * @param bool $noTitle If set, then only the site title is outputted
2644
     * @param bool $showTitleFirst If set, then website title and $title is swapped
2645
     * @param string $pageTitleSeparator an alternative to the ": " as the separator between site title and page title
2646
     * @return string The page title on the form "[website title]: [input-title]". Not htmlspecialchar()'ed.
2647
     * @see generatePageTitle()
2648
     */
2649
    protected function printTitle(string $pageTitle, bool $noTitle = false, bool $showTitleFirst = false, string $pageTitleSeparator = ''): string
2650
    {
2651
        $websiteTitle = $this->getWebsiteTitle();
2652
        $pageTitle = $noTitle ? '' : $pageTitle;
2653
        if ($showTitleFirst) {
2654
            $temp = $websiteTitle;
2655
            $websiteTitle = $pageTitle;
2656
            $pageTitle = $temp;
2657
        }
2658
        // only show a separator if there are both site title and page title
2659
        if ($pageTitle === '' || $websiteTitle === '') {
2660
            $pageTitleSeparator = '';
2661
        } elseif (empty($pageTitleSeparator)) {
2662
            // use the default separator if non given
2663
            $pageTitleSeparator = ': ';
2664
        }
2665
        return $websiteTitle . $pageTitleSeparator . $pageTitle;
2666
    }
2667
2668
    /**
2669
     * @return string
2670
     */
2671
    protected function getWebsiteTitle(): string
2672
    {
2673
        if ($this->language instanceof SiteLanguage
2674
            && trim($this->language->getWebsiteTitle()) !== ''
2675
        ) {
2676
            return trim($this->language->getWebsiteTitle());
2677
        }
2678
        if ($this->site instanceof SiteInterface
2679
            && trim($this->site->getConfiguration()['websiteTitle']) !== ''
2680
        ) {
2681
            return trim($this->site->getConfiguration()['websiteTitle']);
2682
        }
2683
2684
        return '';
2685
    }
2686
2687
    /**
2688
     * Processes the INTinclude-scripts
2689
     */
2690
    public function INTincScript()
2691
    {
2692
        $this->additionalHeaderData = $this->config['INTincScript_ext']['additionalHeaderData'] ?? [];
2693
        $this->additionalFooterData = $this->config['INTincScript_ext']['additionalFooterData'] ?? [];
2694
        if (empty($this->config['INTincScript_ext']['pageRenderer'])) {
2695
            $this->initPageRenderer();
2696
        } else {
2697
            /** @var PageRenderer $pageRenderer */
2698
            $pageRenderer = unserialize($this->config['INTincScript_ext']['pageRenderer']);
2699
            $this->pageRenderer->updateState($pageRenderer->getState());
2700
        }
2701
        if (!empty($this->config['INTincScript_ext']['assetCollector'])) {
2702
            /** @var AssetCollector $assetCollector */
2703
            $assetCollector = unserialize($this->config['INTincScript_ext']['assetCollector'], ['allowed_classes' => [AssetCollector::class]]);
2704
            GeneralUtility::makeInstance(AssetCollector::class)->updateState($assetCollector->getState());
2705
        }
2706
2707
        $this->recursivelyReplaceIntPlaceholdersInContent();
2708
        $this->getTimeTracker()->push('Substitute header section');
2709
        $this->INTincScript_loadJSCode();
2710
        $this->generatePageTitle();
2711
2712
        $this->content = str_replace(
2713
            [
2714
                '<!--HD_' . $this->config['INTincScript_ext']['divKey'] . '-->',
2715
                '<!--FD_' . $this->config['INTincScript_ext']['divKey'] . '-->',
2716
            ],
2717
            [
2718
                $this->convOutputCharset(implode(LF, $this->additionalHeaderData)),
2719
                $this->convOutputCharset(implode(LF, $this->additionalFooterData)),
2720
            ],
2721
            $this->pageRenderer->renderJavaScriptAndCssForProcessingOfUncachedContentObjects($this->content, $this->config['INTincScript_ext']['divKey'])
2722
        );
2723
        // Replace again, because header and footer data and page renderer replacements may introduce additional placeholders (see #44825)
2724
        $this->recursivelyReplaceIntPlaceholdersInContent();
2725
        $this->setAbsRefPrefix();
2726
        $this->getTimeTracker()->pull();
2727
    }
2728
2729
    /**
2730
     * Replaces INT placeholders (COA_INT and USER_INT) in $this->content
2731
     * In case the replacement adds additional placeholders, it loops
2732
     * until no new placeholders are found any more.
2733
     */
2734
    protected function recursivelyReplaceIntPlaceholdersInContent()
2735
    {
2736
        do {
2737
            $nonCacheableData = $this->config['INTincScript'];
2738
            $this->processNonCacheableContentPartsAndSubstituteContentMarkers($nonCacheableData);
2739
            // Check if there were new items added to INTincScript during the previous execution:
2740
            // array_diff_assoc throws notices if values are arrays but not strings. We suppress this here.
2741
            $nonCacheableData = @array_diff_assoc($this->config['INTincScript'], $nonCacheableData);
2742
            $reprocess = count($nonCacheableData) > 0;
2743
        } while ($reprocess);
2744
    }
2745
2746
    /**
2747
     * Processes the INTinclude-scripts and substitute in content.
2748
     *
2749
     * Takes $this->content, and splits the content by <!--INT_SCRIPT.12345 --> and then puts the content
2750
     * back together.
2751
     *
2752
     * @param array $nonCacheableData $GLOBALS['TSFE']->config['INTincScript'] or part of it
2753
     * @see INTincScript()
2754
     */
2755
    protected function processNonCacheableContentPartsAndSubstituteContentMarkers(array $nonCacheableData)
2756
    {
2757
        $timeTracker = $this->getTimeTracker();
2758
        $timeTracker->push('Split content');
2759
        // Splits content with the key.
2760
        $contentSplitByUncacheableMarkers = explode('<!--INT_SCRIPT.', $this->content);
2761
        $this->content = '';
2762
        $timeTracker->setTSlogMessage('Parts: ' . count($contentSplitByUncacheableMarkers));
2763
        $timeTracker->pull();
2764
        foreach ($contentSplitByUncacheableMarkers as $counter => $contentPart) {
2765
            // If the split had a comment-end after 32 characters it's probably a split-string
2766
            if (substr($contentPart, 32, 3) === '-->') {
2767
                $nonCacheableKey = 'INT_SCRIPT.' . substr($contentPart, 0, 32);
2768
                if (is_array($nonCacheableData[$nonCacheableKey])) {
2769
                    $label = 'Include ' . $nonCacheableData[$nonCacheableKey]['type'];
2770
                    $timeTracker->push($label);
2771
                    $nonCacheableContent = '';
2772
                    $contentObjectRendererForNonCacheable = unserialize($nonCacheableData[$nonCacheableKey]['cObj']);
2773
                    /* @var ContentObjectRenderer $contentObjectRendererForNonCacheable */
2774
                    switch ($nonCacheableData[$nonCacheableKey]['type']) {
2775
                        case 'COA':
2776
                            $nonCacheableContent = $contentObjectRendererForNonCacheable->cObjGetSingle('COA', $nonCacheableData[$nonCacheableKey]['conf']);
2777
                            break;
2778
                        case 'FUNC':
2779
                            $nonCacheableContent = $contentObjectRendererForNonCacheable->cObjGetSingle('USER', $nonCacheableData[$nonCacheableKey]['conf']);
2780
                            break;
2781
                        case 'POSTUSERFUNC':
2782
                            $nonCacheableContent = $contentObjectRendererForNonCacheable->callUserFunction($nonCacheableData[$nonCacheableKey]['postUserFunc'], $nonCacheableData[$nonCacheableKey]['conf'], $nonCacheableData[$nonCacheableKey]['content']);
2783
                            break;
2784
                    }
2785
                    $this->content .= $this->convOutputCharset($nonCacheableContent);
2786
                    $this->content .= substr($contentPart, 35);
2787
                    $timeTracker->pull($nonCacheableContent);
2788
                } else {
2789
                    $this->content .= substr($contentPart, 35);
2790
                }
2791
            } elseif ($counter) {
2792
                // If it's not the first entry (which would be "0" of the array keys), then re-add the INT_SCRIPT part
2793
                $this->content .= '<!--INT_SCRIPT.' . $contentPart;
2794
            } else {
2795
                $this->content .= $contentPart;
2796
            }
2797
        }
2798
    }
2799
2800
    /**
2801
     * Loads the JavaScript/CSS code for INTincScript, if there are non-cacheable content objects
2802
     * it prepares the placeholders, otherwise populates options directly.
2803
     *
2804
     * @internal this method should be renamed as it does not only handle JS, but all additional header data
2805
     */
2806
    public function INTincScript_loadJSCode()
2807
    {
2808
        // Prepare code and placeholders for additional header and footer files (and make sure that this isn't called twice)
2809
        if ($this->isINTincScript() && !isset($this->config['INTincScript_ext'])) {
2810
            $substituteHash = $this->uniqueHash();
2811
            $this->config['INTincScript_ext']['divKey'] = $substituteHash;
2812
            // Storing the header-data array
2813
            $this->config['INTincScript_ext']['additionalHeaderData'] = $this->additionalHeaderData;
2814
            // Storing the footer-data array
2815
            $this->config['INTincScript_ext']['additionalFooterData'] = $this->additionalFooterData;
2816
            // Clearing the array
2817
            $this->additionalHeaderData = ['<!--HD_' . $substituteHash . '-->'];
2818
            // Clearing the array
2819
            $this->additionalFooterData = ['<!--FD_' . $substituteHash . '-->'];
2820
        }
2821
    }
2822
2823
    /**
2824
     * Determines if there are any INTincScripts to include = "non-cacheable" parts
2825
     *
2826
     * @return bool Returns TRUE if scripts are found
2827
     */
2828
    public function isINTincScript()
2829
    {
2830
        return !empty($this->config['INTincScript']) && is_array($this->config['INTincScript']);
2831
    }
2832
2833
    /**
2834
     * Add HTTP headers to the response object.
2835
     *
2836
     * @param ResponseInterface $response
2837
     * @return ResponseInterface
2838
     */
2839
    public function applyHttpHeadersToResponse(ResponseInterface $response): ResponseInterface
2840
    {
2841
        // Set header for charset-encoding unless disabled
2842
        if (empty($this->config['config']['disableCharsetHeader'])) {
2843
            $response = $response->withHeader('Content-Type', $this->contentType . '; charset=' . trim($this->metaCharset));
2844
        }
2845
        // Set header for content language unless disabled
2846
        $contentLanguage = $this->language->getTwoLetterIsoCode();
2847
        if (empty($this->config['config']['disableLanguageHeader']) && !empty($contentLanguage)) {
2848
            $response = $response->withHeader('Content-Language', trim($contentLanguage));
2849
        }
2850
        // Set cache related headers to client (used to enable proxy / client caching!)
2851
        if (!empty($this->config['config']['sendCacheHeaders'])) {
2852
            $headers = $this->getCacheHeaders();
2853
            foreach ($headers as $header => $value) {
2854
                $response = $response->withHeader($header, $value);
2855
            }
2856
        }
2857
        // Set additional headers if any have been configured via TypoScript
2858
        $additionalHeaders = $this->getAdditionalHeaders();
2859
        foreach ($additionalHeaders as $headerConfig) {
2860
            [$header, $value] = GeneralUtility::trimExplode(':', $headerConfig['header'], false, 2);
2861
            if ($headerConfig['statusCode']) {
2862
                $response = $response->withStatus((int)$headerConfig['statusCode']);
2863
            }
2864
            if ($headerConfig['replace']) {
2865
                $response = $response->withHeader($header, $value);
2866
            } else {
2867
                $response = $response->withAddedHeader($header, $value);
2868
            }
2869
        }
2870
        return $response;
2871
    }
2872
2873
    /**
2874
     * Get cache headers good for client/reverse proxy caching.
2875
     *
2876
     * @return array
2877
     */
2878
    protected function getCacheHeaders(): array
2879
    {
2880
        // Getting status whether we can send cache control headers for proxy caching:
2881
        $doCache = $this->isStaticCacheble();
2882
        // This variable will be TRUE unless cache headers are configured to be sent ONLY if a branch does not allow logins and logins turns out to be allowed anyway...
2883
        $loginsDeniedCfg = empty($this->config['config']['sendCacheHeaders_onlyWhenLoginDeniedInBranch']) || empty($this->loginAllowedInBranch);
2884
        // Finally, when backend users are logged in, do not send cache headers at all (Admin Panel might be displayed for instance).
2885
        $this->isClientCachable = $doCache && !$this->isBackendUserLoggedIn() && !$this->doWorkspacePreview() && $loginsDeniedCfg;
2886
        if ($this->isClientCachable) {
2887
            $headers = [
2888
                'Expires' => gmdate('D, d M Y H:i:s T', $this->cacheExpires),
2889
                'ETag' => '"' . md5($this->content) . '"',
2890
                'Cache-Control' => 'max-age=' . ($this->cacheExpires - $GLOBALS['EXEC_TIME']),
2891
                // no-cache
2892
                'Pragma' => 'public'
2893
            ];
2894
        } else {
2895
            // "no-store" is used to ensure that the client HAS to ask the server every time, and is not allowed to store anything at all
2896
            $headers = [
2897
                'Cache-Control' => 'private, no-store'
2898
            ];
2899
            // Now, if a backend user is logged in, tell him in the Admin Panel log what the caching status would have been:
2900
            if ($this->isBackendUserLoggedIn()) {
2901
                if ($doCache) {
2902
                    $this->getTimeTracker()->setTSlogMessage('Cache-headers with max-age "' . ($this->cacheExpires - $GLOBALS['EXEC_TIME']) . '" would have been sent');
2903
                } else {
2904
                    $reasonMsg = [];
2905
                    if ($this->no_cache) {
2906
                        $reasonMsg[] = 'Caching disabled (no_cache).';
2907
                    }
2908
                    if ($this->isINTincScript()) {
2909
                        $reasonMsg[] = '*_INT object(s) on page.';
2910
                    }
2911
                    if (is_array($this->fe_user->user)) {
2912
                        $reasonMsg[] = 'Frontend user logged in.';
2913
                    }
2914
                    $this->getTimeTracker()->setTSlogMessage('Cache-headers would disable proxy caching! Reason(s): "' . implode(' ', $reasonMsg) . '"', 1);
2915
                }
2916
            }
2917
        }
2918
        return $headers;
2919
    }
2920
2921
    /**
2922
     * Reporting status whether we can send cache control headers for proxy caching or publishing to static files
2923
     *
2924
     * Rules are:
2925
     * no_cache cannot be set: If it is, the page might contain dynamic content and should never be cached.
2926
     * There can be no USER_INT objects on the page ("isINTincScript()") because they implicitly indicate dynamic content
2927
     * There can be no logged in user because user sessions are based on a cookie and thereby does not offer client caching a chance to know if the user is logged in. Actually, there will be a reverse problem here; If a page will somehow change when a user is logged in he may not see it correctly if the non-login version sent a cache-header! So do NOT use cache headers in page sections where user logins change the page content. (unless using such as realurl to apply a prefix in case of login sections)
2928
     *
2929
     * @return bool
2930
     */
2931
    public function isStaticCacheble()
2932
    {
2933
        return !$this->no_cache && !$this->isINTincScript() && !$this->isUserOrGroupSet();
2934
    }
2935
2936
    /********************************************
2937
     *
2938
     * Various internal API functions
2939
     *
2940
     *******************************************/
2941
    /**
2942
     * Creates an instance of ContentObjectRenderer in $this->cObj
2943
     * This instance is used to start the rendering of the TypoScript template structure
2944
     *
2945
     * @see RequestHandler
2946
     */
2947
    public function newCObj()
2948
    {
2949
        $this->cObj = GeneralUtility::makeInstance(ContentObjectRenderer::class, $this);
2950
        $this->cObj->start($this->page, 'pages');
2951
    }
2952
2953
    /**
2954
     * Converts relative paths in the HTML source to absolute paths for fileadmin/, typo3conf/ext/ and media/ folders.
2955
     *
2956
     * @internal
2957
     * @see \TYPO3\CMS\Frontend\Http\RequestHandler
2958
     * @see INTincScript()
2959
     */
2960
    public function setAbsRefPrefix()
2961
    {
2962
        if (!$this->absRefPrefix) {
2963
            return;
2964
        }
2965
        $search = [
2966
            '"typo3temp/',
2967
            '"' . PathUtility::stripPathSitePrefix(Environment::getExtensionsPath()) . '/',
2968
            '"' . PathUtility::stripPathSitePrefix(Environment::getBackendPath()) . '/ext/',
2969
            '"' . PathUtility::stripPathSitePrefix(Environment::getFrameworkBasePath()) . '/',
2970
        ];
2971
        $replace = [
2972
            '"' . $this->absRefPrefix . 'typo3temp/',
2973
            '"' . $this->absRefPrefix . PathUtility::stripPathSitePrefix(Environment::getExtensionsPath()) . '/',
2974
            '"' . $this->absRefPrefix . PathUtility::stripPathSitePrefix(Environment::getBackendPath()) . '/ext/',
2975
            '"' . $this->absRefPrefix . PathUtility::stripPathSitePrefix(Environment::getFrameworkBasePath()) . '/',
2976
        ];
2977
        /** @var StorageRepository $storageRepository */
2978
        $storageRepository = GeneralUtility::makeInstance(StorageRepository::class);
2979
        $storages = $storageRepository->findAll();
2980
        foreach ($storages as $storage) {
2981
            if ($storage->getDriverType() === 'Local' && $storage->isPublic() && $storage->isOnline()) {
2982
                $folder = $storage->getPublicUrl($storage->getRootLevelFolder(), true);
2983
                $search[] = '"' . $folder;
2984
                $replace[] = '"' . $this->absRefPrefix . $folder;
2985
            }
2986
        }
2987
        // Process additional directories
2988
        $directories = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['additionalAbsRefPrefixDirectories'], true);
2989
        foreach ($directories as $directory) {
2990
            $search[] = '"' . $directory;
2991
            $replace[] = '"' . $this->absRefPrefix . $directory;
2992
        }
2993
        $this->content = str_replace(
2994
            $search,
2995
            $replace,
2996
            $this->content
2997
        );
2998
    }
2999
3000
    /**
3001
     * Prefixing the input URL with ->baseUrl If ->baseUrl is set and the input url is not absolute in some way.
3002
     * Designed as a wrapper functions for use with all frontend links that are processed by JavaScript (for "realurl" compatibility!). So each time a URL goes into window.open, window.location.href or otherwise, wrap it with this function!
3003
     *
3004
     * @param string $url Input URL, relative or absolute
3005
     * @return string Processed input value.
3006
     */
3007
    public function baseUrlWrap($url)
3008
    {
3009
        if ($this->baseUrl) {
3010
            $urlParts = parse_url($url);
3011
            if (empty($urlParts['scheme']) && $url[0] !== '/') {
3012
                $url = $this->baseUrl . $url;
3013
            }
3014
        }
3015
        return $url;
3016
    }
3017
3018
    /**
3019
     * Logs access to deprecated TypoScript objects and properties.
3020
     *
3021
     * Dumps message to the TypoScript message log (admin panel) and the TYPO3 deprecation log.
3022
     *
3023
     * @param string $typoScriptProperty Deprecated object or property
3024
     * @param string $explanation Message or additional information
3025
     */
3026
    public function logDeprecatedTyposcript($typoScriptProperty, $explanation = '')
3027
    {
3028
        $explanationText = $explanation !== '' ? ' - ' . $explanation : '';
3029
        $this->getTimeTracker()->setTSlogMessage($typoScriptProperty . ' is deprecated.' . $explanationText, 2);
3030
        trigger_error('TypoScript property ' . $typoScriptProperty . ' is deprecated' . $explanationText, E_USER_DEPRECATED);
3031
    }
3032
3033
    /********************************************
3034
     * PUBLIC ACCESSIBLE WORKSPACES FUNCTIONS
3035
     *******************************************/
3036
3037
    /**
3038
     * Returns TRUE if workspace preview is enabled
3039
     *
3040
     * @return bool Returns TRUE if workspace preview is enabled
3041
     */
3042
    public function doWorkspacePreview()
3043
    {
3044
        return $this->context->getPropertyFromAspect('workspace', 'isOffline', false);
3045
    }
3046
3047
    /**
3048
     * Returns the uid of the current workspace
3049
     *
3050
     * @return int returns workspace integer for which workspace is being preview. 0 if none (= live workspace).
3051
     */
3052
    public function whichWorkspace(): int
3053
    {
3054
        return $this->context->getPropertyFromAspect('workspace', 'id', 0);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->context->g...t('workspace', 'id', 0) could return the type null which is incompatible with the type-hinted return integer. Consider adding an additional type-check to rule them out.
Loading history...
3055
    }
3056
3057
    /********************************************
3058
     *
3059
     * Various external API functions - for use in plugins etc.
3060
     *
3061
     *******************************************/
3062
3063
    /**
3064
     * Returns the pages TSconfig array based on the current ->rootLine
3065
     *
3066
     * @return array
3067
     */
3068
    public function getPagesTSconfig()
3069
    {
3070
        if (!is_array($this->pagesTSconfig)) {
3071
            $contentHashCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('hash');
3072
            $loader = GeneralUtility::makeInstance(PageTsConfigLoader::class);
3073
            $tsConfigString = $loader->load(array_reverse($this->rootLine));
3074
            $parser = GeneralUtility::makeInstance(
3075
                PageTsConfigParser::class,
3076
                GeneralUtility::makeInstance(TypoScriptParser::class),
3077
                $contentHashCache
3078
            );
3079
            $this->pagesTSconfig = $parser->parse(
3080
                $tsConfigString,
3081
                GeneralUtility::makeInstance(ConditionMatcher::class, $this->context, $this->id, $this->rootLine),
3082
                $this->site
3083
            );
3084
        }
3085
        return $this->pagesTSconfig;
3086
    }
3087
3088
    /**
3089
     * Returns a unique md5 hash.
3090
     * There is no special magic in this, the only point is that you don't have to call md5(uniqid()) which is slow and by this you are sure to get a unique string each time in a little faster way.
3091
     *
3092
     * @param string $str Some string to include in what is hashed. Not significant at all.
3093
     * @return string MD5 hash of ->uniqueString, input string and uniqueCounter
3094
     */
3095
    public function uniqueHash($str = '')
3096
    {
3097
        return md5($this->uniqueString . '_' . $str . $this->uniqueCounter++);
3098
    }
3099
3100
    /**
3101
     * Sets the cache-flag to 1. Could be called from user-included php-files in order to ensure that a page is not cached.
3102
     *
3103
     * @param string $reason An optional reason to be written to the log.
3104
     * @param bool $internal Whether the call is done from core itself (should only be used by core).
3105
     */
3106
    public function set_no_cache($reason = '', $internal = false)
3107
    {
3108
        if ($reason !== '') {
3109
            $warning = '$TSFE->set_no_cache() was triggered. Reason: ' . $reason . '.';
3110
        } else {
3111
            $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
3112
            // This is a hack to work around ___FILE___ resolving symbolic links
3113
            $realWebPath = PathUtility::dirname((string)realpath(Environment::getBackendPath())) . '/';
3114
            $file = $trace[0]['file'];
3115
            if (strpos($file, $realWebPath) === 0) {
3116
                $file = str_replace($realWebPath, '', $file);
3117
            } else {
3118
                $file = str_replace(Environment::getPublicPath() . '/', '', $file);
3119
            }
3120
            $line = $trace[0]['line'];
3121
            $trigger = $file . ' on line ' . $line;
3122
            $warning = '$GLOBALS[\'TSFE\']->set_no_cache() was triggered by ' . $trigger . '.';
3123
        }
3124
        if (!$internal && $GLOBALS['TYPO3_CONF_VARS']['FE']['disableNoCacheParameter']) {
3125
            $warning .= ' However, $TYPO3_CONF_VARS[\'FE\'][\'disableNoCacheParameter\'] is set, so it will be ignored!';
3126
            $this->getTimeTracker()->setTSlogMessage($warning, 2);
3127
        } else {
3128
            $warning .= ' Caching is disabled!';
3129
            $this->disableCache();
3130
        }
3131
        if ($internal && $this->isBackendUserLoggedIn()) {
3132
            $this->logger->notice($warning);
3133
        } else {
3134
            $this->logger->warning($warning);
3135
        }
3136
    }
3137
3138
    /**
3139
     * Disables caching of the current page.
3140
     *
3141
     * @internal
3142
     */
3143
    protected function disableCache()
3144
    {
3145
        $this->no_cache = true;
3146
    }
3147
3148
    /**
3149
     * Sets the cache-timeout in seconds
3150
     *
3151
     * @param int $seconds Cache-timeout in seconds
3152
     */
3153
    public function set_cache_timeout_default($seconds)
3154
    {
3155
        $seconds = (int)$seconds;
3156
        if ($seconds > 0) {
3157
            $this->cacheTimeOutDefault = $seconds;
3158
        }
3159
    }
3160
3161
    /**
3162
     * Get the cache timeout for the current page.
3163
     *
3164
     * @return int The cache timeout for the current page.
3165
     */
3166
    public function get_cache_timeout()
3167
    {
3168
        /** @var \TYPO3\CMS\Core\Cache\Frontend\AbstractFrontend $runtimeCache */
3169
        $runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('runtime');
3170
        $cachedCacheLifetimeIdentifier = 'core-tslib_fe-get_cache_timeout';
3171
        $cachedCacheLifetime = $runtimeCache->get($cachedCacheLifetimeIdentifier);
3172
        if ($cachedCacheLifetime === false) {
3173
            if ($this->page['cache_timeout']) {
3174
                // Cache period was set for the page:
3175
                $cacheTimeout = $this->page['cache_timeout'];
3176
            } else {
3177
                // Cache period was set via TypoScript "config.cache_period",
3178
                // otherwise it's the default of 24 hours
3179
                $cacheTimeout = $this->cacheTimeOutDefault;
3180
            }
3181
            if (!empty($this->config['config']['cache_clearAtMidnight'])) {
3182
                $timeOutTime = $GLOBALS['EXEC_TIME'] + $cacheTimeout;
3183
                $midnightTime = mktime(0, 0, 0, (int)date('m', $timeOutTime), (int)date('d', $timeOutTime), (int)date('Y', $timeOutTime));
3184
                // If the midnight time of the expire-day is greater than the current time,
3185
                // we may set the timeOutTime to the new midnighttime.
3186
                if ($midnightTime > $GLOBALS['EXEC_TIME']) {
3187
                    $cacheTimeout = $midnightTime - $GLOBALS['EXEC_TIME'];
3188
                }
3189
            }
3190
3191
            // Calculate the timeout time for records on the page and adjust cache timeout if necessary
3192
            $cacheTimeout = min($this->calculatePageCacheTimeout(), $cacheTimeout);
3193
3194
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['get_cache_timeout'] ?? [] as $_funcRef) {
3195
                $params = ['cacheTimeout' => $cacheTimeout];
3196
                $cacheTimeout = GeneralUtility::callUserFunction($_funcRef, $params, $this);
3197
            }
3198
            $runtimeCache->set($cachedCacheLifetimeIdentifier, $cacheTimeout);
3199
            $cachedCacheLifetime = $cacheTimeout;
3200
        }
3201
        return $cachedCacheLifetime;
3202
    }
3203
3204
    /*********************************************
3205
     *
3206
     * Localization and character set conversion
3207
     *
3208
     *********************************************/
3209
    /**
3210
     * Split Label function for front-end applications.
3211
     *
3212
     * @param string $input Key string. Accepts the "LLL:" prefix.
3213
     * @return string Label value, if any.
3214
     */
3215
    public function sL($input)
3216
    {
3217
        return $this->languageService->sL($input);
3218
    }
3219
3220
    /**
3221
     * Sets all internal measures what language the page should be rendered.
3222
     * This is not for records, but rather the HTML / charset and the locallang labels
3223
     */
3224
    protected function setOutputLanguage()
3225
    {
3226
        $this->languageService = LanguageService::createFromSiteLanguage($this->language);
3227
        // Always disable debugging for TSFE
3228
        $this->languageService->debugKey = false;
3229
    }
3230
3231
    /**
3232
     * Converts input string from utf-8 to metaCharset IF the two charsets are different.
3233
     *
3234
     * @param string $content Content to be converted.
3235
     * @return string Converted content string.
3236
     * @throws \RuntimeException if an invalid charset was configured
3237
     */
3238
    public function convOutputCharset($content)
3239
    {
3240
        if ($this->metaCharset !== 'utf-8') {
3241
            /** @var CharsetConverter $charsetConverter */
3242
            $charsetConverter = GeneralUtility::makeInstance(CharsetConverter::class);
3243
            try {
3244
                $content = $charsetConverter->conv($content, 'utf-8', $this->metaCharset);
3245
            } catch (UnknownCharsetException $e) {
3246
                throw new \RuntimeException('Invalid config.metaCharset: ' . $e->getMessage(), 1508916185);
3247
            }
3248
        }
3249
        return $content;
3250
    }
3251
3252
    /**
3253
     * Calculates page cache timeout according to the records with starttime/endtime on the page.
3254
     *
3255
     * @return int Page cache timeout or PHP_INT_MAX if cannot be determined
3256
     */
3257
    protected function calculatePageCacheTimeout()
3258
    {
3259
        $result = PHP_INT_MAX;
3260
        // Get the configuration
3261
        $tablesToConsider = $this->getCurrentPageCacheConfiguration();
3262
        // Get the time, rounded to the minute (do not pollute MySQL cache!)
3263
        // It is ok that we do not take seconds into account here because this
3264
        // value will be subtracted later. So we never get the time "before"
3265
        // the cache change.
3266
        $now = $GLOBALS['ACCESS_TIME'];
3267
        // Find timeout by checking every table
3268
        foreach ($tablesToConsider as $tableDef) {
3269
            $result = min($result, $this->getFirstTimeValueForRecord($tableDef, $now));
3270
        }
3271
        // We return + 1 second just to ensure that cache is definitely regenerated
3272
        return $result === PHP_INT_MAX ? PHP_INT_MAX : $result - $now + 1;
3273
    }
3274
3275
    /**
3276
     * Obtains a list of table/pid pairs to consider for page caching.
3277
     *
3278
     * TS configuration looks like this:
3279
     *
3280
     * The cache lifetime of all pages takes starttime and endtime of news records of page 14 into account:
3281
     * config.cache.all = tt_news:14
3282
     *
3283
     * The cache.lifetime of the current page allows to take records (e.g. fe_users) into account:
3284
     * config.cache.all = fe_users:current
3285
     *
3286
     * The cache lifetime of page 42 takes starttime and endtime of news records of page 15 and addresses of page 16 into account:
3287
     * config.cache.42 = tt_news:15,tt_address:16
3288
     *
3289
     * @return array Array of 'tablename:pid' pairs. There is at least a current page id in the array
3290
     * @see TypoScriptFrontendController::calculatePageCacheTimeout()
3291
     */
3292
    protected function getCurrentPageCacheConfiguration()
3293
    {
3294
        $result = ['tt_content:' . $this->id];
3295
        if (isset($this->config['config']['cache.'][$this->id])) {
3296
            $result = array_merge($result, GeneralUtility::trimExplode(',', str_replace(':current', ':' . $this->id, $this->config['config']['cache.'][$this->id])));
3297
        }
3298
        if (isset($this->config['config']['cache.']['all'])) {
3299
            $result = array_merge($result, GeneralUtility::trimExplode(',', str_replace(':current', ':' . $this->id, $this->config['config']['cache.']['all'])));
3300
        }
3301
        return array_unique($result);
3302
    }
3303
3304
    /**
3305
     * Find the minimum starttime or endtime value in the table and pid that is greater than the current time.
3306
     *
3307
     * @param string $tableDef Table definition (format tablename:pid)
3308
     * @param int $now "Now" time value
3309
     * @throws \InvalidArgumentException
3310
     * @return int Value of the next start/stop time or PHP_INT_MAX if not found
3311
     * @see TypoScriptFrontendController::calculatePageCacheTimeout()
3312
     */
3313
    protected function getFirstTimeValueForRecord($tableDef, $now)
3314
    {
3315
        $now = (int)$now;
3316
        $result = PHP_INT_MAX;
3317
        [$tableName, $pid] = GeneralUtility::trimExplode(':', $tableDef);
3318
        if (empty($tableName) || empty($pid)) {
3319
            throw new \InvalidArgumentException('Unexpected value for parameter $tableDef. Expected <tablename>:<pid>, got \'' . htmlspecialchars($tableDef) . '\'.', 1307190365);
3320
        }
3321
3322
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
3323
            ->getQueryBuilderForTable($tableName);
3324
        $queryBuilder->getRestrictions()
3325
            ->removeByType(StartTimeRestriction::class)
3326
            ->removeByType(EndTimeRestriction::class);
3327
        $timeFields = [];
3328
        $timeConditions = $queryBuilder->expr()->orX();
3329
        foreach (['starttime', 'endtime'] as $field) {
3330
            if (isset($GLOBALS['TCA'][$tableName]['ctrl']['enablecolumns'][$field])) {
3331
                $timeFields[$field] = $GLOBALS['TCA'][$tableName]['ctrl']['enablecolumns'][$field];
3332
                $queryBuilder->addSelectLiteral(
3333
                    'MIN('
3334
                        . 'CASE WHEN '
3335
                        . $queryBuilder->expr()->lte(
3336
                            $timeFields[$field],
3337
                            $queryBuilder->createNamedParameter($now, \PDO::PARAM_INT)
3338
                        )
3339
                        . ' THEN NULL ELSE ' . $queryBuilder->quoteIdentifier($timeFields[$field]) . ' END'
3340
                        . ') AS ' . $queryBuilder->quoteIdentifier($timeFields[$field])
3341
                );
3342
                $timeConditions->add(
3343
                    $queryBuilder->expr()->gt(
3344
                        $timeFields[$field],
3345
                        $queryBuilder->createNamedParameter($now, \PDO::PARAM_INT)
3346
                    )
3347
                );
3348
            }
3349
        }
3350
3351
        // if starttime or endtime are defined, evaluate them
3352
        if (!empty($timeFields)) {
3353
            // find the timestamp, when the current page's content changes the next time
3354
            $row = $queryBuilder
3355
                ->from($tableName)
3356
                ->where(
3357
                    $queryBuilder->expr()->eq(
3358
                        'pid',
3359
                        $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)
3360
                    ),
3361
                    $timeConditions
3362
                )
3363
                ->execute()
3364
                ->fetch();
3365
3366
            if ($row) {
3367
                foreach ($timeFields as $timeField => $_) {
3368
                    // if a MIN value is found, take it into account for the
3369
                    // cache lifetime we have to filter out start/endtimes < $now,
3370
                    // as the SQL query also returns rows with starttime < $now
3371
                    // and endtime > $now (and using a starttime from the past
3372
                    // would be wrong)
3373
                    if ($row[$timeField] !== null && (int)$row[$timeField] > $now) {
3374
                        $result = min($result, (int)$row[$timeField]);
3375
                    }
3376
                }
3377
            }
3378
        }
3379
3380
        return $result;
3381
    }
3382
3383
    /**
3384
     * Fetches the originally requested id, falls back to $this->id
3385
     *
3386
     * @return int the originally requested page uid
3387
     * @see fetch_the_id()
3388
     */
3389
    public function getRequestedId()
3390
    {
3391
        return $this->requestedId ?: $this->id;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->requestedId ?: $this->id also could return the type string which is incompatible with the documented return type integer.
Loading history...
3392
    }
3393
3394
    /**
3395
     * Acquire a page specific lock
3396
     *
3397
     *
3398
     * The schematics here is:
3399
     * - First acquire an access lock. This is using the type of the requested lock as key.
3400
     *   Since the number of types is rather limited we can use the type as key as it will only
3401
     *   eat up a limited number of lock resources on the system (files, semaphores)
3402
     * - Second, we acquire the actual lock (named page lock). We can be sure we are the only process at this
3403
     *   very moment, hence we either get the lock for the given key or we get an error as we request a non-blocking mode.
3404
     *
3405
     * Interleaving two locks is extremely important, because the actual page lock uses a hash value as key (see callers
3406
     * of this function). If we would simply employ a normal blocking lock, we would get a potentially unlimited
3407
     * (number of pages at least) number of different locks. Depending on the available locking methods on the system
3408
     * we might run out of available resources. (e.g. maximum limit of semaphores is a system setting and applies
3409
     * to the whole system)
3410
     * We therefore must make sure that page locks are destroyed again if they are not used anymore, such that
3411
     * we never use more locking resources than parallel requests to different pages (hashes).
3412
     * In order to ensure this, we need to guarantee that no other process is waiting on a page lock when
3413
     * the process currently having the lock on the page lock is about to release the lock again.
3414
     * This can only be achieved by using a non-blocking mode, such that a process is never put into wait state
3415
     * by the kernel, but only checks the availability of the lock. The access lock is our guard to be sure
3416
     * that no two processes are at the same time releasing/destroying a page lock, whilst the other one tries to
3417
     * get a lock for this page lock.
3418
     * The only drawback of this implementation is that we basically have to poll the availability of the page lock.
3419
     *
3420
     * Note that the access lock resources are NEVER deleted/destroyed, otherwise the whole thing would be broken.
3421
     *
3422
     * @param string $type
3423
     * @param string $key
3424
     * @throws \InvalidArgumentException
3425
     * @throws \RuntimeException
3426
     * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
3427
     */
3428
    protected function acquireLock($type, $key)
3429
    {
3430
        $lockFactory = GeneralUtility::makeInstance(LockFactory::class);
3431
        $this->locks[$type]['accessLock'] = $lockFactory->createLocker($type);
3432
3433
        $this->locks[$type]['pageLock'] = $lockFactory->createLocker(
3434
            $key,
3435
            LockingStrategyInterface::LOCK_CAPABILITY_EXCLUSIVE | LockingStrategyInterface::LOCK_CAPABILITY_NOBLOCK
3436
        );
3437
3438
        do {
3439
            if (!$this->locks[$type]['accessLock']->acquire()) {
3440
                throw new \RuntimeException('Could not acquire access lock for "' . $type . '"".', 1294586098);
3441
            }
3442
3443
            try {
3444
                $locked = $this->locks[$type]['pageLock']->acquire(
3445
                    LockingStrategyInterface::LOCK_CAPABILITY_EXCLUSIVE | LockingStrategyInterface::LOCK_CAPABILITY_NOBLOCK
3446
                );
3447
            } catch (LockAcquireWouldBlockException $e) {
3448
                // somebody else has the lock, we keep waiting
3449
3450
                // first release the access lock
3451
                $this->locks[$type]['accessLock']->release();
3452
                // now lets make a short break (100ms) until we try again, since
3453
                // the page generation by the lock owner will take a while anyways
3454
                usleep(100000);
3455
                continue;
3456
            }
3457
            $this->locks[$type]['accessLock']->release();
3458
            if ($locked) {
3459
                break;
3460
            }
3461
            throw new \RuntimeException('Could not acquire page lock for ' . $key . '.', 1460975877);
3462
        } while (true);
3463
    }
3464
3465
    /**
3466
     * Release a page specific lock
3467
     *
3468
     * @param string $type
3469
     * @throws \InvalidArgumentException
3470
     * @throws \RuntimeException
3471
     * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
3472
     */
3473
    protected function releaseLock($type)
3474
    {
3475
        if ($this->locks[$type]['accessLock']) {
3476
            if (!$this->locks[$type]['accessLock']->acquire()) {
3477
                throw new \RuntimeException('Could not acquire access lock for "' . $type . '"".', 1460975902);
3478
            }
3479
3480
            $this->locks[$type]['pageLock']->release();
3481
            $this->locks[$type]['pageLock']->destroy();
3482
            $this->locks[$type]['pageLock'] = null;
3483
3484
            $this->locks[$type]['accessLock']->release();
3485
            $this->locks[$type]['accessLock'] = null;
3486
        }
3487
    }
3488
3489
    /**
3490
     * Send additional headers from config.additionalHeaders
3491
     */
3492
    protected function getAdditionalHeaders(): array
3493
    {
3494
        if (!isset($this->config['config']['additionalHeaders.'])) {
3495
            return [];
3496
        }
3497
        $additionalHeaders = [];
3498
        ksort($this->config['config']['additionalHeaders.']);
3499
        foreach ($this->config['config']['additionalHeaders.'] as $options) {
3500
            if (!is_array($options)) {
3501
                continue;
3502
            }
3503
            $header = trim($options['header'] ?? '');
3504
            if ($header === '') {
3505
                continue;
3506
            }
3507
            $additionalHeaders[] = [
3508
                'header' => $header,
3509
                // "replace existing headers" is turned on by default, unless turned off
3510
                'replace' => ($options['replace'] ?? '') !== '0',
3511
                'statusCode' => (int)($options['httpResponseCode'] ?? 0) ?: null
3512
            ];
3513
        }
3514
        return $additionalHeaders;
3515
    }
3516
3517
    /**
3518
     * Returns the current BE user.
3519
     *
3520
     * @return \TYPO3\CMS\Backend\FrontendBackendUserAuthentication
3521
     */
3522
    protected function getBackendUser()
3523
    {
3524
        return $GLOBALS['BE_USER'];
3525
    }
3526
3527
    /**
3528
     * @return TimeTracker
3529
     */
3530
    protected function getTimeTracker()
3531
    {
3532
        return GeneralUtility::makeInstance(TimeTracker::class);
3533
    }
3534
3535
    /**
3536
     * Return the global instance of this class.
3537
     *
3538
     * Intended to be used as prototype factory for this class, see Services.yaml.
3539
     * This is required as long as TypoScriptFrontendController needs request
3540
     * dependent constructor parameters. Once that has been refactored this
3541
     * factory will be removed.
3542
     *
3543
     * @return TypoScriptFrontendController
3544
     * @internal
3545
     */
3546
    public static function getGlobalInstance(): ?self
3547
    {
3548
        if (($GLOBALS['TSFE'] ?? null) instanceof self) {
3549
            return $GLOBALS['TSFE'];
3550
        }
3551
3552
        if (!(TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_FE)) {
3553
            // Return null for now (together with shared: false in Services.yaml) as TSFE might not be available in backend context
3554
            // That's not an error then
3555
            return null;
3556
        }
3557
3558
        throw new \LogicException('TypoScriptFrontendController was tried to be injected before initial creation', 1538370377);
3559
    }
3560
3561
    public function getLanguage(): SiteLanguage
3562
    {
3563
        return $this->language;
3564
    }
3565
3566
    public function getSite(): Site
3567
    {
3568
        return $this->site;
3569
    }
3570
3571
    public function getContext(): Context
3572
    {
3573
        return $this->context;
3574
    }
3575
3576
    public function getPageArguments(): PageArguments
3577
    {
3578
        return $this->pageArguments;
3579
    }
3580
}
3581