Completed
Push — master ( af32df...1507bf )
by
unknown
21:00
created

TypoScriptFrontendController::initFEuser()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 29
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 18
nc 16
nop 0
dl 0
loc 29
rs 8.439
c 0
b 0
f 0
1
<?php
2
namespace TYPO3\CMS\Frontend\Controller;
3
4
/*
5
 * This file is part of the TYPO3 CMS project.
6
 *
7
 * It is free software; you can redistribute it and/or modify it under
8
 * the terms of the GNU General Public License, either version 2
9
 * of the License, or any later version.
10
 *
11
 * For the full copyright and license information, please read the
12
 * LICENSE.txt file that was distributed with this source code.
13
 *
14
 * The TYPO3 project - inspiring people to share!
15
 */
16
17
use Doctrine\DBAL\DBALException;
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\Authentication\BackendUserAuthentication;
24
use TYPO3\CMS\Core\Cache\CacheManager;
25
use TYPO3\CMS\Core\Charset\CharsetConverter;
26
use TYPO3\CMS\Core\Charset\UnknownCharsetException;
27
use TYPO3\CMS\Core\Controller\ErrorPageController;
28
use TYPO3\CMS\Core\Database\ConnectionPool;
29
use TYPO3\CMS\Core\Database\Query\QueryHelper;
30
use TYPO3\CMS\Core\Database\Query\Restriction\DefaultRestrictionContainer;
31
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
32
use TYPO3\CMS\Core\Database\Query\Restriction\EndTimeRestriction;
33
use TYPO3\CMS\Core\Database\Query\Restriction\StartTimeRestriction;
34
use TYPO3\CMS\Core\Error\Http\PageNotFoundException;
35
use TYPO3\CMS\Core\Error\Http\ServiceUnavailableException;
36
use TYPO3\CMS\Core\Error\Http\ShortcutTargetPageNotFoundException;
37
use TYPO3\CMS\Core\Localization\LanguageService;
38
use TYPO3\CMS\Core\Locking\Exception\LockAcquireWouldBlockException;
39
use TYPO3\CMS\Core\Locking\LockFactory;
40
use TYPO3\CMS\Core\Locking\LockingStrategyInterface;
41
use TYPO3\CMS\Core\Log\LogManager;
42
use TYPO3\CMS\Core\Page\PageRenderer;
43
use TYPO3\CMS\Core\Resource\StorageRepository;
44
use TYPO3\CMS\Core\Service\DependencyOrderingService;
45
use TYPO3\CMS\Core\Site\Entity\SiteLanguage;
46
use TYPO3\CMS\Core\TimeTracker\TimeTracker;
47
use TYPO3\CMS\Core\Type\Bitmask\Permission;
48
use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
49
use TYPO3\CMS\Core\TypoScript\TemplateService;
50
use TYPO3\CMS\Core\Utility\ArrayUtility;
51
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
52
use TYPO3\CMS\Core\Utility\GeneralUtility;
53
use TYPO3\CMS\Core\Utility\HttpUtility;
54
use TYPO3\CMS\Core\Utility\MathUtility;
55
use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
56
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
57
use TYPO3\CMS\Frontend\Http\UrlHandlerInterface;
58
use TYPO3\CMS\Frontend\Page\CacheHashCalculator;
59
use TYPO3\CMS\Frontend\Page\PageRepository;
60
61
/**
62
 * Class for the built TypoScript based frontend. Instantiated in
63
 * \TYPO3\CMS\Frontend\Http\RequestHandler as the global object TSFE.
64
 *
65
 * Main frontend class, instantiated in \TYPO3\CMS\Frontend\Http\RequestHandler
66
 * as the global object TSFE.
67
 *
68
 * This class has a lot of functions and internal variable which are used from
69
 * \TYPO3\CMS\Frontend\Http\RequestHandler
70
 *
71
 * The class is instantiated as $GLOBALS['TSFE'] in \TYPO3\CMS\Frontend\Http\RequestHandler.
72
 *
73
 * The use of this class should be inspired by the order of function calls as
74
 * found in \TYPO3\CMS\Frontend\Http\RequestHandler.
75
 */
76
class TypoScriptFrontendController implements LoggerAwareInterface
77
{
78
    use LoggerAwareTrait;
79
80
    /**
81
     * The page id (int)
82
     * @var string
83
     */
84
    public $id = '';
85
86
    /**
87
     * The type (read-only)
88
     * @var int
89
     */
90
    public $type = '';
91
92
    /**
93
     * The submitted cHash
94
     * @var string
95
     */
96
    public $cHash = '';
97
98
    /**
99
     * Page will not be cached. Write only TRUE. Never clear value (some other
100
     * code might have reasons to set it TRUE).
101
     * @var bool
102
     */
103
    public $no_cache = false;
104
105
    /**
106
     * The rootLine (all the way to tree root, not only the current site!)
107
     * @var array
108
     */
109
    public $rootLine = '';
110
111
    /**
112
     * The pagerecord
113
     * @var array
114
     */
115
    public $page = '';
116
117
    /**
118
     * This will normally point to the same value as id, but can be changed to
119
     * point to another page from which content will then be displayed instead.
120
     * @var int
121
     */
122
    public $contentPid = 0;
123
124
    /**
125
     * Gets set when we are processing a page of type mounpoint with enabled overlay in getPageAndRootline()
126
     * Used later in checkPageForMountpointRedirect() to determine the final target URL where the user
127
     * should be redirected to.
128
     *
129
     * @var array|null
130
     */
131
    protected $originalMountPointPage = null;
132
133
    /**
134
     * Gets set when we are processing a page of type shortcut in the early stages
135
     * of the request when we do not know about languages yet, used later in the request
136
     * to determine the correct shortcut in case a translation changes the shortcut
137
     * target
138
     * @var array|null
139
     * @see checkTranslatedShortcut()
140
     */
141
    protected $originalShortcutPage = null;
142
143
    /**
144
     * sys_page-object, pagefunctions
145
     *
146
     * @var PageRepository
147
     */
148
    public $sys_page = '';
149
150
    /**
151
     * Contains all URL handler instances that are active for the current request.
152
     *
153
     * The methods isGeneratePage(), isOutputting() and isINTincScript() depend on this property.
154
     *
155
     * @var \TYPO3\CMS\Frontend\Http\UrlHandlerInterface[]
156
     * @see initializeRedirectUrlHandlers()
157
     */
158
    protected $activeUrlHandlers = [];
159
160
    /**
161
     * Is set to 1 if a pageNotFound handler could have been called.
162
     * @var int
163
     */
164
    public $pageNotFound = 0;
165
166
    /**
167
     * Domain start page
168
     * @var int
169
     */
170
    public $domainStartPage = 0;
171
172
    /**
173
     * Array containing a history of why a requested page was not accessible.
174
     * @var array
175
     */
176
    public $pageAccessFailureHistory = [];
177
178
    /**
179
     * @var string
180
     */
181
    public $MP = '';
182
183
    /**
184
     * This can be set from applications as a way to tag cached versions of a page
185
     * and later perform some external cache management, like clearing only a part
186
     * of the cache of a page...
187
     * @var int
188
     * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.
189
     */
190
    public $page_cache_reg1 = 0;
191
192
    /**
193
     * Contains the value of the current script path that activated the frontend.
194
     * Typically "index.php" but by rewrite rules it could be something else! Used
195
     * for Speaking Urls / Simulate Static Documents.
196
     * @var string
197
     */
198
    public $siteScript = '';
199
200
    /**
201
     * The frontend user
202
     *
203
     * @var FrontendUserAuthentication
204
     */
205
    public $fe_user = '';
206
207
    /**
208
     * Global flag indicating that a frontend user is logged in. This is set only if
209
     * a user really IS logged in. The group-list may show other groups (like added
210
     * by IP filter or so) even though there is no user.
211
     * @var bool
212
     */
213
    public $loginUser = false;
214
215
    /**
216
     * (RO=readonly) The group list, sorted numerically. Group '0,-1' is the default
217
     * group, but other groups may be added by other means than a user being logged
218
     * in though...
219
     * @var string
220
     */
221
    public $gr_list = '';
222
223
    /**
224
     * Flag that indicates if a backend user is logged in!
225
     * @var bool
226
     */
227
    public $beUserLogin = false;
228
229
    /**
230
     * Integer, that indicates which workspace is being previewed.
231
     * Not in use anymore, as this is part of the workspace preview functionality, use $TSFE->whichWorkspace() instead.
232
     * @var int
233
     */
234
    public $workspacePreview = 0;
235
236
    /**
237
     * Shows whether logins are allowed in branch
238
     * @var bool
239
     */
240
    public $loginAllowedInBranch = true;
241
242
    /**
243
     * Shows specific mode (all or groups)
244
     * @var string
245
     */
246
    public $loginAllowedInBranch_mode = '';
247
248
    /**
249
     * Set to backend user ID to initialize when keyword-based preview is used
250
     * @var int
251
     */
252
    public $ADMCMD_preview_BEUSER_uid = 0;
253
254
    /**
255
     * Flag indication that preview is active. This is based on the login of a
256
     * backend user and whether the backend user has read access to the current
257
     * page.
258
     * @var int
259
     */
260
    public $fePreview = 0;
261
262
    /**
263
     * Flag indicating that hidden pages should be shown, selected and so on. This
264
     * goes for almost all selection of pages!
265
     * @var bool
266
     */
267
    public $showHiddenPage = false;
268
269
    /**
270
     * Flag indicating that hidden records should be shown. This includes
271
     * sys_template and even fe_groups in addition to all
272
     * other regular content. So in effect, this includes everything except pages.
273
     * @var bool
274
     */
275
    public $showHiddenRecords = false;
276
277
    /**
278
     * Value that contains the simulated usergroup if any
279
     * @var int
280
     */
281
    public $simUserGroup = 0;
282
283
    /**
284
     * "CONFIG" object from TypoScript. Array generated based on the TypoScript
285
     * configuration of the current page. Saved with the cached pages.
286
     * @var array
287
     */
288
    public $config = [];
289
290
    /**
291
     * The TypoScript template object. Used to parse the TypoScript template
292
     *
293
     * @var TemplateService
294
     */
295
    public $tmpl = null;
296
297
    /**
298
     * Is set to the time-to-live time of cached pages. If FALSE, default is
299
     * 60*60*24, which is 24 hours.
300
     * @var bool|int
301
     */
302
    public $cacheTimeOutDefault = false;
303
304
    /**
305
     * Set internally if cached content is fetched from the database
306
     * @var bool
307
     * @internal
308
     */
309
    public $cacheContentFlag = false;
310
311
    /**
312
     * Set to the expire time of cached content
313
     * @var int
314
     */
315
    public $cacheExpires = 0;
316
317
    /**
318
     * Set if cache headers allowing caching are sent.
319
     * @var bool
320
     */
321
    public $isClientCachable = false;
322
323
    /**
324
     * Used by template fetching system. This array is an identification of
325
     * the template. If $this->all is empty it's because the template-data is not
326
     * cached, which it must be.
327
     * @var array
328
     */
329
    public $all = [];
330
331
    /**
332
     * Toplevel - objArrayName, eg 'page'
333
     * @var string
334
     */
335
    public $sPre = '';
336
337
    /**
338
     * TypoScript configuration of the page-object pointed to by sPre.
339
     * $this->tmpl->setup[$this->sPre.'.']
340
     * @var array
341
     */
342
    public $pSetup = '';
343
344
    /**
345
     * This hash is unique to the template, the $this->id and $this->type vars and
346
     * the gr_list (list of groups). Used to get and later store the cached data
347
     * @var string
348
     */
349
    public $newHash = '';
350
351
    /**
352
     * If config.ftu (Frontend Track User) is set in TypoScript for the current
353
     * page, the string value of this var is substituted in the rendered source-code
354
     * with the string, '&ftu=[token...]' which enables GET-method usertracking as
355
     * opposed to cookie based
356
     * @var string
357
     */
358
    public $getMethodUrlIdToken = '';
359
360
    /**
361
     * This flag is set before inclusion of pagegen.php IF no_cache is set. If this
362
     * flag is set after the inclusion of pagegen.php, no_cache is forced to be set.
363
     * This is done in order to make sure that php-code from pagegen does not falsely
364
     * clear the no_cache flag.
365
     * @var bool
366
     */
367
    public $no_cacheBeforePageGen = false;
368
369
    /**
370
     * This flag indicates if temporary content went into the cache during
371
     * page-generation.
372
     * @var mixed
373
     */
374
    public $tempContent = false;
375
376
    /**
377
     * Passed to TypoScript template class and tells it to force template rendering
378
     * @var bool
379
     */
380
    public $forceTemplateParsing = false;
381
382
    /**
383
     * The array which cHash_calc is based on, see ->makeCacheHash().
384
     * @var array
385
     */
386
    public $cHash_array = [];
387
388
    /**
389
     * May be set to the pagesTSconfig
390
     * @var array
391
     */
392
    public $pagesTSconfig = '';
393
394
    /**
395
     * Eg. insert JS-functions in this array ($additionalHeaderData) to include them
396
     * once. Use associative keys.
397
     *
398
     * Keys in use:
399
     *
400
     * used to accumulate additional HTML-code for the header-section,
401
     * <head>...</head>. Insert either associative keys (like
402
     * additionalHeaderData['myStyleSheet'], see reserved keys above) or num-keys
403
     * (like additionalHeaderData[] = '...')
404
     *
405
     * @var array
406
     */
407
    public $additionalHeaderData = [];
408
409
    /**
410
     * Used to accumulate additional HTML-code for the footer-section of the template
411
     * @var array
412
     */
413
    public $additionalFooterData = [];
414
415
    /**
416
     * Used to accumulate additional JavaScript-code. Works like
417
     * additionalHeaderData. Reserved keys at 'openPic' and 'mouseOver'
418
     *
419
     * @var array
420
     */
421
    public $additionalJavaScript = [];
422
423
    /**
424
     * Used to accumulate additional Style code. Works like additionalHeaderData.
425
     *
426
     * @var array
427
     */
428
    public $additionalCSS = [];
429
430
    /**
431
     * @var  string
432
     */
433
    public $JSCode;
434
435
    /**
436
     * @var string
437
     */
438
    public $inlineJS;
439
440
    /**
441
     * Used to accumulate DHTML-layers.
442
     * @var string
443
     */
444
    public $divSection = '';
445
446
    /**
447
     * Debug flag. If TRUE special debug-output maybe be shown (which includes html-formatting).
448
     * @var bool
449
     */
450
    public $debug = false;
451
452
    /**
453
     * Default internal target
454
     * @var string
455
     */
456
    public $intTarget = '';
457
458
    /**
459
     * Default external target
460
     * @var string
461
     */
462
    public $extTarget = '';
463
464
    /**
465
     * Default file link target
466
     * @var string
467
     */
468
    public $fileTarget = '';
469
470
    /**
471
     * Keys are page ids and values are default &MP (mount point) values to set
472
     * when using the linking features...)
473
     * @var array
474
     */
475
    public $MP_defaults = [];
476
477
    /**
478
     * If set, typolink() function encrypts email addresses. Is set in pagegen-class.
479
     * @var string|int
480
     */
481
    public $spamProtectEmailAddresses = 0;
482
483
    /**
484
     * Absolute Reference prefix
485
     * @var string
486
     */
487
    public $absRefPrefix = '';
488
489
    /**
490
     * <A>-tag parameters
491
     * @var string
492
     */
493
    public $ATagParams = '';
494
495
    /**
496
     * Search word regex, calculated if there has been search-words send. This is
497
     * used to mark up the found search words on a page when jumped to from a link
498
     * in a search-result.
499
     * @var string
500
     */
501
    public $sWordRegEx = '';
502
503
    /**
504
     * Is set to the incoming array sword_list in case of a page-view jumped to from
505
     * a search-result.
506
     * @var string
507
     */
508
    public $sWordList = '';
509
510
    /**
511
     * A string prepared for insertion in all links on the page as url-parameters.
512
     * Based on configuration in TypoScript where you defined which GET_VARS you
513
     * would like to pass on.
514
     * @var string
515
     */
516
    public $linkVars = '';
517
518
    /**
519
     * If set, edit icons are rendered aside content records. Must be set only if
520
     * the ->beUserLogin flag is set and set_no_cache() must be called as well.
521
     * @var string
522
     */
523
    public $displayEditIcons = '';
524
525
    /**
526
     * If set, edit icons are rendered aside individual fields of content. Must be
527
     * set only if the ->beUserLogin flag is set and set_no_cache() must be called as
528
     * well.
529
     * @var string
530
     */
531
    public $displayFieldEditIcons = '';
532
533
    /**
534
     * Site language, 0 (zero) is default, int+ is uid pointing to a sys_language
535
     * record. Should reflect which language menus, templates etc is displayed in
536
     * (master language) - but not necessarily the content which could be falling
537
     * back to default (see sys_language_content)
538
     * @var int
539
     */
540
    public $sys_language_uid = 0;
541
542
    /**
543
     * Site language mode for content fall back.
544
     * @var string
545
     */
546
    public $sys_language_mode = '';
547
548
    /**
549
     * Site content selection uid (can be different from sys_language_uid if content
550
     * is to be selected from a fall-back language. Depends on sys_language_mode)
551
     * @var int
552
     */
553
    public $sys_language_content = 0;
554
555
    /**
556
     * Site content overlay flag; If set - and sys_language_content is > 0 - ,
557
     * records selected will try to look for a translation pointing to their uid. (If
558
     * configured in [ctrl][languageField] / [ctrl][transOrigP...]
559
     * Possible values: [0,1,hideNonTranslated]
560
     * This flag is set based on TypoScript config.sys_language_overlay setting
561
     *
562
     * @var int|string
563
     */
564
    public $sys_language_contentOL = 0;
565
566
    /**
567
     * Is set to the iso code of the sys_language_content if that is properly defined
568
     * by the sys_language record representing the sys_language_uid.
569
     * @var string
570
     */
571
    public $sys_language_isocode = '';
572
573
    /**
574
     * 'Global' Storage for various applications. Keys should be 'tx_'.extKey for
575
     * extensions.
576
     * @var array
577
     */
578
    public $applicationData = [];
579
580
    /**
581
     * @var array
582
     */
583
    public $register = [];
584
585
    /**
586
     * Stack used for storing array and retrieving register arrays (see
587
     * LOAD_REGISTER and RESTORE_REGISTER)
588
     * @var array
589
     */
590
    public $registerStack = [];
591
592
    /**
593
     * Checking that the function is not called eternally. This is done by
594
     * interrupting at a depth of 50
595
     * @var int
596
     */
597
    public $cObjectDepthCounter = 50;
598
599
    /**
600
     * Used by RecordContentObject and ContentContentObject to ensure the a records is NOT
601
     * rendered twice through it!
602
     * @var array
603
     */
604
    public $recordRegister = [];
605
606
    /**
607
     * This is set to the [table]:[uid] of the latest record rendered. Note that
608
     * class ContentObjectRenderer has an equal value, but that is pointing to the
609
     * record delivered in the $data-array of the ContentObjectRenderer instance, if
610
     * the cObjects CONTENT or RECORD created that instance
611
     * @var string
612
     */
613
    public $currentRecord = '';
614
615
    /**
616
     * Used by class \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject
617
     * to keep track of access-keys.
618
     * @var array
619
     */
620
    public $accessKey = [];
621
622
    /**
623
     * Numerical array where image filenames are added if they are referenced in the
624
     * rendered document. This includes only TYPO3 generated/inserted images.
625
     * @var array
626
     */
627
    public $imagesOnPage = [];
628
629
    /**
630
     * Is set in ContentObjectRenderer->cImage() function to the info-array of the
631
     * most recent rendered image. The information is used in ImageTextContentObject
632
     * @var array
633
     */
634
    public $lastImageInfo = [];
635
636
    /**
637
     * Used to generate page-unique keys. Point is that uniqid() functions is very
638
     * slow, so a unikey key is made based on this, see function uniqueHash()
639
     * @var int
640
     */
641
    public $uniqueCounter = 0;
642
643
    /**
644
     * @var string
645
     */
646
    public $uniqueString = '';
647
648
    /**
649
     * This value will be used as the title for the page in the indexer (if
650
     * indexing happens)
651
     * @var string
652
     */
653
    public $indexedDocTitle = '';
654
655
    /**
656
     * Alternative page title (normally the title of the page record). Can be set
657
     * from applications you make.
658
     * @var string
659
     */
660
    public $altPageTitle = '';
661
662
    /**
663
     * The base URL set for the page header.
664
     * @var string
665
     */
666
    public $baseUrl = '';
667
668
    /**
669
     * IDs we already rendered for this page (to make sure they are unique)
670
     * @var array
671
     */
672
    private $usedUniqueIds = [];
673
674
    /**
675
     * Page content render object
676
     *
677
     * @var ContentObjectRenderer
678
     */
679
    public $cObj = '';
680
681
    /**
682
     * All page content is accumulated in this variable. See pagegen.php
683
     * @var string
684
     */
685
    public $content = '';
686
687
    /**
688
     * Output charset of the websites content. This is the charset found in the
689
     * header, meta tag etc. If different than utf-8 a conversion
690
     * happens before output to browser. Defaults to utf-8.
691
     * @var string
692
     */
693
    public $metaCharset = 'utf-8';
694
695
    /**
696
     * Set to the system language key (used on the site)
697
     * @var string
698
     */
699
    public $lang = '';
700
701
    /**
702
     * Internal calculations for labels
703
     *
704
     * @var LanguageService
705
     */
706
    protected $languageService;
707
708
    /**
709
     * @var LockingStrategyInterface[][]
710
     */
711
    protected $locks = [];
712
713
    /**
714
     * @var PageRenderer
715
     */
716
    protected $pageRenderer = null;
717
718
    /**
719
     * The page cache object, use this to save pages to the cache and to
720
     * retrieve them again
721
     *
722
     * @var \TYPO3\CMS\Core\Cache\Backend\AbstractBackend
723
     */
724
    protected $pageCache;
725
726
    /**
727
     * @var array
728
     */
729
    protected $pageCacheTags = [];
730
731
    /**
732
     * The cHash Service class used for cHash related functionality
733
     *
734
     * @var CacheHashCalculator
735
     */
736
    protected $cacheHash;
737
738
    /**
739
     * Runtime cache of domains per processed page ids.
740
     *
741
     * @var array
742
     */
743
    protected $domainDataCache = [];
744
745
    /**
746
     * Content type HTTP header being sent in the request.
747
     * @todo Ticket: #63642 Should be refactored to a request/response model later
748
     * @internal Should only be used by TYPO3 core for now
749
     *
750
     * @var string
751
     */
752
    protected $contentType = 'text/html';
753
754
    /**
755
     * Doctype to use
756
     *
757
     * @var string
758
     */
759
    public $xhtmlDoctype = '';
760
761
    /**
762
     * @var int
763
     */
764
    public $xhtmlVersion;
765
766
    /**
767
     * Originally requested id from the initial $_GET variable
768
     *
769
     * @var int
770
     */
771
    protected $requestedId;
772
773
    /**
774
     * Class constructor
775
     * Takes a number of GET/POST input variable as arguments and stores them internally.
776
     * The processing of these variables goes on later in this class.
777
     * Also sets a unique string (->uniqueString) for this script instance; A md5 hash of the microtime()
778
     *
779
     * @param array $_ unused, previously defined to set TYPO3_CONF_VARS
780
     * @param mixed $id The value of GeneralUtility::_GP('id')
781
     * @param int $type The value of GeneralUtility::_GP('type')
782
     * @param bool|string $no_cache The value of GeneralUtility::_GP('no_cache'), evaluated to 1/0
783
     * @param string $cHash The value of GeneralUtility::_GP('cHash')
784
     * @param string $_2 previously was used to define the jumpURL
785
     * @param string $MP The value of GeneralUtility::_GP('MP')
786
     * @see \TYPO3\CMS\Frontend\Http\RequestHandler
787
     */
788
    public function __construct($_ = null, $id, $type, $no_cache = '', $cHash = '', $_2 = null, $MP = '')
789
    {
790
        // Setting some variables:
791
        $this->id = $id;
792
        $this->type = $type;
793
        if ($no_cache) {
794
            if ($GLOBALS['TYPO3_CONF_VARS']['FE']['disableNoCacheParameter']) {
795
                $warning = '&no_cache=1 has been ignored because $TYPO3_CONF_VARS[\'FE\'][\'disableNoCacheParameter\'] is set!';
796
                $this->getTimeTracker()->setTSlogMessage($warning, 2);
797
            } else {
798
                $warning = '&no_cache=1 has been supplied, so caching is disabled! URL: "' . GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL') . '"';
799
                $this->disableCache();
800
            }
801
            // note: we need to instantiate the logger manually here since the injection happens after the constructor
802
            GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__)->warning($warning);
803
        }
804
        $this->cHash = $cHash;
805
        $this->MP = $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] ? (string)$MP : '';
806
        $this->uniqueString = md5(microtime());
807
        $this->initPageRenderer();
808
        // Call post processing function for constructor:
809
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-PostProc'] ?? [] as $_funcRef) {
810
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
811
        }
812
        $this->cacheHash = GeneralUtility::makeInstance(CacheHashCalculator::class);
813
        $this->initCaches();
814
    }
815
816
    /**
817
     * Initializes the page renderer object
818
     */
819
    protected function initPageRenderer()
820
    {
821
        if ($this->pageRenderer !== null) {
822
            return;
823
        }
824
        $this->pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
825
        $this->pageRenderer->setTemplateFile('EXT:frontend/Resources/Private/Templates/MainPage.html');
826
    }
827
828
    /**
829
     * @param string $contentType
830
     * @internal Should only be used by TYPO3 core for now
831
     */
832
    public function setContentType($contentType)
833
    {
834
        $this->contentType = $contentType;
835
    }
836
837
    /**
838
     * Connect to SQL database. May exit after outputting an error message
839
     * or some JavaScript redirecting to the install tool.
840
     *
841
     * @throws \RuntimeException
842
     * @throws ServiceUnavailableException
843
     */
844
    public function connectToDB()
845
    {
846
        try {
847
            $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('pages');
848
            $connection->connect();
849
        } catch (DBALException $exception) {
850
            // Cannot connect to current database
851
            $message = sprintf(
852
                'Cannot connect to the configured database. Connection failed with: "%s"',
853
                $exception->getMessage()
854
            );
855
            $this->logger->emergency($message, ['exception' => $exception]);
856
            try {
857
                $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($GLOBALS['TYPO3_REQUEST'], $message);
858
                $this->sendResponseAndExit($response);
859
            } catch (ServiceUnavailableException $e) {
860
                throw new ServiceUnavailableException($message, 1301648782);
861
            }
862
        }
863
        // Call post processing function for DB connection:
864
        $_params = ['pObj' => &$this];
865
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['connectToDB'] ?? [] as $_funcRef) {
866
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
867
        }
868
    }
869
870
    /********************************************
871
     *
872
     * Initializing, resolving page id
873
     *
874
     ********************************************/
875
    /**
876
     * Initializes the caching system.
877
     */
878
    protected function initCaches()
879
    {
880
        $this->pageCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_pages');
881
    }
882
883
    /**
884
     * Initializes the front-end login user.
885
     */
886
    public function initFEuser()
887
    {
888
        $this->fe_user = GeneralUtility::makeInstance(FrontendUserAuthentication::class);
889
        // List of pid's acceptable
890
        $pid = GeneralUtility::_GP('pid');
891
        $this->fe_user->checkPid_value = $pid ? implode(',', GeneralUtility::intExplode(',', $pid)) : 0;
892
        // Check if a session is transferred:
893
        if (GeneralUtility::_GP('FE_SESSION_KEY')) {
894
            $fe_sParts = explode('-', GeneralUtility::_GP('FE_SESSION_KEY'));
895
            // If the session key hash check is OK:
896
            if (md5($fe_sParts[0] . '/' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']) === (string)$fe_sParts[1]) {
897
                $cookieName = FrontendUserAuthentication::getCookieName();
898
                $_COOKIE[$cookieName] = $fe_sParts[0];
899
                if (isset($_SERVER['HTTP_COOKIE'])) {
900
                    // See http://forge.typo3.org/issues/27740
901
                    $_SERVER['HTTP_COOKIE'] .= ';' . $cookieName . '=' . $fe_sParts[0];
902
                }
903
                $this->fe_user->forceSetCookie = true;
904
                $this->fe_user->dontSetCookie = false;
905
                unset($cookieName);
906
            }
907
        }
908
        $this->fe_user->start();
909
        $this->fe_user->unpack_uc();
910
911
        // Call hook for possible manipulation of frontend user object
912
        $_params = ['pObj' => &$this];
913
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['initFEuser'] ?? [] as $_funcRef) {
914
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
915
        }
916
    }
917
918
    /**
919
     * Initializes the front-end user groups.
920
     * Sets ->loginUser and ->gr_list based on front-end user status.
921
     */
922
    public function initUserGroups()
923
    {
924
        // This affects the hidden-flag selecting the fe_groups for the user!
925
        $this->fe_user->showHiddenRecords = $this->showHiddenRecords;
926
        // no matter if we have an active user we try to fetch matching groups which can be set without an user (simulation for instance!)
927
        $this->fe_user->fetchGroupData();
928
        if (is_array($this->fe_user->user) && !empty($this->fe_user->groupData['uid'])) {
929
            // global flag!
930
            $this->loginUser = true;
931
            // group -2 is not an existing group, but denotes a 'default' group when a user IS logged in. This is used to let elements be shown for all logged in users!
932
            $this->gr_list = '0,-2';
933
            $gr_array = $this->fe_user->groupData['uid'];
934
        } else {
935
            $this->loginUser = false;
936
            // group -1 is not an existing group, but denotes a 'default' group when not logged in. This is used to let elements be hidden, when a user is logged in!
937
            $this->gr_list = '0,-1';
938
            if ($this->loginAllowedInBranch) {
939
                // 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.
940
                $gr_array = $this->fe_user->groupData['uid'];
941
            } else {
942
                // Set to blank since we will NOT risk any groups being set when no logins are allowed!
943
                $gr_array = [];
944
            }
945
        }
946
        // Clean up.
947
        // Make unique...
948
        $gr_array = array_unique($gr_array);
949
        // sort
950
        sort($gr_array);
951
        if (!empty($gr_array) && !$this->loginAllowedInBranch_mode) {
952
            $this->gr_list .= ',' . implode(',', $gr_array);
953
        }
954
955
        // For every 60 seconds the is_online timestamp for a logged-in user is updated
956
        if ($this->loginUser) {
957
            $this->fe_user->updateOnlineTimestamp();
958
        }
959
960
        $this->logger->debug('Valid usergroups for TSFE: ' . $this->gr_list);
961
    }
962
963
    /**
964
     * Checking if a user is logged in or a group constellation different from "0,-1"
965
     *
966
     * @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!)
967
     */
968
    public function isUserOrGroupSet()
969
    {
970
        return is_array($this->fe_user->user) || $this->gr_list !== '0,-1';
971
    }
972
973
    /**
974
     * Provides ways to bypass the '?id=[xxx]&type=[xx]' format, using either PATH_INFO or virtual HTML-documents (using Apache mod_rewrite)
975
     *
976
     * Two options:
977
     * 1) Use PATH_INFO (also Apache) to extract id and type from that var. Does not require any special modules compiled with apache. (less typical)
978
     * 2) Using hook which enables features like those provided from "realurl" extension (AKA "Speaking URLs")
979
     */
980
    public function checkAlternativeIdMethods()
981
    {
982
        $this->siteScript = GeneralUtility::getIndpEnv('TYPO3_SITE_SCRIPT');
983
        // Call post processing function for custom URL methods.
984
        $_params = ['pObj' => &$this];
985
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc'] ?? [] as $_funcRef) {
986
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
987
        }
988
    }
989
990
    /**
991
     * Clears the preview-flags, sets sim_exec_time to current time.
992
     * Hidden pages must be hidden as default, $GLOBALS['SIM_EXEC_TIME'] is set to $GLOBALS['EXEC_TIME']
993
     * in bootstrap initializeGlobalTimeVariables(). Alter it by adding or subtracting seconds.
994
     */
995
    public function clear_preview()
996
    {
997
        $this->showHiddenPage = false;
998
        $this->showHiddenRecords = false;
999
        $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
1000
        $GLOBALS['SIM_ACCESS_TIME'] = $GLOBALS['ACCESS_TIME'];
1001
        $this->fePreview = 0;
1002
    }
1003
1004
    /**
1005
     * Checks if a backend user is logged in
1006
     *
1007
     * @return bool whether a backend user is logged in
1008
     */
1009
    public function isBackendUserLoggedIn()
1010
    {
1011
        return (bool)$this->beUserLogin;
1012
    }
1013
1014
    /**
1015
     * Creates the backend user object and returns it.
1016
     *
1017
     * @return FrontendBackendUserAuthentication the backend user object
1018
     */
1019
    public function initializeBackendUser()
1020
    {
1021
        // PRE BE_USER HOOK
1022
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['preBeUser'] ?? [] as $_funcRef) {
1023
            $_params = [];
1024
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1025
        }
1026
        $backendUserObject = null;
1027
        // If the backend cookie is set,
1028
        // we proceed and check if a backend user is logged in.
1029
        if ($_COOKIE[BackendUserAuthentication::getCookieName()]) {
1030
            $GLOBALS['TYPO3_MISC']['microtime_BE_USER_start'] = microtime(true);
1031
            $this->getTimeTracker()->push('Back End user initialized', '');
1032
            $this->beUserLogin = false;
1033
            // New backend user object
1034
            $backendUserObject = GeneralUtility::makeInstance(FrontendBackendUserAuthentication::class);
1035
            $backendUserObject->start();
1036
            $backendUserObject->unpack_uc();
1037
            if (!empty($backendUserObject->user['uid'])) {
1038
                $backendUserObject->fetchGroupData();
1039
            }
1040
            // Unset the user initialization if any setting / restriction applies
1041
            if (!$backendUserObject->checkBackendAccessSettingsFromInitPhp()) {
1042
                $backendUserObject = null;
1043
            } elseif (!empty($backendUserObject->user['uid'])) {
1044
                // If the user is active now, let the controller know
1045
                $this->beUserLogin = true;
1046
            } else {
1047
                $backendUserObject = null;
1048
            }
1049
            $this->getTimeTracker()->pull();
1050
            $GLOBALS['TYPO3_MISC']['microtime_BE_USER_end'] = microtime(true);
1051
        }
1052
        // POST BE_USER HOOK
1053
        $_params = [
1054
            'BE_USER' => &$backendUserObject
1055
        ];
1056
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['postBeUser'] ?? [] as $_funcRef) {
1057
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1058
        }
1059
        return $backendUserObject;
1060
    }
1061
1062
    /**
1063
     * Determines the id and evaluates any preview settings
1064
     * Basically this function is about determining whether a backend user is logged in,
1065
     * if he has read access to the page and if he's previewing the page.
1066
     * That all determines which id to show and how to initialize the id.
1067
     */
1068
    public function determineId()
1069
    {
1070
        // Call pre processing function for id determination
1071
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PreProcessing'] ?? [] as $functionReference) {
1072
            $parameters = ['parentObject' => $this];
1073
            GeneralUtility::callUserFunction($functionReference, $parameters, $this);
1074
        }
1075
        // If there is a Backend login we are going to check for any preview settings
1076
        $originalFrontendUserGroups = $this->applyPreviewSettings($this->getBackendUser());
1077
        // If the front-end is showing a preview, caching MUST be disabled.
1078
        if ($this->fePreview) {
1079
            $this->disableCache();
1080
        }
1081
        // Now, get the id, validate access etc:
1082
        $this->fetch_the_id();
1083
        // Check if backend user has read access to this page. If not, recalculate the id.
1084
        if ($this->beUserLogin && $this->fePreview && !$this->getBackendUser()->doesUserHaveAccess($this->page, Permission::PAGE_SHOW)) {
1085
            // Resetting
1086
            $this->clear_preview();
1087
            $this->fe_user->user[$this->fe_user->usergroup_column] = $originalFrontendUserGroups;
1088
            // Fetching the id again, now with the preview settings reset.
1089
            $this->fetch_the_id();
1090
        }
1091
        // Checks if user logins are blocked for a certain branch and if so, will unset user login and re-fetch ID.
1092
        $this->loginAllowedInBranch = $this->checkIfLoginAllowedInBranch();
1093
        // Logins are not allowed:
1094
        if (!$this->loginAllowedInBranch) {
1095
            // Only if there is a login will we run this...
1096
            if ($this->isUserOrGroupSet()) {
1097
                if ($this->loginAllowedInBranch_mode === 'all') {
1098
                    // Clear out user and group:
1099
                    $this->fe_user->hideActiveLogin();
1100
                    $this->gr_list = '0,-1';
1101
                } else {
1102
                    $this->gr_list = '0,-2';
1103
                }
1104
                // Fetching the id again, now with the preview settings reset.
1105
                $this->fetch_the_id();
1106
            }
1107
        }
1108
        // Final cleaning.
1109
        // Make sure it's an integer
1110
        $this->id = ($this->contentPid = (int)$this->id);
1111
        // Make sure it's an integer
1112
        $this->type = (int)$this->type;
1113
        // Call post processing function for id determination:
1114
        $_params = ['pObj' => &$this];
1115
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'] ?? [] as $_funcRef) {
1116
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1117
        }
1118
    }
1119
1120
    /**
1121
     * Evaluates admin panel or workspace settings to see if
1122
     * visibility settings like
1123
     * - $fePreview
1124
     * - $showHiddenPage
1125
     * - $showHiddenRecords
1126
     * - $simUserGroup
1127
     * should be applied to the current object.
1128
     *
1129
     * @param FrontendBackendUserAuthentication $backendUser
1130
     * @return string|null null if no changes to the current frontend usergroups have been made, otherwise the original list of frontend usergroups
1131
     * @private do not use this in your extension code.
1132
     */
1133
    protected function applyPreviewSettings($backendUser = null)
1134
    {
1135
        if (!$backendUser) {
1136
            return null;
1137
        }
1138
        $originalFrontendUser = null;
1139
        if ($this->fe_user->user) {
1140
            $originalFrontendUser = $this->fe_user->user[$this->fe_user->usergroup_column];
1141
        }
1142
1143
        // The preview flag is set if the current page turns out to be hidden
1144
        if ($this->id && $this->determineIdIsHiddenPage()) {
1145
            $this->fePreview = 1;
1146
            $this->showHiddenPage = true;
1147
        }
1148
        // The preview flag will be set if an offline workspace will be previewed
1149
        if ($this->whichWorkspace() > 0) {
1150
            $this->fePreview = 1;
1151
        }
1152
        return $this->simUserGroup ? $originalFrontendUser : null;
1153
    }
1154
1155
    /**
1156
     * Checks if the page is hidden in the active workspace.
1157
     * If it is hidden, preview flags will be set.
1158
     *
1159
     * @return bool
1160
     */
1161
    protected function determineIdIsHiddenPage()
1162
    {
1163
        $field = MathUtility::canBeInterpretedAsInteger($this->id) ? 'uid' : 'alias';
1164
1165
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1166
            ->getQueryBuilderForTable('pages');
1167
        $queryBuilder
1168
            ->getRestrictions()
1169
            ->removeAll()
1170
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1171
1172
        $page = $queryBuilder
1173
            ->select('uid', 'hidden', 'starttime', 'endtime')
1174
            ->from('pages')
1175
            ->where(
1176
                $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($this->id)),
1177
                $queryBuilder->expr()->gte('pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
1178
            )
1179
            ->setMaxResults(1)
1180
            ->execute()
1181
            ->fetch();
1182
1183
        if ($this->whichWorkspace() > 0) {
1184
            // Fetch overlay of page if in workspace and check if it is hidden
1185
            $pageSelectObject = GeneralUtility::makeInstance(PageRepository::class);
1186
            $pageSelectObject->versioningPreview = true;
1187
            $pageSelectObject->init(false);
1188
            $targetPage = $pageSelectObject->getWorkspaceVersionOfRecord($this->whichWorkspace(), 'pages', $page['uid']);
1189
            $result = $targetPage === -1 || $targetPage === -2;
1190
        } else {
1191
            $result = is_array($page) && ($page['hidden'] || $page['starttime'] > $GLOBALS['SIM_EXEC_TIME'] || $page['endtime'] != 0 && $page['endtime'] <= $GLOBALS['SIM_EXEC_TIME']);
1192
        }
1193
        return $result;
1194
    }
1195
1196
    /**
1197
     * Resolves the page id and sets up several related properties.
1198
     *
1199
     * If $this->id is not set at all or is not a plain integer, the method
1200
     * does it's best to set the value to an integer. Resolving is based on
1201
     * this options:
1202
     *
1203
     * - Splitting $this->id if it contains an additional type parameter.
1204
     * - Getting the id for an alias in $this->id
1205
     * - Finding the domain record start page
1206
     * - First visible page
1207
     * - Relocating the id below the domain record if outside
1208
     *
1209
     * The following properties may be set up or updated:
1210
     *
1211
     * - id
1212
     * - requestedId
1213
     * - type
1214
     * - domainStartPage
1215
     * - sys_page
1216
     * - sys_page->where_groupAccess
1217
     * - sys_page->where_hid_del
1218
     * - loginUser
1219
     * - gr_list
1220
     * - no_cache
1221
     * - register['SYS_LASTCHANGED']
1222
     * - pageNotFound
1223
     *
1224
     * Via getPageAndRootlineWithDomain()
1225
     *
1226
     * - rootLine
1227
     * - page
1228
     * - MP
1229
     * - originalShortcutPage
1230
     * - originalMountPointPage
1231
     * - pageAccessFailureHistory['direct_access']
1232
     * - pageNotFound
1233
     *
1234
     * @todo:
1235
     *
1236
     * On the first impression the method does to much. This is increased by
1237
     * the fact, that is is called repeated times by the method determineId.
1238
     * The reasons are manifold.
1239
     *
1240
     * 1.) The first part, the creation of sys_page, the type and alias
1241
     * resolution don't need to be repeated. They could be separated to be
1242
     * called only once.
1243
     *
1244
     * 2.) The user group setup could be done once on a higher level.
1245
     *
1246
     * 3.) The workflow of the resolution could be elaborated to be less
1247
     * tangled. Maybe the check of the page id to be below the domain via the
1248
     * root line doesn't need to be done each time, but for the final result
1249
     * only.
1250
     *
1251
     * 4.) The root line does not need to be directly addressed by this class.
1252
     * A root line is always related to one page. The rootline could be handled
1253
     * indirectly by page objects. Page objects still don't exist.
1254
     *
1255
     * @throws ServiceUnavailableException
1256
     * @access private
1257
     */
1258
    public function fetch_the_id()
1259
    {
1260
        $timeTracker = $this->getTimeTracker();
1261
        $timeTracker->push('fetch_the_id initialize/', '');
1262
        // Initialize the page-select functions.
1263
        $this->sys_page = GeneralUtility::makeInstance(PageRepository::class);
1264
        $this->sys_page->versioningPreview = $this->whichWorkspace() > 0 || (bool)GeneralUtility::_GP('ADMCMD_view');
1265
        $this->sys_page->versioningWorkspaceId = $this->whichWorkspace();
1266
        $this->sys_page->init($this->showHiddenPage);
1267
        // Set the valid usergroups for FE
1268
        $this->initUserGroups();
1269
        // Sets sys_page where-clause
1270
        $this->setSysPageWhereClause();
1271
        // If $this->id is a string, it's an alias
1272
        $this->checkAndSetAlias();
1273
        // The id and type is set to the integer-value - just to be sure...
1274
        $this->id = (int)$this->id;
1275
        $this->type = (int)$this->type;
1276
        $timeTracker->pull();
1277
        // We find the first page belonging to the current domain
1278
        $timeTracker->push('fetch_the_id domain/', '');
1279
        if (!$this->id) {
1280
            if ($this->domainStartPage) {
1281
                // If the id was not previously set, set it to the id of the domain.
1282
                $this->id = $this->domainStartPage;
1283
            } else {
1284
                // Find the first 'visible' page in that domain
1285
                $theFirstPage = $this->sys_page->getFirstWebPage($this->id);
1286
                if ($theFirstPage) {
1287
                    $this->id = $theFirstPage['uid'];
1288
                } else {
1289
                    $message = 'No pages are found on the rootlevel!';
1290
                    $this->logger->alert($message);
1291
                    try {
1292
                        $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($GLOBALS['TYPO3_REQUEST'], $message);
1293
                        $this->sendResponseAndExit($response);
1294
                    } catch (ServiceUnavailableException $e) {
1295
                        throw new ServiceUnavailableException($message, 1301648975);
1296
                    }
1297
                }
1298
            }
1299
        }
1300
        $timeTracker->pull();
1301
        $timeTracker->push('fetch_the_id rootLine/', '');
1302
        // We store the originally requested id
1303
        $this->requestedId = $this->id;
1304
        try {
1305
            $this->getPageAndRootlineWithDomain($this->domainStartPage);
1306
        } catch (ShortcutTargetPageNotFoundException $e) {
1307
            $this->pageNotFound = 1;
1308
        }
1309
        $timeTracker->pull();
1310
        // @todo: in the future, the check if "pageNotFound_handling" is configured should go away, but this breaks
1311
        // Functional tests in workspaces currently
1312
        if ($this->pageNotFound && $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling']) {
1313
            $pNotFoundMsg = [
1314
                1 => 'ID was not an accessible page',
1315
                2 => 'Subsection was found and not accessible',
1316
                3 => 'ID was outside the domain',
1317
                4 => 'The requested page alias does not exist'
1318
            ];
1319
            $message = $pNotFoundMsg[$this->pageNotFound];
1320
            if ($this->pageNotFound === 1 || $this->pageNotFound === 2) {
1321
                $response = GeneralUtility::makeInstance(ErrorController::class)->accessDeniedAction($GLOBALS['TYPO3_REQUEST'], $message, $this->getPageAccessFailureReasons());
1322
            } else {
1323
                $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($GLOBALS['TYPO3_REQUEST'], $message, $this->getPageAccessFailureReasons());
1324
            }
1325
            $this->sendResponseAndExit($response);
1326
        }
1327
        // Init SYS_LASTCHANGED
1328
        $this->register['SYS_LASTCHANGED'] = (int)$this->page['tstamp'];
1329
        if ($this->register['SYS_LASTCHANGED'] < (int)$this->page['SYS_LASTCHANGED']) {
1330
            $this->register['SYS_LASTCHANGED'] = (int)$this->page['SYS_LASTCHANGED'];
1331
        }
1332
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['fetchPageId-PostProcessing'] ?? [] as $functionReference) {
1333
            $parameters = ['parentObject' => $this];
1334
            GeneralUtility::callUserFunction($functionReference, $parameters, $this);
1335
        }
1336
    }
1337
1338
    /**
1339
     * Loads the page and root line records based on $this->id
1340
     *
1341
     * A final page and the matching root line are determined and loaded by
1342
     * the algorithm defined by this method.
1343
     *
1344
     * First it loads the initial page from the page repository for $this->id.
1345
     * If that can't be loaded directly, it gets the root line for $this->id.
1346
     * It walks up the root line towards the root page until the page
1347
     * repository can deliver a page record. (The loading restrictions of
1348
     * the root line records are more liberal than that of the page record.)
1349
     *
1350
     * Now the page type is evaluated and handled if necessary. If the page is
1351
     * a short cut, it is replaced by the target page. If the page is a mount
1352
     * point in overlay mode, the page is replaced by the mounted page.
1353
     *
1354
     * After this potential replacements are done, the root line is loaded
1355
     * (again) for this page record. It walks up the root line up to
1356
     * the first viewable record.
1357
     *
1358
     * (While upon the first accessibility check of the root line it was done
1359
     * by loading page by page from the page repository, this time the method
1360
     * checkRootlineForIncludeSection() is used to find the most distant
1361
     * accessible page within the root line.)
1362
     *
1363
     * Having found the final page id, the page record and the root line are
1364
     * loaded for last time by this method.
1365
     *
1366
     * Exceptions may be thrown for DOKTYPE_SPACER and not loadable page records
1367
     * or root lines.
1368
     *
1369
     * If $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'] is set,
1370
     * instead of throwing an exception it's handled by a page unavailable
1371
     * handler.
1372
     *
1373
     * May set or update this properties:
1374
     *
1375
     * @see TypoScriptFrontendController::$id
1376
     * @see TypoScriptFrontendController::$MP
1377
     * @see TypoScriptFrontendController::$page
1378
     * @see TypoScriptFrontendController::$pageNotFound
1379
     * @see TypoScriptFrontendController::$pageAccessFailureHistory
1380
     * @see TypoScriptFrontendController::$originalMountPointPage
1381
     * @see TypoScriptFrontendController::$originalShortcutPage
1382
     *
1383
     * @throws ServiceUnavailableException
1384
     * @throws PageNotFoundException
1385
     * @access private
1386
     */
1387
    public function getPageAndRootline()
1388
    {
1389
        $this->resolveTranslatedPageId();
1390
        if (empty($this->page)) {
1391
            // If no page, we try to find the page before in the rootLine.
1392
            // Page is 'not found' in case the id itself was not an accessible page. code 1
1393
            $this->pageNotFound = 1;
1394
            $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1395
            if (!empty($this->rootLine)) {
1396
                $c = count($this->rootLine) - 1;
1397
                while ($c > 0) {
1398
                    // Add to page access failure history:
1399
                    $this->pageAccessFailureHistory['direct_access'][] = $this->rootLine[$c];
1400
                    // Decrease to next page in rootline and check the access to that, if OK, set as page record and ID value.
1401
                    $c--;
1402
                    $this->id = $this->rootLine[$c]['uid'];
1403
                    $this->page = $this->sys_page->getPage($this->id);
1404
                    if (!empty($this->page)) {
1405
                        break;
1406
                    }
1407
                }
1408
            }
1409
            // If still no page...
1410
            if (empty($this->page)) {
1411
                $message = 'The requested page does not exist!';
1412
                $this->logger->error($message);
1413
                try {
1414
                    $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($GLOBALS['TYPO3_REQUEST'], $message, $this->getPageAccessFailureReasons());
1415
                    $this->sendResponseAndExit($response);
1416
                } catch (PageNotFoundException $e) {
1417
                    throw new PageNotFoundException($message, 1301648780);
1418
                }
1419
            }
1420
        }
1421
        // Spacer is not accessible in frontend
1422
        if ($this->page['doktype'] == PageRepository::DOKTYPE_SPACER) {
1423
            $message = 'The requested page does not exist!';
1424
            $this->logger->error($message);
1425
            try {
1426
                $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($GLOBALS['TYPO3_REQUEST'], $message, $this->getPageAccessFailureReasons());
1427
                $this->sendResponseAndExit($response);
1428
            } catch (PageNotFoundException $e) {
1429
                throw new PageNotFoundException($message, 1301648781);
1430
            }
1431
        }
1432
        // Is the ID a link to another page??
1433
        if ($this->page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1434
            // 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.
1435
            $this->MP = '';
1436
            // saving the page so that we can check later - when we know
1437
            // about languages - whether we took the correct shortcut or
1438
            // whether a translation of the page overwrites the shortcut
1439
            // target and we need to follow the new target
1440
            $this->originalShortcutPage = $this->page;
1441
            $this->page = $this->getPageShortcut($this->page['shortcut'], $this->page['shortcut_mode'], $this->page['uid']);
1442
            $this->id = $this->page['uid'];
1443
        }
1444
        // If the page is a mountpoint which should be overlaid with the contents of the mounted page,
1445
        // it must never be accessible directly, but only in the mountpoint context. Therefore we change
1446
        // the current ID and the user is redirected by checkPageForMountpointRedirect().
1447
        if ($this->page['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT && $this->page['mount_pid_ol']) {
1448
            $this->originalMountPointPage = $this->page;
1449
            $this->page = $this->sys_page->getPage($this->page['mount_pid']);
1450
            if (empty($this->page)) {
1451
                $message = 'This page (ID ' . $this->originalMountPointPage['uid'] . ') is of type "Mount point" and '
1452
                    . 'mounts a page which is not accessible (ID ' . $this->originalMountPointPage['mount_pid'] . ').';
1453
                throw new PageNotFoundException($message, 1402043263);
1454
            }
1455
            $this->MP = $this->page['uid'] . '-' . $this->originalMountPointPage['uid'];
1456
            $this->id = $this->page['uid'];
1457
        }
1458
        // Gets the rootLine
1459
        $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1460
        // If not rootline we're off...
1461
        if (empty($this->rootLine)) {
1462
            $message = 'The requested page didn\'t have a proper connection to the tree-root!';
1463
            $this->logger->error($message);
1464
            try {
1465
                $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($GLOBALS['TYPO3_REQUEST'], $message, $this->getPageAccessFailureReasons());
1466
                $this->sendResponseAndExit($response);
1467
            } catch (ServiceUnavailableException $e) {
1468
                throw new ServiceUnavailableException($message, 1301648167);
1469
            }
1470
        }
1471
        // Checking for include section regarding the hidden/starttime/endtime/fe_user (that is access control of a whole subbranch!)
1472
        if ($this->checkRootlineForIncludeSection()) {
1473
            if (empty($this->rootLine)) {
1474
                $message = 'The requested page was not accessible!';
1475
                try {
1476
                    $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($GLOBALS['TYPO3_REQUEST'], $message, $this->getPageAccessFailureReasons());
1477
                    $this->sendResponseAndExit($response);
1478
                } catch (ServiceUnavailableException $e) {
1479
                    $this->logger->warning($message);
1480
                    throw new ServiceUnavailableException($message, 1301648234);
1481
                }
1482
            } else {
1483
                $el = reset($this->rootLine);
1484
                $this->id = $el['uid'];
1485
                $this->page = $this->sys_page->getPage($this->id);
1486
                $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1487
            }
1488
        }
1489
    }
1490
1491
    /**
1492
     * If $this->id contains a translated page record, this needs to be resolved to the default language
1493
     * in order for all rootline functionality and access restrictions to be in place further on.
1494
     *
1495
     * Additionally, if a translated page is found, $this->sys_language_uid/sys_language_content is set as well.
1496
     */
1497
    protected function resolveTranslatedPageId()
1498
    {
1499
        $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\Frontend\Page\PageRepository::getPage(). ( Ignorable by Annotation )

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

1499
        $this->page = $this->sys_page->getPage(/** @scrutinizer ignore-type */ $this->id);
Loading history...
1500
        // Accessed a default language page record, nothing to resolve
1501
        if (empty($this->page) || (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']] === 0) {
1502
            return;
1503
        }
1504
        $this->sys_language_uid = (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
1505
        $this->sys_language_content = $this->sys_language_uid;
1506
        $this->page = $this->sys_page->getPage($this->page[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']]);
1507
        $this->id = $this->page['uid'];
1508
        // For common best-practice reasons, this is set, however, will be optional for new routing mechanisms
1509
        $this->mergingWithGetVars(['L' => $this->sys_language_uid]);
1510
    }
1511
1512
    /**
1513
     * Get page shortcut; Finds the records pointed to by input value $SC (the shortcut value)
1514
     *
1515
     * @param int $SC The value of the "shortcut" field from the pages record
1516
     * @param int $mode The shortcut mode: 1 will select first subpage, 2 a random subpage, 3 the parent page; default is the page pointed to by $SC
1517
     * @param int $thisUid The current page UID of the page which is a shortcut
1518
     * @param int $itera Safety feature which makes sure that the function is calling itself recursively max 20 times (since this function can find shortcuts to other shortcuts to other shortcuts...)
1519
     * @param array $pageLog An array filled with previous page uids tested by the function - new page uids are evaluated against this to avoid going in circles.
1520
     * @param bool $disableGroupCheck If true, the group check is disabled when fetching the target page (needed e.g. for menu generation)
1521
     * @throws \RuntimeException
1522
     * @throws ShortcutTargetPageNotFoundException
1523
     * @return mixed Returns the page record of the page that the shortcut pointed to.
1524
     * @access private
1525
     * @see getPageAndRootline()
1526
     */
1527
    public function getPageShortcut($SC, $mode, $thisUid, $itera = 20, $pageLog = [], $disableGroupCheck = false)
1528
    {
1529
        $idArray = GeneralUtility::intExplode(',', $SC);
1530
        // Find $page record depending on shortcut mode:
1531
        switch ($mode) {
1532
            case PageRepository::SHORTCUT_MODE_FIRST_SUBPAGE:
1533
1534
            case PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE:
1535
                $pageArray = $this->sys_page->getMenu($idArray[0] ? $idArray[0] : $thisUid, '*', 'sorting', 'AND pages.doktype<199 AND pages.doktype!=' . PageRepository::DOKTYPE_BE_USER_SECTION);
1536
                $pO = 0;
1537
                if ($mode == PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE && !empty($pageArray)) {
1538
                    $randval = (int)rand(0, count($pageArray) - 1);
1539
                    $pO = $randval;
1540
                }
1541
                $c = 0;
1542
                $page = [];
1543
                foreach ($pageArray as $pV) {
1544
                    if ($c === $pO) {
1545
                        $page = $pV;
1546
                        break;
1547
                    }
1548
                    $c++;
1549
                }
1550
                if (empty($page)) {
1551
                    $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a subpage. ' . 'However, this page has no accessible subpages.';
1552
                    throw new ShortcutTargetPageNotFoundException($message, 1301648328);
1553
                }
1554
                break;
1555
            case PageRepository::SHORTCUT_MODE_PARENT_PAGE:
1556
                $parent = $this->sys_page->getPage($idArray[0] ? $idArray[0] : $thisUid, $disableGroupCheck);
1557
                $page = $this->sys_page->getPage($parent['pid'], $disableGroupCheck);
1558
                if (empty($page)) {
1559
                    $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to its parent page. ' . 'However, the parent page is not accessible.';
1560
                    throw new ShortcutTargetPageNotFoundException($message, 1301648358);
1561
                }
1562
                break;
1563
            default:
1564
                $page = $this->sys_page->getPage($idArray[0], $disableGroupCheck);
1565
                if (empty($page)) {
1566
                    $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a page, which is not accessible (ID ' . $idArray[0] . ').';
1567
                    throw new ShortcutTargetPageNotFoundException($message, 1301648404);
1568
                }
1569
        }
1570
        // Check if short cut page was a shortcut itself, if so look up recursively:
1571
        if ($page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1572
            if (!in_array($page['uid'], $pageLog) && $itera > 0) {
1573
                $pageLog[] = $page['uid'];
1574
                $page = $this->getPageShortcut($page['shortcut'], $page['shortcut_mode'], $page['uid'], $itera - 1, $pageLog, $disableGroupCheck);
1575
            } else {
1576
                $pageLog[] = $page['uid'];
1577
                $message = 'Page shortcuts were looping in uids ' . implode(',', $pageLog) . '...!';
1578
                $this->logger->error($message);
1579
                throw new \RuntimeException($message, 1294587212);
1580
            }
1581
        }
1582
        // Return resulting page:
1583
        return $page;
1584
    }
1585
1586
    /**
1587
     * Checks if visibility of the page is blocked upwards in the root line.
1588
     *
1589
     * If any page in the root line is blocking visibility, true is returend.
1590
     *
1591
     * All pages from the blocking page downwards are removed from the root
1592
     * line, so that the remaning pages can be used to relocate the page up
1593
     * to lowest visible page.
1594
     *
1595
     * The blocking feature of a page must be turned on by setting the page
1596
     * record field 'extendToSubpages' to 1.
1597
     *
1598
     * The following fields are evaluated then:
1599
     *
1600
     *      hidden, starttime, endtime, fe_group
1601
     *
1602
     * @todo Find a better name, i.e. checkVisibilityByRootLine
1603
     * @todo Invert boolean return value. Return true if visible.
1604
     *
1605
     * @return bool
1606
     * @access private
1607
     */
1608
    public function checkRootlineForIncludeSection(): bool
1609
    {
1610
        $c = count($this->rootLine);
1611
        $removeTheRestFlag = false;
1612
        for ($a = 0; $a < $c; $a++) {
1613
            if (!$this->checkPagerecordForIncludeSection($this->rootLine[$a])) {
1614
                // Add to page access failure history:
1615
                $this->pageAccessFailureHistory['sub_section'][] = $this->rootLine[$a];
1616
                $removeTheRestFlag = true;
1617
            }
1618
1619
            if ($this->rootLine[$a]['doktype'] == PageRepository::DOKTYPE_BE_USER_SECTION) {
1620
                // If there is a backend user logged in, check if he has read access to the page:
1621
                if ($this->beUserLogin) {
1622
                    $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1623
                        ->getQueryBuilderForTable('pages');
1624
1625
                    $queryBuilder
1626
                        ->getRestrictions()
1627
                        ->removeAll();
1628
1629
                    $row = $queryBuilder
1630
                        ->select('uid')
1631
                        ->from('pages')
1632
                        ->where(
1633
                            $queryBuilder->expr()->eq(
1634
                                'uid',
1635
                                $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
1636
                            ),
1637
                            $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW)
1638
                        )
1639
                        ->execute()
1640
                        ->fetch();
1641
1642
                    // versionOL()?
1643
                    if (!$row) {
1644
                        // 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...
1645
                        $removeTheRestFlag = true;
1646
                    }
1647
                } else {
1648
                    // Don't go here, if there is no backend user logged in.
1649
                    $removeTheRestFlag = true;
1650
                }
1651
            }
1652
            if ($removeTheRestFlag) {
1653
                // Page is 'not found' in case a subsection was found and not accessible, code 2
1654
                $this->pageNotFound = 2;
1655
                unset($this->rootLine[$a]);
1656
            }
1657
        }
1658
        return $removeTheRestFlag;
1659
    }
1660
1661
    /**
1662
     * Checks page record for enableFields
1663
     * Returns TRUE if enableFields does not disable the page record.
1664
     * Takes notice of the ->showHiddenPage flag and uses SIM_ACCESS_TIME for start/endtime evaluation
1665
     *
1666
     * @param array $row The page record to evaluate (needs fields: hidden, starttime, endtime, fe_group)
1667
     * @param bool $bypassGroupCheck Bypass group-check
1668
     * @return bool TRUE, if record is viewable.
1669
     * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList(), checkPagerecordForIncludeSection()
1670
     */
1671
    public function checkEnableFields($row, $bypassGroupCheck = false)
1672
    {
1673
        $_params = ['pObj' => $this, 'row' => &$row, 'bypassGroupCheck' => &$bypassGroupCheck];
1674
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_checkEnableFields'] ?? [] as $_funcRef) {
1675
            // Call hooks: If one returns FALSE, method execution is aborted with result "This record is not available"
1676
            $return = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1677
            if ($return === false) {
1678
                return false;
1679
            }
1680
        }
1681
        if ((!$row['hidden'] || $this->showHiddenPage) && $row['starttime'] <= $GLOBALS['SIM_ACCESS_TIME'] && ($row['endtime'] == 0 || $row['endtime'] > $GLOBALS['SIM_ACCESS_TIME']) && ($bypassGroupCheck || $this->checkPageGroupAccess($row))) {
1682
            return true;
1683
        }
1684
        return false;
1685
    }
1686
1687
    /**
1688
     * Check group access against a page record
1689
     *
1690
     * @param array $row The page record to evaluate (needs field: fe_group)
1691
     * @param mixed $groupList List of group id's (comma list or array). Default is $this->gr_list
1692
     * @return bool TRUE, if group access is granted.
1693
     * @access private
1694
     */
1695
    public function checkPageGroupAccess($row, $groupList = null)
1696
    {
1697
        if ($groupList === null) {
1698
            $groupList = $this->gr_list;
1699
        }
1700
        if (!is_array($groupList)) {
1701
            $groupList = explode(',', $groupList);
1702
        }
1703
        $pageGroupList = explode(',', $row['fe_group'] ?: 0);
1704
        return count(array_intersect($groupList, $pageGroupList)) > 0;
1705
    }
1706
1707
    /**
1708
     * Checks if the current page of the root line is visible.
1709
     *
1710
     * If the field extendToSubpages is 0, access is granted,
1711
     * else the fields hidden, starttime, endtime, fe_group are evaluated.
1712
     *
1713
     * @todo Find a better name, i.e. isVisibleRecord()
1714
     *
1715
     * @param array $row The page record
1716
     * @return bool true if visible
1717
     * @access private
1718
     * @see checkEnableFields()
1719
     * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList()
1720
     * @see checkRootlineForIncludeSection()
1721
     */
1722
    public function checkPagerecordForIncludeSection(array $row): bool
1723
    {
1724
        return !$row['extendToSubpages'] || $this->checkEnableFields($row);
1725
    }
1726
1727
    /**
1728
     * 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!)
1729
     *
1730
     * @return bool returns TRUE if logins are OK, otherwise FALSE (and then the login user must be unset!)
1731
     */
1732
    public function checkIfLoginAllowedInBranch()
1733
    {
1734
        // Initialize:
1735
        $c = count($this->rootLine);
1736
        $loginAllowed = true;
1737
        // Traverse root line from root and outwards:
1738
        for ($a = 0; $a < $c; $a++) {
1739
            // If a value is set for login state:
1740
            if ($this->rootLine[$a]['fe_login_mode'] > 0) {
1741
                // Determine state from value:
1742
                if ((int)$this->rootLine[$a]['fe_login_mode'] === 1) {
1743
                    $loginAllowed = false;
1744
                    $this->loginAllowedInBranch_mode = 'all';
1745
                } elseif ((int)$this->rootLine[$a]['fe_login_mode'] === 3) {
1746
                    $loginAllowed = false;
1747
                    $this->loginAllowedInBranch_mode = 'groups';
1748
                } else {
1749
                    $loginAllowed = true;
1750
                }
1751
            }
1752
        }
1753
        return $loginAllowed;
1754
    }
1755
1756
    /**
1757
     * 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
1758
     *
1759
     * @return array Summary of why page access was not allowed.
1760
     */
1761
    public function getPageAccessFailureReasons()
1762
    {
1763
        $output = [];
1764
        $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'] : []);
1765
        if (!empty($combinedRecords)) {
1766
            foreach ($combinedRecords as $k => $pagerec) {
1767
                // 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
1768
                // 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!
1769
                if (!$k || $pagerec['extendToSubpages']) {
1770
                    if ($pagerec['hidden']) {
1771
                        $output['hidden'][$pagerec['uid']] = true;
1772
                    }
1773
                    if ($pagerec['starttime'] > $GLOBALS['SIM_ACCESS_TIME']) {
1774
                        $output['starttime'][$pagerec['uid']] = $pagerec['starttime'];
1775
                    }
1776
                    if ($pagerec['endtime'] != 0 && $pagerec['endtime'] <= $GLOBALS['SIM_ACCESS_TIME']) {
1777
                        $output['endtime'][$pagerec['uid']] = $pagerec['endtime'];
1778
                    }
1779
                    if (!$this->checkPageGroupAccess($pagerec)) {
1780
                        $output['fe_group'][$pagerec['uid']] = $pagerec['fe_group'];
1781
                    }
1782
                }
1783
            }
1784
        }
1785
        return $output;
1786
    }
1787
1788
    /**
1789
     * Gets ->page and ->rootline information based on ->id. ->id may change during this operation.
1790
     * If not inside domain, then default to first page in domain.
1791
     *
1792
     * @param int $domainStartPage Page uid of the page where the found domain record is (pid of the domain record)
1793
     * @access private
1794
     */
1795
    public function getPageAndRootlineWithDomain($domainStartPage)
1796
    {
1797
        $this->getPageAndRootline();
1798
        // Checks if the $domain-startpage is in the rootLine. This is necessary so that references to page-id's from other domains are not possible.
1799
        if ($domainStartPage && is_array($this->rootLine)) {
1800
            $idFound = false;
1801
            foreach ($this->rootLine as $key => $val) {
1802
                if ($val['uid'] == $domainStartPage) {
1803
                    $idFound = true;
1804
                    break;
1805
                }
1806
            }
1807
            if (!$idFound) {
1808
                // Page is 'not found' in case the id was outside the domain, code 3
1809
                $this->pageNotFound = 3;
1810
                $this->id = $domainStartPage;
1811
                // re-get the page and rootline if the id was not found.
1812
                $this->getPageAndRootline();
1813
            }
1814
        }
1815
    }
1816
1817
    /**
1818
     * Sets sys_page where-clause
1819
     *
1820
     * @access private
1821
     */
1822
    public function setSysPageWhereClause()
1823
    {
1824
        $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1825
            ->getConnectionForTable('pages')
1826
            ->getExpressionBuilder();
1827
        $this->sys_page->where_hid_del = ' AND ' . (string)$expressionBuilder->andX(
1828
            QueryHelper::stripLogicalOperatorPrefix($this->sys_page->where_hid_del),
1829
            $expressionBuilder->lt('pages.doktype', 200)
1830
        );
1831
        $this->sys_page->where_groupAccess = $this->sys_page->getMultipleGroupsWhereClause('pages.fe_group', 'pages');
1832
    }
1833
1834
    /**
1835
     * Page unavailable handler for use in frontend plugins from extensions.
1836
     *
1837
     * @param string $reason Reason text
1838
     * @param string $header HTTP header to send
1839
     * @deprecated
1840
     */
1841
    public function pageUnavailableAndExit($reason = '', $header = '')
1842
    {
1843
        trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1844
        $header = $header ?: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling_statheader'];
1845
        $this->pageUnavailableHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling'], $header, $reason);
0 ignored issues
show
Deprecated Code introduced by
The function TYPO3\CMS\Frontend\Contr...ageUnavailableHandler() has been deprecated. ( Ignorable by Annotation )

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

1845
        /** @scrutinizer ignore-deprecated */ $this->pageUnavailableHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling'], $header, $reason);
Loading history...
1846
        die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1847
    }
1848
1849
    /**
1850
     * Page-not-found handler for use in frontend plugins from extensions.
1851
     *
1852
     * @param string $reason Reason text
1853
     * @param string $header HTTP header to send
1854
     * @deprecated
1855
     */
1856
    public function pageNotFoundAndExit($reason = '', $header = '')
1857
    {
1858
        trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1859
        $header = $header ?: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling_statheader'];
1860
        $this->pageNotFoundHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'], $header, $reason);
0 ignored issues
show
Deprecated Code introduced by
The function TYPO3\CMS\Frontend\Contr...::pageNotFoundHandler() has been deprecated. ( Ignorable by Annotation )

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

1860
        /** @scrutinizer ignore-deprecated */ $this->pageNotFoundHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'], $header, $reason);
Loading history...
1861
        die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1862
    }
1863
1864
    /**
1865
     * Checks whether the pageUnavailableHandler should be used. To be used, pageUnavailable_handling must be set
1866
     * and devIPMask must not match the current visitor's IP address.
1867
     *
1868
     * @return bool TRUE/FALSE whether the pageUnavailable_handler should be used.
1869
     * @deprecated
1870
     */
1871
    public function checkPageUnavailableHandler()
1872
    {
1873
        trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1874
        if (
1875
            $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling']
1876
            && !GeneralUtility::cmpIP(
1877
                GeneralUtility::getIndpEnv('REMOTE_ADDR'),
1878
                $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']
1879
            )
1880
        ) {
1881
            $checkPageUnavailableHandler = true;
1882
        } else {
1883
            $checkPageUnavailableHandler = false;
1884
        }
1885
        return $checkPageUnavailableHandler;
1886
    }
1887
1888
    /**
1889
     * Page unavailable handler. Acts a wrapper for the pageErrorHandler method.
1890
     *
1891
     * @param mixed $code See ['FE']['pageUnavailable_handling'] for possible values
1892
     * @param string $header If set, this is passed directly to the PHP function, header()
1893
     * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1894
     * @deprecated
1895
     */
1896
    public function pageUnavailableHandler($code, $header, $reason)
1897
    {
1898
        trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1899
        $this->pageErrorHandler($code, $header, $reason);
0 ignored issues
show
Deprecated Code introduced by
The function TYPO3\CMS\Frontend\Contr...ler::pageErrorHandler() has been deprecated. ( Ignorable by Annotation )

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

1899
        /** @scrutinizer ignore-deprecated */ $this->pageErrorHandler($code, $header, $reason);
Loading history...
1900
    }
1901
1902
    /**
1903
     * Page not found handler. Acts a wrapper for the pageErrorHandler method.
1904
     *
1905
     * @param mixed $code See docs of ['FE']['pageNotFound_handling'] for possible values
1906
     * @param string $header If set, this is passed directly to the PHP function, header()
1907
     * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1908
     * @deprecated
1909
     */
1910
    public function pageNotFoundHandler($code, $header = '', $reason = '')
1911
    {
1912
        trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1913
        $this->pageErrorHandler($code, $header, $reason);
0 ignored issues
show
Deprecated Code introduced by
The function TYPO3\CMS\Frontend\Contr...ler::pageErrorHandler() has been deprecated. ( Ignorable by Annotation )

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

1913
        /** @scrutinizer ignore-deprecated */ $this->pageErrorHandler($code, $header, $reason);
Loading history...
1914
    }
1915
1916
    /**
1917
     * Generic error page handler.
1918
     * Exits.
1919
     *
1920
     * @param mixed $code See docs of ['FE']['pageNotFound_handling'] and ['FE']['pageUnavailable_handling'] for all possible values
1921
     * @param string $header If set, this is passed directly to the PHP function, header()
1922
     * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1923
     * @throws \RuntimeException
1924
     * @deprecated
1925
     */
1926
    public function pageErrorHandler($code, $header = '', $reason = '')
1927
    {
1928
        trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1929
        // Issue header in any case:
1930
        if ($header) {
1931
            $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY);
1932
            foreach ($headerArr as $header) {
1933
                header($header);
1934
            }
1935
        }
1936
        // Create response:
1937
        // Simply boolean; Just shows TYPO3 error page with reason:
1938
        if (strtolower($code) === 'true' || (string)$code === '1' || gettype($code) === 'boolean') {
1939
            echo GeneralUtility::makeInstance(ErrorPageController::class)->errorAction(
1940
                'Page Not Found',
1941
                'The page did not exist or was inaccessible.' . ($reason ? ' Reason: ' . $reason : '')
1942
            );
1943
        } elseif (GeneralUtility::isFirstPartOfStr($code, 'USER_FUNCTION:')) {
1944
            $funcRef = trim(substr($code, 14));
1945
            $params = [
1946
                'currentUrl' => GeneralUtility::getIndpEnv('REQUEST_URI'),
1947
                'reasonText' => $reason,
1948
                'pageAccessFailureReasons' => $this->getPageAccessFailureReasons()
1949
            ];
1950
            try {
1951
                echo GeneralUtility::callUserFunction($funcRef, $params, $this);
1952
            } catch (\Exception $e) {
1953
                throw new \RuntimeException('Error: 404 page by USER_FUNCTION "' . $funcRef . '" failed.', 1509296032, $e);
1954
            }
1955
        } elseif (GeneralUtility::isFirstPartOfStr($code, 'READFILE:')) {
1956
            $readFile = GeneralUtility::getFileAbsFileName(trim(substr($code, 9)));
1957
            if (@is_file($readFile)) {
1958
                echo str_replace(
1959
                    [
1960
                        '###CURRENT_URL###',
1961
                        '###REASON###'
1962
                    ],
1963
                    [
1964
                        GeneralUtility::getIndpEnv('REQUEST_URI'),
1965
                        htmlspecialchars($reason)
1966
                    ],
1967
                    file_get_contents($readFile)
1968
                );
1969
            } else {
1970
                throw new \RuntimeException('Configuration Error: 404 page "' . $readFile . '" could not be found.', 1294587214);
1971
            }
1972
        } elseif (GeneralUtility::isFirstPartOfStr($code, 'REDIRECT:')) {
1973
            HttpUtility::redirect(substr($code, 9));
1974
        } elseif ($code !== '') {
1975
            // Check if URL is relative
1976
            $url_parts = parse_url($code);
1977
            // parse_url could return an array without the key "host", the empty check works better than strict check
1978
            if (empty($url_parts['host'])) {
1979
                $url_parts['host'] = GeneralUtility::getIndpEnv('HTTP_HOST');
1980
                if ($code[0] === '/') {
1981
                    $code = GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST') . $code;
1982
                } else {
1983
                    $code = GeneralUtility::getIndpEnv('TYPO3_REQUEST_DIR') . $code;
1984
                }
1985
                $checkBaseTag = false;
1986
            } else {
1987
                $checkBaseTag = true;
1988
            }
1989
            // Check recursion
1990
            if ($code == GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')) {
1991
                if ($reason == '') {
1992
                    $reason = 'Page cannot be found.';
1993
                }
1994
                $reason .= LF . LF . 'Additionally, ' . $code . ' was not found while trying to retrieve the error document.';
1995
                throw new \RuntimeException(nl2br(htmlspecialchars($reason)), 1294587215);
1996
            }
1997
            // Prepare headers
1998
            $headerArr = [
1999
                'User-agent: ' . GeneralUtility::getIndpEnv('HTTP_USER_AGENT'),
2000
                'Referer: ' . GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')
2001
            ];
2002
            $report = [];
2003
            $res = GeneralUtility::getUrl($code, 1, $headerArr, $report);
2004
            if ((int)$report['error'] !== 0 && (int)$report['error'] !== 200) {
2005
                throw new \RuntimeException('Failed to fetch error page "' . $code . '", reason: ' . $report['message'], 1509296606);
2006
            }
2007
            // Header and content are separated by an empty line
2008
            list($header, $content) = explode(CRLF . CRLF, $res, 2);
0 ignored issues
show
Bug introduced by
It seems like $res can also be of type false; however, parameter $string of explode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

2008
            list($header, $content) = explode(CRLF . CRLF, /** @scrutinizer ignore-type */ $res, 2);
Loading history...
2009
            $content .= CRLF;
2010
            if (false === $res) {
2011
                // Last chance -- redirect
2012
                HttpUtility::redirect($code);
2013
            } else {
2014
                // Forward these response headers to the client
2015
                $forwardHeaders = [
2016
                    'Content-Type:'
2017
                ];
2018
                $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY);
2019
                foreach ($headerArr as $header) {
2020
                    foreach ($forwardHeaders as $h) {
2021
                        if (preg_match('/^' . $h . '/', $header)) {
2022
                            header($header);
2023
                        }
2024
                    }
2025
                }
2026
                // Put <base> if necessary
2027
                if ($checkBaseTag) {
2028
                    // If content already has <base> tag, we do not need to do anything
2029
                    if (false === stristr($content, '<base ')) {
2030
                        // Generate href for base tag
2031
                        $base = $url_parts['scheme'] . '://';
2032
                        if ($url_parts['user'] != '') {
2033
                            $base .= $url_parts['user'];
2034
                            if ($url_parts['pass'] != '') {
2035
                                $base .= ':' . $url_parts['pass'];
2036
                            }
2037
                            $base .= '@';
2038
                        }
2039
                        $base .= $url_parts['host'];
2040
                        // Add path portion skipping possible file name
2041
                        $base .= preg_replace('/(.*\\/)[^\\/]*/', '${1}', $url_parts['path']);
2042
                        // Put it into content (generate also <head> if necessary)
2043
                        $replacement = LF . '<base href="' . htmlentities($base) . '" />' . LF;
2044
                        if (stristr($content, '<head>')) {
2045
                            $content = preg_replace('/(<head>)/i', '\\1' . $replacement, $content);
2046
                        } else {
2047
                            $content = preg_replace('/(<html[^>]*>)/i', '\\1<head>' . $replacement . '</head>', $content);
2048
                        }
2049
                    }
2050
                }
2051
                // Output the content
2052
                echo $content;
2053
            }
2054
        } else {
2055
            echo GeneralUtility::makeInstance(ErrorPageController::class)->errorAction(
2056
                'Page Not Found',
2057
                $reason ? 'Reason: ' . $reason : 'Page cannot be found.'
2058
            );
2059
        }
2060
        die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
2061
    }
2062
2063
    /**
2064
     * Fetches the integer page id for a page alias.
2065
     * Looks if ->id is not an integer and if so it will search for a page alias and if found the page uid of that page is stored in $this->id
2066
     *
2067
     * @access private
2068
     */
2069
    public function checkAndSetAlias()
2070
    {
2071
        if ($this->id && !MathUtility::canBeInterpretedAsInteger($this->id)) {
2072
            $aid = $this->sys_page->getPageIdFromAlias($this->id);
2073
            if ($aid) {
2074
                $this->id = $aid;
2075
            } else {
2076
                $this->pageNotFound = 4;
2077
            }
2078
        }
2079
    }
2080
2081
    /**
2082
     * Merging values into the global $_GET
2083
     *
2084
     * @param array $GET_VARS Array of key/value pairs that will be merged into the current GET-vars. (Non-escaped values)
2085
     */
2086
    public function mergingWithGetVars($GET_VARS)
2087
    {
2088
        if (is_array($GET_VARS)) {
0 ignored issues
show
introduced by
The condition is_array($GET_VARS) is always true.
Loading history...
2089
            // Getting $_GET var, unescaped.
2090
            $realGet = GeneralUtility::_GET();
2091
            if (!is_array($realGet)) {
2092
                $realGet = [];
2093
            }
2094
            // Merge new values on top:
2095
            ArrayUtility::mergeRecursiveWithOverrule($realGet, $GET_VARS);
2096
            // Write values back to $_GET:
2097
            GeneralUtility::_GETset($realGet);
2098
            // Setting these specifically (like in the init-function):
2099
            if (isset($GET_VARS['type'])) {
2100
                $this->type = (int)$GET_VARS['type'];
2101
            }
2102
            if (isset($GET_VARS['cHash'])) {
2103
                $this->cHash = $GET_VARS['cHash'];
2104
            }
2105
            if (isset($GET_VARS['MP'])) {
2106
                $this->MP = $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] ? $GET_VARS['MP'] : '';
2107
            }
2108
            if (isset($GET_VARS['no_cache']) && $GET_VARS['no_cache']) {
2109
                $this->set_no_cache('no_cache is requested via GET parameter');
2110
            }
2111
        }
2112
    }
2113
2114
    /********************************************
2115
     *
2116
     * Template and caching related functions.
2117
     *
2118
     *******************************************/
2119
    /**
2120
     * Calculates a hash string based on additional parameters in the url.
2121
     *
2122
     * Calculated hash is stored in $this->cHash_array.
2123
     * This is used to cache pages with more parameters than just id and type.
2124
     *
2125
     * @see reqCHash()
2126
     */
2127
    public function makeCacheHash()
2128
    {
2129
        // No need to test anything if caching was already disabled.
2130
        if ($this->no_cache && !$GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2131
            return;
2132
        }
2133
        $GET = GeneralUtility::_GET();
2134
        if ($this->cHash && is_array($GET)) {
2135
            // Make sure we use the page uid and not the page alias
2136
            $GET['id'] = $this->id;
2137
            $this->cHash_array = $this->cacheHash->getRelevantParameters(GeneralUtility::implodeArrayForUrl('', $GET));
2138
            $cHash_calc = $this->cacheHash->calculateCacheHash($this->cHash_array);
2139
            if (!hash_equals($cHash_calc, $this->cHash)) {
2140
                if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2141
                    $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($GLOBALS['TYPO3_REQUEST'], 'Request parameters could not be validated (&cHash comparison failed)');
2142
                    $this->sendResponseAndExit($response);
2143
                } else {
2144
                    $this->disableCache();
2145
                    $this->getTimeTracker()->setTSlogMessage('The incoming cHash "' . $this->cHash . '" and calculated cHash "' . $cHash_calc . '" did not match, so caching was disabled. The fieldlist used was "' . implode(',', array_keys($this->cHash_array)) . '"', 2);
2146
                }
2147
            }
2148
        } elseif (is_array($GET)) {
2149
            // No cHash is set, check if that is correct
2150
            if ($this->cacheHash->doParametersRequireCacheHash(GeneralUtility::implodeArrayForUrl('', $GET))) {
2151
                $this->reqCHash();
2152
            }
2153
        }
2154
    }
2155
2156
    /**
2157
     * Will disable caching if the cHash value was not set.
2158
     * This function should be called to check the _existence_ of "&cHash" whenever a plugin generating cacheable output is using extra GET variables. If there _is_ a cHash value the validation of it automatically takes place in makeCacheHash() (see above)
2159
     *
2160
     * @see makeCacheHash(), \TYPO3\CMS\Frontend\Plugin\AbstractPlugin::pi_cHashCheck()
2161
     */
2162
    public function reqCHash()
2163
    {
2164
        if (!$this->cHash) {
2165
            if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2166
                if ($this->tempContent) {
2167
                    $this->clearPageCacheContent();
2168
                }
2169
                $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($GLOBALS['TYPO3_REQUEST'], 'Request parameters could not be validated (&cHash empty)');
2170
                $this->sendResponseAndExit($response);
2171
            } else {
2172
                $this->disableCache();
2173
                $this->getTimeTracker()->setTSlogMessage('TSFE->reqCHash(): No &cHash parameter was sent for GET vars though required so caching is disabled', 2);
2174
            }
2175
        }
2176
    }
2177
2178
    /**
2179
     * Initialize the TypoScript template parser
2180
     */
2181
    public function initTemplate()
2182
    {
2183
        $this->tmpl = GeneralUtility::makeInstance(TemplateService::class);
2184
        $this->tmpl->setVerbose((bool)$this->beUserLogin);
2185
        $this->tmpl->init();
2186
        $this->tmpl->tt_track = (bool)$this->beUserLogin;
2187
    }
2188
2189
    /**
2190
     * See if page is in cache and get it if so
2191
     * Stores the page content in $this->content if something is found.
2192
     *
2193
     * @throws \InvalidArgumentException
2194
     * @throws \RuntimeException
2195
     */
2196
    public function getFromCache()
2197
    {
2198
        // clearing the content-variable, which will hold the pagecontent
2199
        $this->content = '';
2200
        // Unsetting the lowlevel config
2201
        $this->config = [];
2202
        $this->cacheContentFlag = false;
2203
2204
        if ($this->no_cache) {
2205
            return;
2206
        }
2207
2208
        $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2209
        if (!is_array($pageSectionCacheContent)) {
0 ignored issues
show
introduced by
The condition is_array($pageSectionCacheContent) is always true.
Loading history...
2210
            // Nothing in the cache, we acquire an "exclusive lock" for the key now.
2211
            // We use the Registry to store this lock centrally,
2212
            // but we protect the access again with a global exclusive lock to avoid race conditions
2213
2214
            $this->acquireLock('pagesection', $this->id . '::' . $this->MP);
2215
            //
2216
            // from this point on we're the only one working on that page ($key)
2217
            //
2218
2219
            // query the cache again to see if the page data are there meanwhile
2220
            $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2221
            if (is_array($pageSectionCacheContent)) {
2222
                // we have the content, nice that some other process did the work for us already
2223
                $this->releaseLock('pagesection');
2224
            }
2225
            // We keep the lock set, because we are the ones generating the page now
2226
                // and filling the cache.
2227
                // This indicates that we have to release the lock in the Registry later in releaseLocks()
2228
        }
2229
2230
        if (is_array($pageSectionCacheContent)) {
0 ignored issues
show
introduced by
The condition is_array($pageSectionCacheContent) is always true.
Loading history...
2231
            // 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.
2232
            // If this hash is not the same in here in this section and after page-generation, then the page will not be properly cached!
2233
            // 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.
2234
            $pageSectionCacheContent = $this->tmpl->matching($pageSectionCacheContent);
2235
            ksort($pageSectionCacheContent);
2236
            $this->all = $pageSectionCacheContent;
2237
        }
2238
        unset($pageSectionCacheContent);
2239
2240
        // Look for page in cache only if a shift-reload is not sent to the server.
2241
        $lockHash = $this->getLockHash();
2242
        if (!$this->headerNoCache()) {
2243
            if ($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...
2244
                // we got page section information
2245
                $this->newHash = $this->getHash();
2246
                $this->getTimeTracker()->push('Cache Row', '');
2247
                $row = $this->getFromCache_queryRow();
2248
                if (!is_array($row)) {
0 ignored issues
show
introduced by
The condition is_array($row) is always true.
Loading history...
2249
                    // nothing in the cache, we acquire an exclusive lock now
2250
2251
                    $this->acquireLock('pages', $lockHash);
2252
                    //
2253
                    // from this point on we're the only one working on that page ($lockHash)
2254
                    //
2255
2256
                    // query the cache again to see if the data are there meanwhile
2257
                    $row = $this->getFromCache_queryRow();
2258
                    if (is_array($row)) {
2259
                        // we have the content, nice that some other process did the work for us
2260
                        $this->releaseLock('pages');
2261
                    }
2262
                    // We keep the lock set, because we are the ones generating the page now
2263
                        // and filling the cache.
2264
                        // This indicates that we have to release the lock in the Registry later in releaseLocks()
2265
                }
2266
                if (is_array($row)) {
0 ignored issues
show
introduced by
The condition is_array($row) is always true.
Loading history...
2267
                    // we have data from cache
2268
2269
                    // Call hook when a page is retrieved from cache:
2270
                    $_params = ['pObj' => &$this, 'cache_pages_row' => &$row];
2271
                    foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'] ?? [] as $_funcRef) {
2272
                        GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2273
                    }
2274
                    // Fetches the lowlevel config stored with the cached data
2275
                    $this->config = $row['cache_data'];
2276
                    // Getting the content
2277
                    $this->content = $row['content'];
2278
                    // Flag for temp content
2279
                    $this->tempContent = $row['temp_content'];
2280
                    // Setting flag, so we know, that some cached content has been loaded
2281
                    $this->cacheContentFlag = true;
2282
                    $this->cacheExpires = $row['expires'];
2283
2284
                    // Restore page title information, this is needed to generate the page title for
2285
                    // partially cached pages.
2286
                    $this->page['title'] = $row['pageTitleInfo']['title'];
2287
                    $this->altPageTitle = $row['pageTitleInfo']['altPageTitle'];
2288
                    $this->indexedDocTitle = $row['pageTitleInfo']['indexedDocTitle'];
2289
2290
                    if (isset($this->config['config']['debug'])) {
2291
                        $debugCacheTime = (bool)$this->config['config']['debug'];
2292
                    } else {
2293
                        $debugCacheTime = !empty($GLOBALS['TYPO3_CONF_VARS']['FE']['debug']);
2294
                    }
2295
                    if ($debugCacheTime) {
2296
                        $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
2297
                        $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
2298
                        $this->content .= LF . '<!-- Cached page generated ' . date($dateFormat . ' ' . $timeFormat, $row['tstamp']) . '. Expires ' . date($dateFormat . ' ' . $timeFormat, $row['expires']) . ' -->';
2299
                    }
2300
                }
2301
                $this->getTimeTracker()->pull();
2302
2303
                return;
2304
            }
2305
        }
2306
        // the user forced rebuilding the page cache or there was no pagesection information
2307
        // get a lock for the page content so other processes will not interrupt the regeneration
2308
        $this->acquireLock('pages', $lockHash);
2309
    }
2310
2311
    /**
2312
     * Returning the cached version of page with hash = newHash
2313
     *
2314
     * @return array Cached row, if any. Otherwise void.
2315
     */
2316
    public function getFromCache_queryRow()
2317
    {
2318
        $this->getTimeTracker()->push('Cache Query', '');
2319
        $row = $this->pageCache->get($this->newHash);
2320
        $this->getTimeTracker()->pull();
2321
        return $row;
2322
    }
2323
2324
    /**
2325
     * Detecting if shift-reload has been clicked
2326
     * Will not be called if re-generation of page happens by other reasons (for instance that the page is not in cache yet!)
2327
     * Also, a backend user MUST be logged in for the shift-reload to be detected due to DoS-attack-security reasons.
2328
     *
2329
     * @return bool If shift-reload in client browser has been clicked, disable getting cached page (and regenerate it).
2330
     */
2331
    public function headerNoCache()
2332
    {
2333
        $disableAcquireCacheData = false;
2334
        if ($this->beUserLogin) {
2335
            if (strtolower($_SERVER['HTTP_CACHE_CONTROL']) === 'no-cache' || strtolower($_SERVER['HTTP_PRAGMA']) === 'no-cache') {
2336
                $disableAcquireCacheData = true;
2337
            }
2338
        }
2339
        // Call hook for possible by-pass of requiring of page cache (for recaching purpose)
2340
        $_params = ['pObj' => &$this, 'disableAcquireCacheData' => &$disableAcquireCacheData];
2341
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'] ?? [] as $_funcRef) {
2342
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2343
        }
2344
        return $disableAcquireCacheData;
2345
    }
2346
2347
    /**
2348
     * Calculates the cache-hash
2349
     * This hash is unique to the template, the variables ->id, ->type, ->gr_list (list of groups), ->MP (Mount Points) and cHash array
2350
     * Used to get and later store the cached data.
2351
     *
2352
     * @return string MD5 hash of serialized hash base from createHashBase()
2353
     * @access private
2354
     * @see getFromCache(), getLockHash()
2355
     */
2356
    public function getHash()
2357
    {
2358
        return md5($this->createHashBase(false));
2359
    }
2360
2361
    /**
2362
     * Calculates the lock-hash
2363
     * This hash is unique to the above hash, except that it doesn't contain the template information in $this->all.
2364
     *
2365
     * @return string MD5 hash
2366
     * @access private
2367
     * @see getFromCache(), getHash()
2368
     */
2369
    public function getLockHash()
2370
    {
2371
        $lockHash = $this->createHashBase(true);
2372
        return md5($lockHash);
2373
    }
2374
2375
    /**
2376
     * Calculates the cache-hash (or the lock-hash)
2377
     * This hash is unique to the template,
2378
     * the variables ->id, ->type, ->gr_list (list of groups),
2379
     * ->MP (Mount Points) and cHash array
2380
     * Used to get and later store the cached data.
2381
     *
2382
     * @param bool $createLockHashBase Whether to create the lock hash, which doesn't contain the "this->all" (the template information)
2383
     * @return string the serialized hash base
2384
     */
2385
    protected function createHashBase($createLockHashBase = false)
2386
    {
2387
        // Ensure the language base is used for the hash base calculation as well, otherwise TypoScript and page-related rendering
2388
        // is not cached properly as we don't have any language-specific conditions anymore
2389
        $siteBase = $this->getCurrentSiteLanguage() ? $this->getCurrentSiteLanguage()->getBase() : '';
2390
        $hashParameters = [
2391
            'id' => (int)$this->id,
2392
            'type' => (int)$this->type,
2393
            'gr_list' => (string)$this->gr_list,
2394
            'MP' => (string)$this->MP,
2395
            'siteBase' => $siteBase,
2396
            'cHash' => $this->cHash_array,
2397
            'domainStartPage' => $this->domainStartPage
2398
        ];
2399
        // Include the template information if we shouldn't create a lock hash
2400
        if (!$createLockHashBase) {
2401
            $hashParameters['all'] = $this->all;
2402
        }
2403
        // Call hook to influence the hash calculation
2404
        $_params = [
2405
            'hashParameters' => &$hashParameters,
2406
            'createLockHashBase' => $createLockHashBase
2407
        ];
2408
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['createHashBase'] ?? [] as $_funcRef) {
2409
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2410
        }
2411
        return serialize($hashParameters);
2412
    }
2413
2414
    /**
2415
     * Checks if config-array exists already but if not, gets it
2416
     *
2417
     * @throws ServiceUnavailableException
2418
     */
2419
    public function getConfigArray()
2420
    {
2421
        // 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
2422
        if (empty($this->config) || is_array($this->config['INTincScript']) || $this->forceTemplateParsing) {
2423
            $timeTracker = $this->getTimeTracker();
2424
            $timeTracker->push('Parse template', '');
2425
            // Force parsing, if set?:
2426
            $this->tmpl->forceTemplateParsing = $this->forceTemplateParsing;
2427
            // Start parsing the TS template. Might return cached version.
2428
            $this->tmpl->start($this->rootLine);
2429
            $timeTracker->pull();
2430
            if ($this->tmpl->loaded) {
2431
                $timeTracker->push('Setting the config-array', '');
2432
                // toplevel - objArrayName
2433
                $this->sPre = $this->tmpl->setup['types.'][$this->type];
2434
                $this->pSetup = $this->tmpl->setup[$this->sPre . '.'];
2435
                if (!is_array($this->pSetup)) {
2436
                    $message = 'The page is not configured! [type=' . $this->type . '][' . $this->sPre . '].';
2437
                    $this->logger->alert($message);
2438
                    try {
2439
                        $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($GLOBALS['TYPO3_REQUEST'], $message);
2440
                        $this->sendResponseAndExit($response);
2441
                    } catch (ServiceUnavailableException $e) {
2442
                        $explanation = 'This means that there is no TypoScript object of type PAGE with typeNum=' . $this->type . ' configured.';
2443
                        throw new ServiceUnavailableException($message . ' ' . $explanation, 1294587217);
2444
                    }
2445
                } else {
2446
                    if (!isset($this->config['config'])) {
2447
                        $this->config['config'] = [];
2448
                    }
2449
                    // Filling the config-array, first with the main "config." part
2450
                    if (is_array($this->tmpl->setup['config.'])) {
2451
                        ArrayUtility::mergeRecursiveWithOverrule($this->tmpl->setup['config.'], $this->config['config']);
2452
                        $this->config['config'] = $this->tmpl->setup['config.'];
2453
                    }
2454
                    // override it with the page/type-specific "config."
2455
                    if (is_array($this->pSetup['config.'])) {
2456
                        ArrayUtility::mergeRecursiveWithOverrule($this->config['config'], $this->pSetup['config.']);
2457
                    }
2458
                    // @deprecated since TYPO3 v9, can be removed in TYPO3 v10
2459
                    if ($this->config['config']['typolinkCheckRootline']) {
2460
                        $this->logDeprecatedTyposcript('config.typolinkCheckRootline', 'The functionality is always enabled since TYPO3 v9 and can be removed from your TypoScript code');
2461
                    }
2462
                    // Set default values for removeDefaultJS and inlineStyle2TempFile so CSS and JS are externalized if compatversion is higher than 4.0
2463
                    if (!isset($this->config['config']['removeDefaultJS'])) {
2464
                        $this->config['config']['removeDefaultJS'] = 'external';
2465
                    }
2466
                    if (!isset($this->config['config']['inlineStyle2TempFile'])) {
2467
                        $this->config['config']['inlineStyle2TempFile'] = 1;
2468
                    }
2469
2470
                    if (!isset($this->config['config']['compressJs'])) {
2471
                        $this->config['config']['compressJs'] = 0;
2472
                    }
2473
                    // Processing for the config_array:
2474
                    $this->config['rootLine'] = $this->tmpl->rootLine;
2475
                    // Class for render Header and Footer parts
2476
                    if ($this->pSetup['pageHeaderFooterTemplateFile']) {
2477
                        $file = $this->tmpl->getFileName($this->pSetup['pageHeaderFooterTemplateFile']);
2478
                        if ($file) {
2479
                            $this->pageRenderer->setTemplateFile($file);
2480
                        }
2481
                    }
2482
                }
2483
                $timeTracker->pull();
2484
            } else {
2485
                $message = 'No TypoScript template found!';
2486
                $this->logger->alert($message);
2487
                try {
2488
                    $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($GLOBALS['TYPO3_REQUEST'], $message);
2489
                    $this->sendResponseAndExit($response);
2490
                } catch (ServiceUnavailableException $e) {
2491
                    throw new ServiceUnavailableException($message, 1294587218);
2492
                }
2493
            }
2494
        }
2495
2496
        // No cache
2497
        // Set $this->no_cache TRUE if the config.no_cache value is set!
2498
        if ($this->config['config']['no_cache']) {
2499
            $this->set_no_cache('config.no_cache is set');
2500
        }
2501
        // Merge GET with defaultGetVars
2502
        if (!empty($this->config['config']['defaultGetVars.'])) {
2503
            $modifiedGetVars = GeneralUtility::removeDotsFromTS($this->config['config']['defaultGetVars.']);
2504
            ArrayUtility::mergeRecursiveWithOverrule($modifiedGetVars, GeneralUtility::_GET());
2505
            GeneralUtility::_GETset($modifiedGetVars);
2506
        }
2507
2508
        // Auto-configure settings when a site is configured
2509
        if ($this->getCurrentSiteLanguage()) {
2510
            $this->config['config']['absRefPrefix'] = $this->config['config']['absRefPrefix'] ?? 'auto';
2511
        }
2512
2513
        // Hook for postProcessing the configuration array
2514
        $params = ['config' => &$this->config['config']];
2515
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'] ?? [] as $funcRef) {
2516
            GeneralUtility::callUserFunction($funcRef, $params, $this);
2517
        }
2518
    }
2519
2520
    /********************************************
2521
     *
2522
     * Further initialization and data processing
2523
     *
2524
     *******************************************/
2525
2526
    /**
2527
     * Setting the language key that will be used by the current page.
2528
     * 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.
2529
     *
2530
     * @access private
2531
     */
2532
    public function settingLanguage()
2533
    {
2534
        $_params = [];
2535
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'] ?? [] as $_funcRef) {
2536
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2537
        }
2538
2539
        $siteLanguage = $this->getCurrentSiteLanguage();
2540
2541
        // Initialize charset settings etc.
2542
        if ($siteLanguage) {
2543
            $languageKey = $siteLanguage->getTypo3Language();
2544
        } else {
2545
            $languageKey = $this->config['config']['language'] ?? 'default';
2546
        }
2547
        $this->lang = $languageKey;
2548
        $this->setOutputLanguage($languageKey);
2549
2550
        // Rendering charset of HTML page.
2551
        if (isset($this->config['config']['metaCharset']) && $this->config['config']['metaCharset'] !== 'utf-8') {
2552
            $this->metaCharset = $this->config['config']['metaCharset'];
2553
        }
2554
2555
        // Get values from site language
2556
        if ($siteLanguage) {
2557
            $this->sys_language_uid = ($this->sys_language_content = $siteLanguage->getLanguageId());
2558
            $this->sys_language_mode = $siteLanguage->getFallbackType();
2559
            if ($this->sys_language_mode === 'fallback') {
2560
                $fallbackOrder = $siteLanguage->getFallbackLanguageIds();
2561
                $fallbackOrder[] = 'pageNotFound';
2562
            }
2563
        } else {
2564
            // Get values from TypoScript, if not set before
2565
            if ($this->sys_language_uid === 0) {
2566
                $this->sys_language_uid = ($this->sys_language_content = (int)$this->config['config']['sys_language_uid']);
2567
            }
2568
            list($this->sys_language_mode, $fallbackOrder) = GeneralUtility::trimExplode(';', $this->config['config']['sys_language_mode']);
2569
            if (!empty($fallbackOrder)) {
2570
                $fallBackOrder = GeneralUtility::trimExplode(',', $fallbackOrder);
2571
            } else {
2572
                $fallBackOrder = [0];
2573
            }
2574
        }
2575
2576
        $this->sys_language_contentOL = $this->config['config']['sys_language_overlay'];
2577
        // If sys_language_uid is set to another language than default:
2578
        if ($this->sys_language_uid > 0) {
2579
            // check whether a shortcut is overwritten by a translated page
2580
            // we can only do this now, as this is the place where we get
2581
            // to know about translations
2582
            $this->checkTranslatedShortcut();
2583
            // Request the overlay record for the sys_language_uid:
2584
            $olRec = $this->sys_page->getPageOverlay($this->id, $this->sys_language_uid);
2585
            if (empty($olRec)) {
2586
                // If no OL record exists and a foreign language is asked for...
2587
                if ($this->sys_language_uid) {
2588
                    // If requested translation is not available:
2589
                    if (GeneralUtility::hideIfNotTranslated($this->page['l18n_cfg'])) {
2590
                        $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($GLOBALS['TYPO3_REQUEST'], 'Page is not available in the requested language.');
2591
                        $this->sendResponseAndExit($response);
2592
                    } else {
2593
                        switch ((string)$this->sys_language_mode) {
2594
                            case 'strict':
2595
                                $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($GLOBALS['TYPO3_REQUEST'], 'Page is not available in the requested language (strict).');
2596
                                $this->sendResponseAndExit($response);
2597
                                break;
2598
                            case 'fallback':
2599
                            case 'content_fallback':
2600
                                // Setting content uid (but leaving the sys_language_uid) when a content_fallback
2601
                                // value was found.
2602
                                foreach ($fallBackOrder ?? [] as $orderValue) {
2603
                                    if ($orderValue === '0' || $orderValue === 0 || $orderValue === '') {
2604
                                        $this->sys_language_content = 0;
2605
                                        break;
2606
                                    }
2607
                                    if (MathUtility::canBeInterpretedAsInteger($orderValue) && !empty($this->sys_page->getPageOverlay($this->id, (int)$orderValue))) {
2608
                                        $this->sys_language_content = (int)$orderValue;
2609
                                        break;
2610
                                    }
2611
                                    if ($orderValue === 'pageNotFound') {
2612
                                        // The existing fallbacks have not been found, but instead of continuing
2613
                                        // page rendering with default language, a "page not found" message should be shown
2614
                                        // instead.
2615
                                        $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($GLOBALS['TYPO3_REQUEST'], 'Page is not available in the requested language (fallbacks did not apply).');
2616
                                        $this->sendResponseAndExit($response);
2617
                                    }
2618
                                }
2619
                                break;
2620
                            case 'ignore':
2621
                                $this->sys_language_content = $this->sys_language_uid;
2622
                                break;
2623
                            default:
2624
                                // Default is that everything defaults to the default language...
2625
                                $this->sys_language_uid = ($this->sys_language_content = 0);
2626
                        }
2627
                    }
2628
                }
2629
            } else {
2630
                // Setting sys_language if an overlay record was found (which it is only if a language is used)
2631
                $this->page = $this->sys_page->getPageOverlay($this->page, $this->sys_language_uid);
2632
            }
2633
        }
2634
        // Setting sys_language_uid inside sys-page:
2635
        $this->sys_page->sys_language_uid = $this->sys_language_uid;
2636
        // If default translation is not available:
2637
        if ((!$this->sys_language_uid || !$this->sys_language_content) && GeneralUtility::hideIfDefaultLanguage($this->page['l18n_cfg'])) {
2638
            $message = 'Page is not available in default language.';
2639
            $this->logger->error($message);
2640
            $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($GLOBALS['TYPO3_REQUEST'], $message);
2641
            $this->sendResponseAndExit($response);
2642
        }
2643
        $this->updateRootLinesWithTranslations();
2644
2645
        // Finding the ISO code for the currently selected language
2646
        // fetched by the sys_language record when not fetching content from the default language
2647
        if ($siteLanguage = $this->getCurrentSiteLanguage()) {
2648
            $this->sys_language_isocode = $siteLanguage->getTwoLetterIsoCode();
2649
        } elseif ($this->sys_language_content > 0) {
2650
            // using sys_language_content because the ISO code only (currently) affect content selection from FlexForms - which should follow "sys_language_content"
2651
            // Set the fourth parameter to TRUE in the next two getRawRecord() calls to
2652
            // avoid versioning overlay to be applied as it generates an SQL error
2653
            $sys_language_row = $this->sys_page->getRawRecord('sys_language', $this->sys_language_content, 'language_isocode,static_lang_isocode');
2654
            if (is_array($sys_language_row) && !empty($sys_language_row['language_isocode'])) {
2655
                $this->sys_language_isocode = $sys_language_row['language_isocode'];
2656
            }
2657
            // the DB value is overridden by TypoScript
2658
            if (!empty($this->config['config']['sys_language_isocode'])) {
2659
                $this->sys_language_isocode = $this->config['config']['sys_language_isocode'];
2660
            }
2661
        } else {
2662
            // fallback to the TypoScript option when rendering with sys_language_uid=0
2663
            // also: use "en" by default
2664
            if (!empty($this->config['config']['sys_language_isocode_default'])) {
2665
                $this->sys_language_isocode = $this->config['config']['sys_language_isocode_default'];
2666
            } else {
2667
                $this->sys_language_isocode = $languageKey !== 'default' ? $languageKey : 'en';
2668
            }
2669
        }
2670
2671
        $_params = [];
2672
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'] ?? [] as $_funcRef) {
2673
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2674
        }
2675
    }
2676
2677
    /**
2678
     * Updating content of the two rootLines IF the language key is set!
2679
     */
2680
    protected function updateRootLinesWithTranslations()
2681
    {
2682
        if ($this->sys_language_uid) {
2683
            $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
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\Frontend\Page\...pository::getRootLine(). ( Ignorable by Annotation )

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

2683
            $this->rootLine = $this->sys_page->getRootLine(/** @scrutinizer ignore-type */ $this->id, $this->MP);
Loading history...
2684
            $this->tmpl->updateRootlineData($this->rootLine);
2685
        }
2686
    }
2687
2688
    /**
2689
     * Setting locale for frontend rendering
2690
     */
2691
    public function settingLocale()
2692
    {
2693
        // Setting locale
2694
        $locale = $this->config['config']['locale_all'];
2695
        $siteLanguage = $this->getCurrentSiteLanguage();
2696
        if ($siteLanguage) {
2697
            $locale = $siteLanguage->getLocale();
2698
        }
2699
        if ($locale) {
2700
            $availableLocales = GeneralUtility::trimExplode(',', $locale, true);
2701
            // If LC_NUMERIC is set e.g. to 'de_DE' PHP parses float values locale-aware resulting in strings with comma
2702
            // as decimal point which causes problems with value conversions - so we set all locale types except LC_NUMERIC
2703
            // @see https://bugs.php.net/bug.php?id=53711
2704
            $locale = setlocale(LC_COLLATE, ...$availableLocales);
2705
            if ($locale) {
2706
                // As str_* methods are locale aware and turkish has no upper case I
2707
                // Class autoloading and other checks depending on case changing break with turkish locale LC_CTYPE
2708
                // @see http://bugs.php.net/bug.php?id=35050
2709
                if (substr($locale, 0, 2) !== 'tr') {
2710
                    setlocale(LC_CTYPE, ...$availableLocales);
2711
                }
2712
                setlocale(LC_MONETARY, ...$availableLocales);
2713
                setlocale(LC_TIME, ...$availableLocales);
2714
            } else {
2715
                $this->getTimeTracker()->setTSlogMessage('Locale "' . htmlspecialchars($locale) . '" not found.', 3);
2716
            }
2717
        }
2718
    }
2719
2720
    /**
2721
     * Checks whether a translated shortcut page has a different shortcut
2722
     * target than the original language page.
2723
     * If that is the case, things get corrected to follow that alternative
2724
     * shortcut
2725
     */
2726
    protected function checkTranslatedShortcut()
2727
    {
2728
        if (!is_null($this->originalShortcutPage)) {
2729
            $originalShortcutPageOverlay = $this->sys_page->getPageOverlay($this->originalShortcutPage['uid'], $this->sys_language_uid);
2730
            if (!empty($originalShortcutPageOverlay['shortcut']) && $originalShortcutPageOverlay['shortcut'] != $this->id) {
2731
                // the translation of the original shortcut page has a different shortcut target!
2732
                // set the correct page and id
2733
                $shortcut = $this->getPageShortcut($originalShortcutPageOverlay['shortcut'], $originalShortcutPageOverlay['shortcut_mode'], $originalShortcutPageOverlay['uid']);
2734
                $this->id = ($this->contentPid = $shortcut['uid']);
2735
                $this->page = $this->sys_page->getPage($this->id);
2736
                // Fix various effects on things like menus f.e.
2737
                $this->fetch_the_id();
2738
                $this->tmpl->rootLine = array_reverse($this->rootLine);
2739
            }
2740
        }
2741
    }
2742
2743
    /**
2744
     * Handle data submission
2745
     * This is done at this point, because we need the config values
2746
     */
2747
    public function handleDataSubmission()
2748
    {
2749
        // Hook for processing data submission to extensions
2750
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission'] ?? [] as $className) {
2751
            $_procObj = GeneralUtility::makeInstance($className);
2752
            $_procObj->checkDataSubmission($this);
2753
        }
2754
    }
2755
2756
    /**
2757
     * Loops over all configured URL handlers and registers all active handlers in the redirect URL handler array.
2758
     *
2759
     * @see $activeRedirectUrlHandlers
2760
     */
2761
    public function initializeRedirectUrlHandlers()
2762
    {
2763
        $urlHandlers = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['urlProcessing']['urlHandlers'] ?? false;
2764
        if (!$urlHandlers) {
2765
            return;
2766
        }
2767
2768
        foreach ($urlHandlers as $identifier => $configuration) {
2769
            if (empty($configuration) || !is_array($configuration)) {
2770
                throw new \RuntimeException('Missing configuration for URL handler "' . $identifier . '".', 1442052263);
2771
            }
2772
            if (!is_string($configuration['handler']) || empty($configuration['handler']) || !class_exists($configuration['handler']) || !is_subclass_of($configuration['handler'], UrlHandlerInterface::class)) {
2773
                throw new \RuntimeException('The URL handler "' . $identifier . '" defines an invalid provider. Ensure the class exists and implements the "' . UrlHandlerInterface::class . '".', 1442052249);
2774
            }
2775
        }
2776
2777
        $orderedHandlers = GeneralUtility::makeInstance(DependencyOrderingService::class)->orderByDependencies($urlHandlers);
2778
2779
        foreach ($orderedHandlers as $configuration) {
2780
            /** @var UrlHandlerInterface $urlHandler */
2781
            $urlHandler = GeneralUtility::makeInstance($configuration['handler']);
2782
            if ($urlHandler->canHandleCurrentUrl()) {
2783
                $this->activeUrlHandlers[] = $urlHandler;
2784
            }
2785
        }
2786
    }
2787
2788
    /**
2789
     * Loops over all registered URL handlers and lets them process the current URL.
2790
     *
2791
     * If no handler has stopped the current process (e.g. by redirecting) and a
2792
     * the redirectUrl propert is not empty, the user will be redirected to this URL.
2793
     *
2794
     * @internal Should be called by the FrontendRequestHandler only.
2795
     * @return ResponseInterface|null
2796
     */
2797
    public function redirectToExternalUrl()
2798
    {
2799
        foreach ($this->activeUrlHandlers as $redirectHandler) {
2800
            $response = $redirectHandler->handle();
2801
            if ($response instanceof ResponseInterface) {
2802
                return $response;
2803
            }
2804
        }
2805
2806
        if (!empty($this->activeUrlHandlers)) {
2807
            throw new \RuntimeException('A URL handler is active but did not process the URL.', 1442305505);
2808
        }
2809
2810
        return null;
2811
    }
2812
2813
    /**
2814
     * Sets the URL_ID_TOKEN in the internal var, $this->getMethodUrlIdToken
2815
     * This feature allows sessions to use a GET-parameter instead of a cookie.
2816
     *
2817
     * @access private
2818
     */
2819
    public function setUrlIdToken()
2820
    {
2821
        if ($this->config['config']['ftu']) {
2822
            $this->getMethodUrlIdToken = $GLOBALS['TYPO3_CONF_VARS']['FE']['get_url_id_token'];
2823
        } else {
2824
            $this->getMethodUrlIdToken = '';
2825
        }
2826
    }
2827
2828
    /**
2829
     * Calculates and sets the internal linkVars based upon the current
2830
     * $_GET parameters and the setting "config.linkVars".
2831
     */
2832
    public function calculateLinkVars()
2833
    {
2834
        $this->linkVars = '';
2835
        if (empty($this->config['config']['linkVars'])) {
2836
            return;
2837
        }
2838
2839
        $linkVars = $this->splitLinkVarsString((string)$this->config['config']['linkVars']);
2840
2841
        if (empty($linkVars)) {
2842
            return;
2843
        }
2844
        $getData = GeneralUtility::_GET();
2845
        foreach ($linkVars as $linkVar) {
2846
            $test = $value = '';
2847
            if (preg_match('/^(.*)\\((.+)\\)$/', $linkVar, $match)) {
2848
                $linkVar = trim($match[1]);
2849
                $test = trim($match[2]);
2850
            }
2851
2852
            $keys = explode('|', $linkVar);
2853
            $numberOfLevels = count($keys);
2854
            $rootKey = trim($keys[0]);
2855
            if (!isset($getData[$rootKey])) {
2856
                continue;
2857
            }
2858
            $value = $getData[$rootKey];
2859
            for ($i = 1; $i < $numberOfLevels; $i++) {
2860
                $currentKey = trim($keys[$i]);
2861
                if (isset($value[$currentKey])) {
2862
                    $value = $value[$currentKey];
2863
                } else {
2864
                    $value = false;
2865
                    break;
2866
                }
2867
            }
2868
            if ($value !== false) {
2869
                $parameterName = $keys[0];
2870
                for ($i = 1; $i < $numberOfLevels; $i++) {
2871
                    $parameterName .= '[' . $keys[$i] . ']';
2872
                }
2873
                if (!is_array($value)) {
2874
                    $temp = rawurlencode($value);
2875
                    if ($test !== '' && !$this->isAllowedLinkVarValue($temp, $test)) {
2876
                        // Error: This value was not allowed for this key
2877
                        continue;
2878
                    }
2879
                    $value = '&' . $parameterName . '=' . $temp;
2880
                } else {
2881
                    if ($test !== '' && $test !== 'array') {
2882
                        // Error: This key must not be an array!
2883
                        continue;
2884
                    }
2885
                    $value = GeneralUtility::implodeArrayForUrl($parameterName, $value);
2886
                }
2887
                $this->linkVars .= $value;
2888
            }
2889
        }
2890
    }
2891
2892
    /**
2893
     * Split the link vars string by "," but not if the "," is inside of braces
2894
     *
2895
     * @param $string
2896
     *
2897
     * @return array
2898
     */
2899
    protected function splitLinkVarsString(string $string): array
2900
    {
2901
        $tempCommaReplacementString = '###KASPER###';
2902
2903
        // replace every "," wrapped in "()" by a "unique" string
2904
        $string = preg_replace_callback('/\((?>[^()]|(?R))*\)/', function ($result) use ($tempCommaReplacementString) {
2905
            return str_replace(',', $tempCommaReplacementString, $result[0]);
2906
        }, $string);
2907
2908
        $string = GeneralUtility::trimExplode(',', $string);
2909
2910
        // replace all "unique" strings back to ","
2911
        return str_replace($tempCommaReplacementString, ',', $string);
2912
    }
2913
2914
    /**
2915
     * Checks if the value defined in "config.linkVars" contains an allowed value.
2916
     * Otherwise, return FALSE which means the value will not be added to any links.
2917
     *
2918
     * @param string $haystack The string in which to find $needle
2919
     * @param string $needle The string to find in $haystack
2920
     * @return bool Returns TRUE if $needle matches or is found in $haystack
2921
     */
2922
    protected function isAllowedLinkVarValue(string $haystack, string $needle): bool
2923
    {
2924
        $isAllowed = false;
2925
        // Integer
2926
        if ($needle === 'int' || $needle === 'integer') {
2927
            if (MathUtility::canBeInterpretedAsInteger($haystack)) {
2928
                $isAllowed = true;
2929
            }
2930
        } elseif (preg_match('/^\\/.+\\/[imsxeADSUXu]*$/', $needle)) {
2931
            // Regular expression, only "//" is allowed as delimiter
2932
            if (@preg_match($needle, $haystack)) {
2933
                $isAllowed = true;
2934
            }
2935
        } elseif (strstr($needle, '-')) {
2936
            // Range
2937
            if (MathUtility::canBeInterpretedAsInteger($haystack)) {
2938
                $range = explode('-', $needle);
2939
                if ($range[0] <= $haystack && $range[1] >= $haystack) {
2940
                    $isAllowed = true;
2941
                }
2942
            }
2943
        } elseif (strstr($needle, '|')) {
2944
            // List
2945
            // Trim the input
2946
            $haystack = str_replace(' ', '', $haystack);
2947
            if (strstr('|' . $needle . '|', '|' . $haystack . '|')) {
2948
                $isAllowed = true;
2949
            }
2950
        } elseif ((string)$needle === (string)$haystack) {
2951
            // String comparison
2952
            $isAllowed = true;
2953
        }
2954
        return $isAllowed;
2955
    }
2956
2957
    /**
2958
     * Returns URI of target page, if the current page is an overlaid mountpoint.
2959
     *
2960
     * If the current page is of type mountpoint and should be overlaid with the contents of the mountpoint page
2961
     * and is accessed directly, the user will be redirected to the mountpoint context.
2962
     * @internal
2963
     */
2964
    public function getRedirectUriForMountPoint(): ?string
2965
    {
2966
        if (!empty($this->originalMountPointPage) && (int)$this->originalMountPointPage['doktype'] === PageRepository::DOKTYPE_MOUNTPOINT) {
2967
            return $this->getUriToCurrentPageForRedirect();
2968
        }
2969
2970
        return null;
2971
    }
2972
2973
    /**
2974
     * Redirect to target page if the current page is an overlaid mountpoint.
2975
     *
2976
     * If the current page is of type mountpoint and should be overlaid with the contents of the mountpoint page
2977
     * and is accessed directly, the user will be redirected to the mountpoint context.
2978
     * @deprecated in TYPO3 9, will be removed in TYPO3 10
2979
     */
2980
    public function checkPageForMountpointRedirect()
2981
    {
2982
        trigger_error('Method ' . __FUNCTION__ . 'is deprecated.', \E_USER_DEPRECATED);
2983
        if (!empty($this->originalMountPointPage) && $this->originalMountPointPage['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT) {
2984
            $this->redirectToCurrentPage();
0 ignored issues
show
Deprecated Code introduced by
The function TYPO3\CMS\Frontend\Contr...redirectToCurrentPage() has been deprecated: in TYPO3 9, will be removed in TYPO3 10 ( Ignorable by Annotation )

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

2984
            /** @scrutinizer ignore-deprecated */ $this->redirectToCurrentPage();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
2985
        }
2986
    }
2987
2988
    /**
2989
     * Returns URI of target page, if the current page is a Shortcut.
2990
     *
2991
     * If the current page is of type shortcut and accessed directly via its URL,
2992
     * the user will be redirected to shortcut target.
2993
     * @internal
2994
     */
2995
    public function getRedirectUriForShortcut(): ?string
2996
    {
2997
        if (!empty($this->originalShortcutPage) && $this->originalShortcutPage['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
2998
            return $this->getUriToCurrentPageForRedirect();
2999
        }
3000
3001
        return null;
3002
    }
3003
3004
    /**
3005
     * Redirect to target page, if the current page is a Shortcut.
3006
     *
3007
     * If the current page is of type shortcut and accessed directly via its URL, this function redirects to the
3008
     * Shortcut target using a Location header.
3009
     * @deprecated in TYPO3 9, will be removed in TYPO3 10
3010
     */
3011
    public function checkPageForShortcutRedirect()
3012
    {
3013
        trigger_error('Method ' . __FUNCTION__ . 'is deprecated.', \E_USER_DEPRECATED);
3014
        if (!empty($this->originalShortcutPage) && (int)$this->originalShortcutPage['doktype'] === PageRepository::DOKTYPE_SHORTCUT) {
3015
            $this->redirectToCurrentPage();
0 ignored issues
show
Deprecated Code introduced by
The function TYPO3\CMS\Frontend\Contr...redirectToCurrentPage() has been deprecated: in TYPO3 9, will be removed in TYPO3 10 ( Ignorable by Annotation )

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

3015
            /** @scrutinizer ignore-deprecated */ $this->redirectToCurrentPage();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
3016
        }
3017
    }
3018
3019
    /**
3020
     * Builds a typolink to the current page, appends the type parameter if required
3021
     * and redirects the user to the generated URL using a Location header.
3022
     * @deprecated in TYPO3 9, will be removed in TYPO3 10
3023
     */
3024
    protected function redirectToCurrentPage()
3025
    {
3026
        trigger_error('Method ' . __FUNCTION__ . 'is deprecated.', \E_USER_DEPRECATED);
3027
        $redirectUrl = $this->getUriToCurrentPageForRedirect();
3028
        // Prevent redirection loop
3029
        if (!empty($redirectUrl) && GeneralUtility::getIndpEnv('REQUEST_URI') !== '/' . $redirectUrl) {
3030
            // redirect and exit
3031
            HttpUtility::redirect($redirectUrl, HttpUtility::HTTP_STATUS_307);
3032
        }
3033
    }
3034
3035
    /**
3036
     * @return string
3037
     */
3038
    protected function getUriToCurrentPageForRedirect(): string
3039
    {
3040
        $this->calculateLinkVars();
3041
        // Instantiate \TYPO3\CMS\Frontend\ContentObject to generate the correct target URL
3042
        /** @var $cObj ContentObjectRenderer */
3043
        $cObj = GeneralUtility::makeInstance(ContentObjectRenderer::class);
3044
        $parameter = $this->page['uid'];
3045
        $type = GeneralUtility::_GET('type');
3046
        if ($type && MathUtility::canBeInterpretedAsInteger($type)) {
3047
            $parameter .= ',' . $type;
3048
        }
3049
        $redirectUrl = $cObj->typoLink_URL([
3050
            'parameter' => $parameter,
3051
            'addQueryString' => true,
3052
            'addQueryString.' => ['exclude' => 'id']
3053
        ]);
3054
        return $redirectUrl;
3055
    }
3056
3057
    /********************************************
3058
     *
3059
     * Page generation; cache handling
3060
     *
3061
     *******************************************/
3062
    /**
3063
     * Returns TRUE if the page should be generated.
3064
     * That is if no URL handler is active and the cacheContentFlag is not set.
3065
     *
3066
     * @return bool
3067
     */
3068
    public function isGeneratePage()
3069
    {
3070
        return !$this->cacheContentFlag && empty($this->activeUrlHandlers);
3071
    }
3072
3073
    /**
3074
     * Temp cache content
3075
     * The temporary cache will expire after a few seconds (typ. 30) or will be cleared by the rendered page, which will also clear and rewrite the cache.
3076
     */
3077
    public function tempPageCacheContent()
3078
    {
3079
        $this->tempContent = false;
3080
        if (!$this->no_cache) {
3081
            $seconds = 30;
3082
            $title = htmlspecialchars($this->printTitle($this->page['title']));
3083
            $request_uri = htmlspecialchars(GeneralUtility::getIndpEnv('REQUEST_URI'));
3084
            $stdMsg = '
3085
		<strong>Page is being generated.</strong><br />
3086
		If this message does not disappear within ' . $seconds . ' seconds, please reload.';
3087
            $message = $this->config['config']['message_page_is_being_generated'];
3088
            if ((string)$message !== '') {
3089
                $message = str_replace('###TITLE###', $title, $message);
3090
                $message = str_replace('###REQUEST_URI###', $request_uri, $message);
3091
            } else {
3092
                $message = $stdMsg;
3093
            }
3094
            $temp_content = '<?xml version="1.0" encoding="UTF-8"?>
3095
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3096
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3097
<html xmlns="http://www.w3.org/1999/xhtml">
3098
	<head>
3099
		<title>' . $title . '</title>
3100
		<meta http-equiv="refresh" content="10" />
3101
	</head>
3102
	<body style="background-color:white; font-family:Verdana,Arial,Helvetica,sans-serif; color:#cccccc; text-align:center;">' . $message . '
3103
	</body>
3104
</html>';
3105
            // Fix 'nice errors' feature in modern browsers
3106
            $padSuffix = '<!--pad-->';
3107
            // prevent any trims
3108
            $padSize = 768 - strlen($padSuffix) - strlen($temp_content);
3109
            if ($padSize > 0) {
3110
                $temp_content = str_pad($temp_content, $padSize, LF) . $padSuffix;
3111
            }
3112
            if (!$this->headerNoCache() && ($cachedRow = $this->getFromCache_queryRow())) {
0 ignored issues
show
Unused Code introduced by
The assignment to $cachedRow is dead and can be removed.
Loading history...
3113
                // We are here because between checking for cached content earlier and now some other HTTP-process managed to store something in cache AND it was not due to a shift-reload by-pass.
3114
                // This is either the "Page is being generated" screen or it can be the final result.
3115
                // In any case we should not begin another rendering process also, so we silently disable caching and render the page ourselves and that's it.
3116
                // Actually $cachedRow contains content that we could show instead of rendering. Maybe we should do that to gain more performance but then we should set all the stuff done in $this->getFromCache()... For now we stick to this...
3117
                $this->set_no_cache('Another process wrote into the cache since the beginning of the render process', true);
3118
3119
            // Since the new Locking API this should never be the case
3120
            } else {
3121
                $this->tempContent = true;
3122
                // This flag shows that temporary content is put in the cache
3123
                $this->setPageCacheContent($temp_content, $this->config, $GLOBALS['EXEC_TIME'] + $seconds);
3124
            }
3125
        }
3126
    }
3127
3128
    /**
3129
     * Set cache content to $this->content
3130
     */
3131
    public function realPageCacheContent()
3132
    {
3133
        // seconds until a cached page is too old
3134
        $cacheTimeout = $this->get_cache_timeout();
3135
        $timeOutTime = $GLOBALS['EXEC_TIME'] + $cacheTimeout;
3136
        $this->tempContent = false;
3137
        $usePageCache = true;
3138
        // Hook for deciding whether page cache should be written to the cache backend or not
3139
        // NOTE: as hooks are called in a loop, the last hook will have the final word (however each
3140
        // hook receives the current status of the $usePageCache flag)
3141
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['usePageCache'] ?? [] as $className) {
3142
            $_procObj = GeneralUtility::makeInstance($className);
3143
            $usePageCache = $_procObj->usePageCache($this, $usePageCache);
3144
        }
3145
        // Write the page to cache, if necessary
3146
        if ($usePageCache) {
3147
            $this->setPageCacheContent($this->content, $this->config, $timeOutTime);
3148
        }
3149
        // Hook for cache post processing (eg. writing static files!)
3150
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['insertPageIncache'] ?? [] as $className) {
3151
            $_procObj = GeneralUtility::makeInstance($className);
3152
            $_procObj->insertPageIncache($this, $timeOutTime);
3153
        }
3154
    }
3155
3156
    /**
3157
     * Sets cache content; Inserts the content string into the cache_pages cache.
3158
     *
3159
     * @param string $content The content to store in the HTML field of the cache table
3160
     * @param mixed $data The additional cache_data array, fx. $this->config
3161
     * @param int $expirationTstamp Expiration timestamp
3162
     * @see realPageCacheContent(), tempPageCacheContent()
3163
     */
3164
    public function setPageCacheContent($content, $data, $expirationTstamp)
3165
    {
3166
        $cacheData = [
3167
            'identifier' => $this->newHash,
3168
            'page_id' => $this->id,
3169
            'content' => $content,
3170
            'temp_content' => $this->tempContent,
3171
            'cache_data' => $data,
3172
            'expires' => $expirationTstamp,
3173
            'tstamp' => $GLOBALS['EXEC_TIME'],
3174
            'pageTitleInfo' => [
3175
                'title' => $this->page['title'],
3176
                'altPageTitle' => $this->altPageTitle,
3177
                'indexedDocTitle' => $this->indexedDocTitle
3178
            ]
3179
        ];
3180
        $this->cacheExpires = $expirationTstamp;
3181
        $this->pageCacheTags[] = 'pageId_' . $cacheData['page_id'];
3182
        if ($this->page_cache_reg1) {
0 ignored issues
show
Deprecated Code introduced by
The property TYPO3\CMS\Frontend\Contr...oller::$page_cache_reg1 has been deprecated: since TYPO3 v9, will be removed in TYPO3 v10. ( Ignorable by Annotation )

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

3182
        if (/** @scrutinizer ignore-deprecated */ $this->page_cache_reg1) {

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
3183
            // @deprecated since TYPO3 v9, will be removed in TYPO3 v10. Remove this "if" along with property page_cache_reg1
3184
            trigger_error('Property page_cache_reg1 has been deprecated and will be removed in core version 10', E_USER_DEPRECATED);
3185
            $reg1 = (int)$this->page_cache_reg1;
0 ignored issues
show
Deprecated Code introduced by
The property TYPO3\CMS\Frontend\Contr...oller::$page_cache_reg1 has been deprecated: since TYPO3 v9, will be removed in TYPO3 v10. ( Ignorable by Annotation )

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

3185
            $reg1 = (int)/** @scrutinizer ignore-deprecated */ $this->page_cache_reg1;

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
3186
            $cacheData['reg1'] = $reg1;
3187
            $this->pageCacheTags[] = 'reg1_' . $reg1;
3188
        }
3189
        if (!empty($this->page['cache_tags'])) {
3190
            $tags = GeneralUtility::trimExplode(',', $this->page['cache_tags'], true);
3191
            $this->pageCacheTags = array_merge($this->pageCacheTags, $tags);
3192
        }
3193
        $this->pageCache->set($this->newHash, $cacheData, $this->pageCacheTags, $expirationTstamp - $GLOBALS['EXEC_TIME']);
3194
    }
3195
3196
    /**
3197
     * Clears cache content (for $this->newHash)
3198
     */
3199
    public function clearPageCacheContent()
3200
    {
3201
        $this->pageCache->remove($this->newHash);
3202
    }
3203
3204
    /**
3205
     * Clears cache content for a list of page ids
3206
     *
3207
     * @param string $pidList A list of INTEGER numbers which points to page uids for which to clear entries in the cache_pages cache (page content cache)
3208
     */
3209
    public function clearPageCacheContent_pidList($pidList)
3210
    {
3211
        $pageIds = GeneralUtility::trimExplode(',', $pidList);
3212
        foreach ($pageIds as $pageId) {
3213
            $this->pageCache->flushByTag('pageId_' . (int)$pageId);
0 ignored issues
show
Bug introduced by
The method flushByTag() does not exist on TYPO3\CMS\Core\Cache\Backend\AbstractBackend. Did you maybe mean flushByTags()? ( Ignorable by Annotation )

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

3213
            $this->pageCache->/** @scrutinizer ignore-call */ 
3214
                              flushByTag('pageId_' . (int)$pageId);

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...
3214
        }
3215
    }
3216
3217
    /**
3218
     * Sets sys last changed
3219
     * 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.
3220
     *
3221
     * @see ContentObjectRenderer::lastChanged()
3222
     */
3223
    public function setSysLastChanged()
3224
    {
3225
        // We only update the info if browsing the live workspace
3226
        if (!$this->doWorkspacePreview() && $this->page['SYS_LASTCHANGED'] < (int)$this->register['SYS_LASTCHANGED']) {
3227
            $connection = GeneralUtility::makeInstance(ConnectionPool::class)
3228
                ->getConnectionForTable('pages');
3229
            $connection->update(
3230
                'pages',
3231
                [
3232
                    'SYS_LASTCHANGED' => (int)$this->register['SYS_LASTCHANGED']
3233
                ],
3234
                [
3235
                    'uid' => (int)$this->id
3236
                ]
3237
            );
3238
        }
3239
    }
3240
3241
    /**
3242
     * Release pending locks
3243
     *
3244
     * @internal
3245
     */
3246
    public function releaseLocks()
3247
    {
3248
        $this->releaseLock('pagesection');
3249
        $this->releaseLock('pages');
3250
    }
3251
3252
    /**
3253
     * Adds tags to this page's cache entry, you can then f.e. remove cache
3254
     * entries by tag
3255
     *
3256
     * @param array $tags An array of tag
3257
     */
3258
    public function addCacheTags(array $tags)
3259
    {
3260
        $this->pageCacheTags = array_merge($this->pageCacheTags, $tags);
3261
    }
3262
3263
    /********************************************
3264
     *
3265
     * Page generation; rendering and inclusion
3266
     *
3267
     *******************************************/
3268
    /**
3269
     * Does some processing BEFORE the pagegen script is included.
3270
     */
3271
    public function generatePage_preProcessing()
3272
    {
3273
        // Same codeline as in getFromCache(). But $this->all has been changed by
3274
        // \TYPO3\CMS\Core\TypoScript\TemplateService::start() in the meantime, so this must be called again!
3275
        $this->newHash = $this->getHash();
3276
3277
        // If the pages_lock is set, we are in charge of generating the page.
3278
        if (is_object($this->locks['pages']['accessLock'])) {
3279
            // Here we put some temporary stuff in the cache in order to let the first hit generate the page.
3280
            // The temporary cache will expire after a few seconds (typ. 30) or will be cleared by the rendered page,
3281
            // which will also clear and rewrite the cache.
3282
            $this->tempPageCacheContent();
3283
        }
3284
        // At this point we have a valid pagesection_cache and also some temporary page_cache content,
3285
        // so let all other processes proceed now. (They are blocked at the pagessection_lock in getFromCache())
3286
        $this->releaseLock('pagesection');
3287
3288
        // Setting cache_timeout_default. May be overridden by PHP include scripts.
3289
        $this->cacheTimeOutDefault = (int)$this->config['config']['cache_period'];
3290
        // Page is generated
3291
        $this->no_cacheBeforePageGen = $this->no_cache;
3292
    }
3293
3294
    /**
3295
     * Previously located in static method in PageGenerator::init. Is solely used to set up TypoScript
3296
     * config. options and set properties in $TSFE for that.
3297
     */
3298
    public function preparePageContentGeneration()
3299
    {
3300
        $this->getTimeTracker()->push('Prepare page content generation');
3301
        if ($this->page['content_from_pid'] > 0) {
3302
            // make REAL copy of TSFE object - not reference!
3303
            $temp_copy_TSFE = clone $this;
3304
            // 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!
3305
            $temp_copy_TSFE->id = $this->page['content_from_pid'];
3306
            $temp_copy_TSFE->MP = '';
3307
            $temp_copy_TSFE->getPageAndRootlineWithDomain($this->config['config']['content_from_pid_allowOutsideDomain'] ? 0 : $this->domainStartPage);
3308
            $this->contentPid = (int)$temp_copy_TSFE->id;
3309
            unset($temp_copy_TSFE);
3310
        }
3311
        if ($this->config['config']['MP_defaults']) {
3312
            $temp_parts = GeneralUtility::trimExplode('|', $this->config['config']['MP_defaults'], true);
3313
            foreach ($temp_parts as $temp_p) {
3314
                list($temp_idP, $temp_MPp) = explode(':', $temp_p, 2);
3315
                $temp_ids = GeneralUtility::intExplode(',', $temp_idP);
3316
                foreach ($temp_ids as $temp_id) {
3317
                    $this->MP_defaults[$temp_id] = $temp_MPp;
3318
                }
3319
            }
3320
        }
3321
        // Global vars...
3322
        $this->indexedDocTitle = $this->page['title'];
3323
        $this->debug = !empty($this->config['config']['debug']);
3324
        // Base url:
3325
        if (isset($this->config['config']['baseURL'])) {
3326
            $this->baseUrl = $this->config['config']['baseURL'];
3327
        }
3328
        // Internal and External target defaults
3329
        $this->intTarget = '' . $this->config['config']['intTarget'];
3330
        $this->extTarget = '' . $this->config['config']['extTarget'];
3331
        $this->fileTarget = '' . $this->config['config']['fileTarget'];
3332
        if ($this->config['config']['spamProtectEmailAddresses'] === 'ascii') {
3333
            $this->spamProtectEmailAddresses = 'ascii';
3334
        } else {
3335
            $this->spamProtectEmailAddresses = MathUtility::forceIntegerInRange($this->config['config']['spamProtectEmailAddresses'], -10, 10, 0);
3336
        }
3337
        // calculate the absolute path prefix
3338
        if (!empty($this->config['config']['absRefPrefix'])) {
3339
            $absRefPrefix = trim($this->config['config']['absRefPrefix']);
3340
            if ($absRefPrefix === 'auto') {
3341
                $this->absRefPrefix = GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
3342
            } else {
3343
                $this->absRefPrefix = $absRefPrefix;
3344
            }
3345
        } else {
3346
            $this->absRefPrefix = '';
3347
        }
3348
        $this->ATagParams = trim($this->config['config']['ATagParams']) ? ' ' . trim($this->config['config']['ATagParams']) : '';
3349
        $this->initializeSearchWordDataInTsfe();
3350
        // linkVars
3351
        $this->calculateLinkVars();
3352
        // Setting XHTML-doctype from doctype
3353
        if (!$this->config['config']['xhtmlDoctype']) {
3354
            $this->config['config']['xhtmlDoctype'] = $this->config['config']['doctype'];
3355
        }
3356
        if ($this->config['config']['xhtmlDoctype']) {
3357
            $this->xhtmlDoctype = $this->config['config']['xhtmlDoctype'];
3358
            // Checking XHTML-docytpe
3359
            switch ((string)$this->config['config']['xhtmlDoctype']) {
3360
                case 'xhtml_trans':
3361
                case 'xhtml_strict':
3362
                    $this->xhtmlVersion = 100;
3363
                    break;
3364
                case 'xhtml_basic':
3365
                    $this->xhtmlVersion = 105;
3366
                    break;
3367
                case 'xhtml_11':
3368
                case 'xhtml+rdfa_10':
3369
                    $this->xhtmlVersion = 110;
3370
                    break;
3371
                default:
3372
                    $this->pageRenderer->setRenderXhtml(false);
3373
                    $this->xhtmlDoctype = '';
3374
                    $this->xhtmlVersion = 0;
3375
            }
3376
        } else {
3377
            $this->pageRenderer->setRenderXhtml(false);
3378
        }
3379
3380
        // Global content object
3381
        $this->newCObj();
3382
        $this->getTimeTracker()->pull();
3383
    }
3384
3385
    /**
3386
     * Fills the sWordList property and builds the regular expression in TSFE that can be used to split
3387
     * strings by the submitted search words.
3388
     *
3389
     * @see sWordList
3390
     * @see sWordRegEx
3391
     */
3392
    protected function initializeSearchWordDataInTsfe()
3393
    {
3394
        $this->sWordRegEx = '';
3395
        $this->sWordList = GeneralUtility::_GP('sword_list');
3396
        if (is_array($this->sWordList)) {
3397
            $space = !empty($this->config['config']['sword_standAlone']) ? '[[:space:]]' : '';
3398
            foreach ($this->sWordList as $val) {
3399
                if (trim($val) !== '') {
3400
                    $this->sWordRegEx .= $space . preg_quote($val, '/') . $space . '|';
3401
                }
3402
            }
3403
            $this->sWordRegEx = rtrim($this->sWordRegEx, '|');
3404
        }
3405
    }
3406
3407
    /**
3408
     * Does some processing AFTER the pagegen script is included.
3409
     * This includes caching the page, indexing the page (if configured) and setting sysLastChanged
3410
     */
3411
    public function generatePage_postProcessing()
3412
    {
3413
        // 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.
3414
        if ($this->no_cacheBeforePageGen) {
3415
            $this->set_no_cache('no_cache has been set before the page was generated - safety check', true);
3416
        }
3417
        // Hook for post-processing of page content cached/non-cached:
3418
        $_params = ['pObj' => &$this];
3419
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-all'] ?? [] as $_funcRef) {
3420
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
3421
        }
3422
        // Processing if caching is enabled:
3423
        if (!$this->no_cache) {
3424
            // Hook for post-processing of page content before being cached:
3425
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-cached'] ?? [] as $_funcRef) {
3426
                GeneralUtility::callUserFunction($_funcRef, $_params, $this);
3427
            }
3428
        }
3429
        // Convert char-set for output: (should be BEFORE indexing of the content (changed 22/4 2005)),
3430
        // because otherwise indexed search might convert from the wrong charset!
3431
        // One thing is that the charset mentioned in the HTML header would be wrong since the output charset (metaCharset)
3432
        // has not been converted to from utf-8. And indexed search will internally convert from metaCharset
3433
        // to utf-8 so the content MUST be in metaCharset already!
3434
        $this->content = $this->convOutputCharset($this->content);
3435
        // Hook for indexing pages
3436
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageIndexing'] ?? [] as $className) {
3437
            $_procObj = GeneralUtility::makeInstance($className);
3438
            $_procObj->hook_indexContent($this);
3439
        }
3440
        // Storing for cache:
3441
        if (!$this->no_cache) {
3442
            $this->realPageCacheContent();
3443
        } elseif ($this->tempContent) {
3444
            // If there happens to be temporary content in the cache and the cache was not cleared due to new content, put it in... ($this->no_cache=0)
3445
            $this->clearPageCacheContent();
3446
            $this->tempContent = false;
3447
        }
3448
        // Sets sys-last-change:
3449
        $this->setSysLastChanged();
3450
    }
3451
3452
    /**
3453
     * Generate the page title, can be called multiple times,
3454
     * as $this->altPageTitle might have been modified by an uncached plugin etc.
3455
     *
3456
     * @return string the generated page title
3457
     */
3458
    public function generatePageTitle(): string
3459
    {
3460
        $pageTitleSeparator = '';
3461
3462
        // Check for a custom pageTitleSeparator, and perform stdWrap on it
3463
        if (isset($this->config['config']['pageTitleSeparator']) && $this->config['config']['pageTitleSeparator'] !== '') {
3464
            $pageTitleSeparator = $this->config['config']['pageTitleSeparator'];
3465
3466
            if (isset($this->config['config']['pageTitleSeparator.']) && is_array($this->config['config']['pageTitleSeparator.'])) {
3467
                $pageTitleSeparator = $this->cObj->stdWrap($pageTitleSeparator, $this->config['config']['pageTitleSeparator.']);
3468
            } else {
3469
                $pageTitleSeparator .= ' ';
3470
            }
3471
        }
3472
3473
        $pageTitle = $this->altPageTitle ?: $this->page['title'] ?? '';
3474
        $titleTagContent = $this->printTitle(
3475
            $pageTitle,
3476
            (bool)$this->config['config']['noPageTitle'],
3477
            (bool)$this->config['config']['pageTitleFirst'],
3478
            $pageTitleSeparator
3479
        );
3480
        if ($this->config['config']['titleTagFunction']) {
3481
            $titleTagContent = $this->cObj->callUserFunction(
3482
                $this->config['config']['titleTagFunction'],
3483
                [],
3484
                $titleTagContent
3485
            );
3486
        }
3487
        // stdWrap around the title tag
3488
        if (isset($this->config['config']['pageTitle.']) && is_array($this->config['config']['pageTitle.'])) {
3489
            $titleTagContent = $this->cObj->stdWrap($titleTagContent, $this->config['config']['pageTitle.']);
3490
        }
3491
3492
        // config.noPageTitle = 2 - means do not render the page title
3493
        if ($this->config['config']['noPageTitle'] === 2) {
3494
            $titleTagContent = '';
3495
        }
3496
        if ($titleTagContent !== '') {
3497
            $this->pageRenderer->setTitle($titleTagContent);
3498
        }
3499
        return (string)$titleTagContent;
3500
    }
3501
3502
    /**
3503
     * Compiles the content for the page <title> tag.
3504
     *
3505
     * @param string $pageTitle The input title string, typically the "title" field of a page's record.
3506
     * @param bool $noTitle If set, then only the site title is outputted (from $this->setup['sitetitle'])
3507
     * @param bool $showTitleFirst If set, then "sitetitle" and $title is swapped
3508
     * @param string $pageTitleSeparator an alternative to the ": " as the separator between site title and page title
3509
     * @return string The page title on the form "[sitetitle]: [input-title]". Not htmlspecialchar()'ed.
3510
     * @see tempPageCacheContent(), generatePageTitle()
3511
     */
3512
    protected function printTitle(string $pageTitle, bool $noTitle = false, bool $showTitleFirst = false, string $pageTitleSeparator = ''): string
3513
    {
3514
        $siteTitle = trim($this->tmpl->setup['sitetitle'] ?? '');
3515
        $pageTitle = $noTitle ? '' : $pageTitle;
3516
        if ($showTitleFirst) {
3517
            $temp = $siteTitle;
3518
            $siteTitle = $pageTitle;
3519
            $pageTitle = $temp;
3520
        }
3521
        // only show a separator if there are both site title and page title
3522
        if ($pageTitle === '' || $siteTitle === '') {
3523
            $pageTitleSeparator = '';
3524
        } elseif (empty($pageTitleSeparator)) {
3525
            // use the default separator if non given
3526
            $pageTitleSeparator = ': ';
3527
        }
3528
        return $siteTitle . $pageTitleSeparator . $pageTitle;
3529
    }
3530
3531
    /**
3532
     * Processes the INTinclude-scripts
3533
     */
3534
    public function INTincScript()
3535
    {
3536
        // Deprecated stuff:
3537
        // @deprecated: annotation added TYPO3 4.6
3538
        $this->additionalHeaderData = is_array($this->config['INTincScript_ext']['additionalHeaderData']) ? $this->config['INTincScript_ext']['additionalHeaderData'] : [];
3539
        $this->additionalFooterData = is_array($this->config['INTincScript_ext']['additionalFooterData']) ? $this->config['INTincScript_ext']['additionalFooterData'] : [];
3540
        $this->additionalJavaScript = $this->config['INTincScript_ext']['additionalJavaScript'];
3541
        $this->additionalCSS = $this->config['INTincScript_ext']['additionalCSS'];
3542
        $this->divSection = '';
3543
        if (empty($this->config['INTincScript_ext']['pageRenderer'])) {
3544
            $this->initPageRenderer();
3545
        } else {
3546
            /** @var PageRenderer $pageRenderer */
3547
            $pageRenderer = unserialize($this->config['INTincScript_ext']['pageRenderer']);
3548
            $this->pageRenderer = $pageRenderer;
3549
            GeneralUtility::setSingletonInstance(PageRenderer::class, $pageRenderer);
3550
        }
3551
3552
        $this->recursivelyReplaceIntPlaceholdersInContent();
3553
        $this->getTimeTracker()->push('Substitute header section');
3554
        $this->INTincScript_loadJSCode();
3555
        $this->generatePageTitle();
3556
3557
        $this->content = str_replace(
3558
            [
3559
                '<!--HD_' . $this->config['INTincScript_ext']['divKey'] . '-->',
3560
                '<!--FD_' . $this->config['INTincScript_ext']['divKey'] . '-->',
3561
                '<!--TDS_' . $this->config['INTincScript_ext']['divKey'] . '-->'
3562
            ],
3563
            [
3564
                $this->convOutputCharset(implode(LF, $this->additionalHeaderData)),
3565
                $this->convOutputCharset(implode(LF, $this->additionalFooterData)),
3566
                $this->convOutputCharset($this->divSection),
3567
            ],
3568
            $this->pageRenderer->renderJavaScriptAndCssForProcessingOfUncachedContentObjects($this->content, $this->config['INTincScript_ext']['divKey'])
3569
        );
3570
        // Replace again, because header and footer data and page renderer replacements may introduce additional placeholders (see #44825)
3571
        $this->recursivelyReplaceIntPlaceholdersInContent();
3572
        $this->setAbsRefPrefix();
3573
        $this->getTimeTracker()->pull();
3574
    }
3575
3576
    /**
3577
     * Replaces INT placeholders (COA_INT and USER_INT) in $this->content
3578
     * In case the replacement adds additional placeholders, it loops
3579
     * until no new placeholders are found any more.
3580
     */
3581
    protected function recursivelyReplaceIntPlaceholdersInContent()
3582
    {
3583
        do {
3584
            $INTiS_config = $this->config['INTincScript'];
3585
            $this->INTincScript_process($INTiS_config);
3586
            // Check if there were new items added to INTincScript during the previous execution:
3587
            $INTiS_config = array_diff_assoc($this->config['INTincScript'], $INTiS_config);
3588
            $reprocess = count($INTiS_config) > 0;
3589
        } while ($reprocess);
3590
    }
3591
3592
    /**
3593
     * Processes the INTinclude-scripts and substitue in content.
3594
     *
3595
     * @param array $INTiS_config $GLOBALS['TSFE']->config['INTincScript'] or part of it
3596
     * @see INTincScript()
3597
     */
3598
    protected function INTincScript_process($INTiS_config)
3599
    {
3600
        $timeTracker = $this->getTimeTracker();
3601
        $timeTracker->push('Split content');
3602
        // Splits content with the key.
3603
        $INTiS_splitC = explode('<!--INT_SCRIPT.', $this->content);
3604
        $this->content = '';
3605
        $timeTracker->setTSlogMessage('Parts: ' . count($INTiS_splitC));
3606
        $timeTracker->pull();
3607
        foreach ($INTiS_splitC as $INTiS_c => $INTiS_cPart) {
3608
            // If the split had a comment-end after 32 characters it's probably a split-string
3609
            if (substr($INTiS_cPart, 32, 3) === '-->') {
3610
                $INTiS_key = 'INT_SCRIPT.' . substr($INTiS_cPart, 0, 32);
3611
                if (is_array($INTiS_config[$INTiS_key])) {
3612
                    $label = 'Include ' . $INTiS_config[$INTiS_key]['type'];
3613
                    $label = $label . isset($INTiS_config[$INTiS_key]['file']) ? ' ' . $INTiS_config[$INTiS_key]['file'] : '';
3614
                    $timeTracker->push($label, '');
3615
                    $incContent = '';
3616
                    $INTiS_cObj = unserialize($INTiS_config[$INTiS_key]['cObj']);
3617
                    /* @var $INTiS_cObj ContentObjectRenderer */
3618
                    switch ($INTiS_config[$INTiS_key]['type']) {
3619
                        case 'COA':
3620
                            $incContent = $INTiS_cObj->cObjGetSingle('COA', $INTiS_config[$INTiS_key]['conf']);
3621
                            break;
3622
                        case 'FUNC':
3623
                            $incContent = $INTiS_cObj->cObjGetSingle('USER', $INTiS_config[$INTiS_key]['conf']);
3624
                            break;
3625
                        case 'POSTUSERFUNC':
3626
                            $incContent = $INTiS_cObj->callUserFunction($INTiS_config[$INTiS_key]['postUserFunc'], $INTiS_config[$INTiS_key]['conf'], $INTiS_config[$INTiS_key]['content']);
3627
                            break;
3628
                    }
3629
                    $this->content .= $this->convOutputCharset($incContent);
3630
                    $this->content .= substr($INTiS_cPart, 35);
3631
                    $timeTracker->pull($incContent);
3632
                } else {
3633
                    $this->content .= substr($INTiS_cPart, 35);
3634
                }
3635
            } else {
3636
                $this->content .= ($INTiS_c ? '<!--INT_SCRIPT.' : '') . $INTiS_cPart;
3637
            }
3638
        }
3639
    }
3640
3641
    /**
3642
     * Loads the JavaScript code for INTincScript
3643
     */
3644
    public function INTincScript_loadJSCode()
3645
    {
3646
        // Add javascript
3647
        $jsCode = trim($this->JSCode);
3648
        $additionalJavaScript = is_array($this->additionalJavaScript)
0 ignored issues
show
introduced by
The condition is_array($this->additionalJavaScript) is always true.
Loading history...
3649
            ? implode(LF, $this->additionalJavaScript)
3650
            : $this->additionalJavaScript;
3651
        $additionalJavaScript = trim($additionalJavaScript);
3652
        if ($jsCode !== '' || $additionalJavaScript !== '') {
3653
            $this->additionalHeaderData['JSCode'] = '
3654
<script type="text/javascript">
3655
	/*<![CDATA[*/
3656
<!--
3657
' . $additionalJavaScript . '
3658
' . $jsCode . '
3659
// -->
3660
	/*]]>*/
3661
</script>';
3662
        }
3663
        // Add CSS
3664
        $additionalCss = is_array($this->additionalCSS) ? implode(LF, $this->additionalCSS) : $this->additionalCSS;
0 ignored issues
show
introduced by
The condition is_array($this->additionalCSS) is always true.
Loading history...
3665
        $additionalCss = trim($additionalCss);
3666
        if ($additionalCss !== '') {
3667
            $this->additionalHeaderData['_CSS'] = '
3668
<style type="text/css">
3669
' . $additionalCss . '
3670
</style>';
3671
        }
3672
    }
3673
3674
    /**
3675
     * Determines if there are any INTincScripts to include.
3676
     *
3677
     * @return bool Returns TRUE if scripts are found and no URL handler is active.
3678
     */
3679
    public function isINTincScript()
3680
    {
3681
        return is_array($this->config['INTincScript']) && empty($this->activeUrlHandlers);
3682
    }
3683
3684
    /********************************************
3685
     *
3686
     * Finished off; outputting, storing session data, statistics...
3687
     *
3688
     *******************************************/
3689
    /**
3690
     * Determines if content should be outputted.
3691
     * Outputting content is done only if no URL handler is active and no hook disables the output.
3692
     *
3693
     * @return bool Returns TRUE if no redirect URL is set and no hook disables the output.
3694
     */
3695
    public function isOutputting()
3696
    {
3697
        // Initialize by status if there is a Redirect URL
3698
        $enableOutput = empty($this->activeUrlHandlers);
3699
        // Call hook for possible disabling of output:
3700
        $_params = ['pObj' => &$this, 'enableOutput' => &$enableOutput];
3701
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['isOutputting'] ?? [] as $_funcRef) {
3702
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
3703
        }
3704
        return $enableOutput;
3705
    }
3706
3707
    /**
3708
     * Process the output before it's actually outputted. Sends headers also.
3709
     *
3710
     * This includes substituting the "username" comment, sending additional headers
3711
     * (as defined in the TypoScript "config.additionalheaders" object), XHTML cleaning content (if configured)
3712
     * Works on $this->content.
3713
     */
3714
    public function processOutput()
3715
    {
3716
        // Set header for charset-encoding unless disabled
3717
        if (empty($this->config['config']['disableCharsetHeader'])) {
3718
            $headLine = 'Content-Type: ' . $this->contentType . '; charset=' . trim($this->metaCharset);
3719
            header($headLine);
3720
        }
3721
        // Set header for content language unless disabled
3722
        if (empty($this->config['config']['disableLanguageHeader']) && !empty($this->sys_language_isocode)) {
3723
            $headLine = 'Content-Language: ' . trim($this->sys_language_isocode);
3724
            header($headLine);
3725
        }
3726
        // Set cache related headers to client (used to enable proxy / client caching!)
3727
        if (!empty($this->config['config']['sendCacheHeaders'])) {
3728
            $this->sendCacheHeaders();
3729
        }
3730
        // Set headers, if any
3731
        $this->sendAdditionalHeaders();
3732
        // Send appropriate status code in case of temporary content
3733
        if ($this->tempContent) {
3734
            $this->addTempContentHttpHeaders();
3735
        }
3736
        // Make substitution of eg. username/uid in content only if cache-headers for client/proxy caching is NOT sent!
3737
        if (!$this->isClientCachable) {
3738
            $this->contentStrReplace();
3739
        }
3740
        // Hook for post-processing of page content before output:
3741
        $_params = ['pObj' => &$this];
3742
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-output'] ?? [] as $_funcRef) {
3743
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
3744
        }
3745
    }
3746
3747
    /**
3748
     * Send cache headers good for client/reverse proxy caching
3749
     * This function should not be called if the page content is
3750
     * temporary (like for "Page is being generated..." message,
3751
     * but in that case it is ok because the config-variables
3752
     * are not yet available and so will not allow to send
3753
     * cache headers)
3754
     */
3755
    public function sendCacheHeaders()
3756
    {
3757
        // Getting status whether we can send cache control headers for proxy caching:
3758
        $doCache = $this->isStaticCacheble();
3759
        // 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...
3760
        $loginsDeniedCfg = empty($this->config['config']['sendCacheHeaders_onlyWhenLoginDeniedInBranch']) || empty($this->loginAllowedInBranch);
3761
        // Finally, when backend users are logged in, do not send cache headers at all (Admin Panel might be displayed for instance).
3762
        if ($doCache && !$this->beUserLogin && !$this->doWorkspacePreview() && $loginsDeniedCfg) {
3763
            // Build headers:
3764
            $headers = [
3765
                'Expires: ' . gmdate('D, d M Y H:i:s T', $this->cacheExpires),
3766
                'ETag: "' . md5($this->content) . '"',
3767
                'Cache-Control: max-age=' . ($this->cacheExpires - $GLOBALS['EXEC_TIME']),
3768
                // no-cache
3769
                'Pragma: public'
3770
            ];
3771
            $this->isClientCachable = true;
3772
        } else {
3773
            // Build headers
3774
            // "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
3775
            $headers = [
3776
                'Cache-Control: private, no-store'
3777
            ];
3778
            $this->isClientCachable = false;
3779
            // Now, if a backend user is logged in, tell him in the Admin Panel log what the caching status would have been:
3780
            if ($this->beUserLogin) {
3781
                if ($doCache) {
3782
                    $this->getTimeTracker()->setTSlogMessage('Cache-headers with max-age "' . ($this->cacheExpires - $GLOBALS['EXEC_TIME']) . '" would have been sent');
3783
                } else {
3784
                    $reasonMsg = '';
3785
                    $reasonMsg .= !$this->no_cache ? '' : 'Caching disabled (no_cache). ';
3786
                    $reasonMsg .= !$this->isINTincScript() ? '' : '*_INT object(s) on page. ';
3787
                    $reasonMsg .= !is_array($this->fe_user->user) ? '' : 'Frontend user logged in. ';
3788
                    $this->getTimeTracker()->setTSlogMessage('Cache-headers would disable proxy caching! Reason(s): "' . $reasonMsg . '"', 1);
3789
                }
3790
            }
3791
        }
3792
        // Send headers:
3793
        foreach ($headers as $hL) {
3794
            header($hL);
3795
        }
3796
    }
3797
3798
    /**
3799
     * Reporting status whether we can send cache control headers for proxy caching or publishing to static files
3800
     *
3801
     * Rules are:
3802
     * no_cache cannot be set: If it is, the page might contain dynamic content and should never be cached.
3803
     * There can be no USER_INT objects on the page ("isINTincScript()") because they implicitly indicate dynamic content
3804
     * 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)
3805
     *
3806
     * @return bool
3807
     */
3808
    public function isStaticCacheble()
3809
    {
3810
        $doCache = !$this->no_cache && !$this->isINTincScript() && !$this->isUserOrGroupSet();
3811
        return $doCache;
3812
    }
3813
3814
    /**
3815
     * Substitute various tokens in content. This should happen only if the content is not cached by proxies or client browsers.
3816
     */
3817
    public function contentStrReplace()
3818
    {
3819
        $search = [];
3820
        $replace = [];
3821
        // Substitutes username mark with the username
3822
        if (!empty($this->fe_user->user['uid'])) {
3823
            // User name:
3824
            $token = isset($this->config['config']['USERNAME_substToken']) ? trim($this->config['config']['USERNAME_substToken']) : '';
3825
            $search[] = $token ? $token : '<!--###USERNAME###-->';
3826
            $replace[] = $this->fe_user->user['username'];
3827
            // User uid (if configured):
3828
            $token = isset($this->config['config']['USERUID_substToken']) ? trim($this->config['config']['USERUID_substToken']) : '';
3829
            if ($token) {
3830
                $search[] = $token;
3831
                $replace[] = $this->fe_user->user['uid'];
3832
            }
3833
        }
3834
        // Substitutes get_URL_ID in case of GET-fallback
3835
        if ($this->getMethodUrlIdToken) {
3836
            $search[] = $this->getMethodUrlIdToken;
3837
            $replace[] = $this->fe_user->get_URL_ID;
3838
        }
3839
        // Hook for supplying custom search/replace data
3840
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-contentStrReplace'] ?? [] as $_funcRef) {
3841
            $_params = [
3842
                'search' => &$search,
3843
                'replace' => &$replace
3844
            ];
3845
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
3846
        }
3847
        if (!empty($search)) {
3848
            $this->content = str_replace($search, $replace, $this->content);
3849
        }
3850
    }
3851
3852
    /**
3853
     * Stores session data for the front end user
3854
     */
3855
    public function storeSessionData()
3856
    {
3857
        $this->fe_user->storeSessionData();
3858
    }
3859
3860
    /**
3861
     * Outputs preview info.
3862
     */
3863
    public function previewInfo()
3864
    {
3865
        if ($this->fePreview !== 0) {
3866
            $previewInfo = '';
3867
            $_params = ['pObj' => &$this];
3868
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_previewInfo'] ?? [] as $_funcRef) {
3869
                $previewInfo .= GeneralUtility::callUserFunction($_funcRef, $_params, $this);
3870
            }
3871
            $this->content = str_ireplace('</body>', $previewInfo . '</body>', $this->content);
3872
        }
3873
    }
3874
3875
    /**
3876
     * End-Of-Frontend hook
3877
     */
3878
    public function hook_eofe()
3879
    {
3880
        $_params = ['pObj' => &$this];
3881
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_eofe'] ?? [] as $_funcRef) {
3882
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
3883
        }
3884
    }
3885
3886
    /**
3887
     * Sends HTTP headers for temporary content. These headers prevent search engines from caching temporary content and asks them to revisit this page again.
3888
     */
3889
    public function addTempContentHttpHeaders()
3890
    {
3891
        header('HTTP/1.0 503 Service unavailable');
3892
        header('Retry-after: 3600');
3893
        header('Pragma: no-cache');
3894
        header('Cache-control: no-cache');
3895
        header('Expire: 0');
3896
    }
3897
3898
    /********************************************
3899
     *
3900
     * Various internal API functions
3901
     *
3902
     *******************************************/
3903
3904
    /**
3905
     * Creates an instance of ContentObjectRenderer in $this->cObj
3906
     * This instance is used to start the rendering of the TypoScript template structure
3907
     *
3908
     * @see pagegen.php
3909
     */
3910
    public function newCObj()
3911
    {
3912
        $this->cObj = GeneralUtility::makeInstance(ContentObjectRenderer::class);
3913
        $this->cObj->start($this->page, 'pages');
3914
    }
3915
3916
    /**
3917
     * Converts relative paths in the HTML source to absolute paths for fileadmin/, typo3conf/ext/ and media/ folders.
3918
     *
3919
     * @access private
3920
     * @see pagegen.php, INTincScript()
3921
     */
3922
    public function setAbsRefPrefix()
3923
    {
3924
        if (!$this->absRefPrefix) {
3925
            return;
3926
        }
3927
        $search = [
3928
            '"typo3temp/',
3929
            '"typo3conf/ext/',
3930
            '"' . TYPO3_mainDir . 'ext/',
3931
            '"' . TYPO3_mainDir . 'sysext/'
3932
        ];
3933
        $replace = [
3934
            '"' . $this->absRefPrefix . 'typo3temp/',
3935
            '"' . $this->absRefPrefix . 'typo3conf/ext/',
3936
            '"' . $this->absRefPrefix . TYPO3_mainDir . 'ext/',
3937
            '"' . $this->absRefPrefix . TYPO3_mainDir . 'sysext/'
3938
        ];
3939
        /** @var $storageRepository StorageRepository */
3940
        $storageRepository = GeneralUtility::makeInstance(StorageRepository::class);
3941
        $storages = $storageRepository->findAll();
3942
        foreach ($storages as $storage) {
3943
            if ($storage->getDriverType() === 'Local' && $storage->isPublic() && $storage->isOnline()) {
3944
                $folder = $storage->getPublicUrl($storage->getRootLevelFolder(), true);
3945
                $search[] = '"' . $folder;
3946
                $replace[] = '"' . $this->absRefPrefix . $folder;
3947
            }
3948
        }
3949
        // Process additional directories
3950
        $directories = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['additionalAbsRefPrefixDirectories'], true);
3951
        foreach ($directories as $directory) {
3952
            $search[] = '"' . $directory;
3953
            $replace[] = '"' . $this->absRefPrefix . $directory;
3954
        }
3955
        $this->content = str_replace(
3956
            $search,
3957
            $replace,
3958
            $this->content
3959
        );
3960
    }
3961
3962
    /**
3963
     * Prefixing the input URL with ->baseUrl If ->baseUrl is set and the input url is not absolute in some way.
3964
     * 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!
3965
     *
3966
     * @param string $url Input URL, relative or absolute
3967
     * @return string Processed input value.
3968
     */
3969
    public function baseUrlWrap($url)
3970
    {
3971
        if ($this->baseUrl) {
3972
            $urlParts = parse_url($url);
3973
            if (empty($urlParts['scheme']) && $url[0] !== '/') {
3974
                $url = $this->baseUrl . $url;
3975
            }
3976
        }
3977
        return $url;
3978
    }
3979
3980
    /**
3981
     * Logs access to deprecated TypoScript objects and properties.
3982
     *
3983
     * Dumps message to the TypoScript message log (admin panel) and the TYPO3 deprecation log.
3984
     *
3985
     * @param string $typoScriptProperty Deprecated object or property
3986
     * @param string $explanation Message or additional information
3987
     */
3988
    public function logDeprecatedTyposcript($typoScriptProperty, $explanation = '')
3989
    {
3990
        $explanationText = $explanation !== '' ? ' - ' . $explanation : '';
3991
        $this->getTimeTracker()->setTSlogMessage($typoScriptProperty . ' is deprecated.' . $explanationText, 2);
3992
        trigger_error('TypoScript property ' . $typoScriptProperty . ' is deprecated' . $explanationText, E_USER_DEPRECATED);
3993
    }
3994
3995
    /********************************************
3996
     * PUBLIC ACCESSIBLE WORKSPACES FUNCTIONS
3997
     *******************************************/
3998
3999
    /**
4000
     * Returns TRUE if workspace preview is enabled
4001
     *
4002
     * @return bool Returns TRUE if workspace preview is enabled
4003
     */
4004
    public function doWorkspacePreview()
4005
    {
4006
        return $this->whichWorkspace() > 0;
4007
    }
4008
4009
    /**
4010
     * Returns the uid of the current workspace
4011
     *
4012
     * @return int returns workspace integer for which workspace is being preview. 0 if none (= live workspace).
4013
     */
4014
    public function whichWorkspace()
4015
    {
4016
        return $this->beUserLogin ? $this->getBackendUser()->workspace : 0;
4017
    }
4018
4019
    /********************************************
4020
     *
4021
     * Various external API functions - for use in plugins etc.
4022
     *
4023
     *******************************************/
4024
4025
    /**
4026
     * Returns the pages TSconfig array based on the currect ->rootLine
4027
     *
4028
     * @return array
4029
     */
4030
    public function getPagesTSconfig()
4031
    {
4032
        if (!is_array($this->pagesTSconfig)) {
0 ignored issues
show
introduced by
The condition is_array($this->pagesTSconfig) is always true.
Loading history...
4033
            $TSdataArray = [];
4034
            foreach ($this->rootLine as $k => $v) {
4035
                // add TSconfig first, as $TSdataArray is reversed below and it shall be included last
4036
                $TSdataArray[] = $v['TSconfig'];
4037
                if (trim($v['tsconfig_includes'])) {
4038
                    $includeTsConfigFileList = GeneralUtility::trimExplode(',', $v['tsconfig_includes'], true);
4039
                    // reverse the includes first to make sure their order is preserved when $TSdataArray is reversed
4040
                    $includeTsConfigFileList = array_reverse($includeTsConfigFileList);
4041
                    // Traversing list
4042
                    foreach ($includeTsConfigFileList as $includeTsConfigFile) {
4043
                        if (strpos($includeTsConfigFile, 'EXT:') === 0) {
4044
                            list($includeTsConfigFileExtensionKey, $includeTsConfigFilename) = explode(
4045
                                '/',
4046
                                substr($includeTsConfigFile, 4),
4047
                                2
4048
                            );
4049
                            if ((string)$includeTsConfigFileExtensionKey !== ''
4050
                                && (string)$includeTsConfigFilename !== ''
4051
                                && ExtensionManagementUtility::isLoaded($includeTsConfigFileExtensionKey)
4052
                            ) {
4053
                                $includeTsConfigFileAndPath = ExtensionManagementUtility::extPath($includeTsConfigFileExtensionKey)
4054
                                    . $includeTsConfigFilename;
4055
                                if (file_exists($includeTsConfigFileAndPath)) {
4056
                                    $TSdataArray[] = file_get_contents($includeTsConfigFileAndPath);
4057
                                }
4058
                            }
4059
                        }
4060
                    }
4061
                }
4062
            }
4063
            // Adding the default configuration:
4064
            $TSdataArray[] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];
4065
            // Bring everything in the right order. Default first, then the Rootline down to the current page
4066
            $TSdataArray = array_reverse($TSdataArray);
4067
            // Parsing the user TS (or getting from cache)
4068
            $TSdataArray = TypoScriptParser::checkIncludeLines_array($TSdataArray);
4069
            $userTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
4070
            $identifier = md5('pageTS:' . $userTS);
4071
            $contentHashCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash');
4072
            $this->pagesTSconfig = $contentHashCache->get($identifier);
4073
            if (!is_array($this->pagesTSconfig)) {
4074
                $parseObj = GeneralUtility::makeInstance(TypoScriptParser::class);
4075
                $parseObj->parse($userTS);
4076
                $this->pagesTSconfig = $parseObj->setup;
4077
                $contentHashCache->set($identifier, $this->pagesTSconfig, ['PAGES_TSconfig'], 0);
4078
            }
4079
        }
4080
        return $this->pagesTSconfig;
4081
    }
4082
4083
    /**
4084
     * Sets JavaScript code in the additionalJavaScript array
4085
     *
4086
     * @param string $key is the key in the array, for num-key let the value be empty. Note reserved keys 'openPic' and 'mouseOver'
4087
     * @param string $content is the content if you want any
4088
     * @see \TYPO3\CMS\Frontend\ContentObject\Menu\GraphicalMenuContentObject::writeMenu(), ContentObjectRenderer::imageLinkWrap()
4089
     */
4090
    public function setJS($key, $content = '')
4091
    {
4092
        if ($key) {
4093
            switch ($key) {
4094
                case 'mouseOver':
4095
                    $this->additionalJavaScript[$key] = '		// JS function for mouse-over
4096
		function over(name, imgObj) {	//
4097
			if (document[name]) {document[name].src = eval(name+"_h.src");}
4098
			else if (document.getElementById && document.getElementById(name)) {document.getElementById(name).src = eval(name+"_h.src");}
4099
			else if (imgObj)	{imgObj.src = eval(name+"_h.src");}
4100
		}
4101
			// JS function for mouse-out
4102
		function out(name, imgObj) {	//
4103
			if (document[name]) {document[name].src = eval(name+"_n.src");}
4104
			else if (document.getElementById && document.getElementById(name)) {document.getElementById(name).src = eval(name+"_n.src");}
4105
			else if (imgObj)	{imgObj.src = eval(name+"_n.src");}
4106
		}';
4107
                    break;
4108
                case 'openPic':
4109
                    $this->additionalJavaScript[$key] = '	function openPic(url, winName, winParams) {	//
4110
			var theWindow = window.open(url, winName, winParams);
4111
			if (theWindow)	{theWindow.focus();}
4112
		}';
4113
                    break;
4114
                default:
4115
                    $this->additionalJavaScript[$key] = $content;
4116
            }
4117
        }
4118
    }
4119
4120
    /**
4121
     * Sets CSS data in the additionalCSS array
4122
     *
4123
     * @param string $key Is the key in the array, for num-key let the value be empty
4124
     * @param string $content Is the content if you want any
4125
     * @see setJS()
4126
     */
4127
    public function setCSS($key, $content)
4128
    {
4129
        if ($key) {
4130
            $this->additionalCSS[$key] = $content;
4131
        }
4132
    }
4133
4134
    /**
4135
     * Returns a unique md5 hash.
4136
     * 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.
4137
     *
4138
     * @param string $str Some string to include in what is hashed. Not significant at all.
4139
     * @return string MD5 hash of ->uniqueString, input string and uniqueCounter
4140
     */
4141
    public function uniqueHash($str = '')
4142
    {
4143
        return md5($this->uniqueString . '_' . $str . $this->uniqueCounter++);
4144
    }
4145
4146
    /**
4147
     * Sets the cache-flag to 1. Could be called from user-included php-files in order to ensure that a page is not cached.
4148
     *
4149
     * @param string $reason An optional reason to be written to the log.
4150
     * @param bool $internal Whether the call is done from core itself (should only be used by core).
4151
     */
4152
    public function set_no_cache($reason = '', $internal = false)
4153
    {
4154
        if ($reason !== '') {
4155
            $warning = '$TSFE->set_no_cache() was triggered. Reason: ' . $reason . '.';
4156
        } else {
4157
            $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
4158
            // This is a hack to work around ___FILE___ resolving symbolic links
4159
            $PATH_site_real = dirname(realpath(PATH_site . 'typo3')) . '/';
4160
            $file = $trace[0]['file'];
4161
            if (strpos($file, $PATH_site_real) === 0) {
4162
                $file = str_replace($PATH_site_real, '', $file);
4163
            } else {
4164
                $file = str_replace(PATH_site, '', $file);
4165
            }
4166
            $line = $trace[0]['line'];
4167
            $trigger = $file . ' on line ' . $line;
4168
            $warning = '$GLOBALS[\'TSFE\']->set_no_cache() was triggered by ' . $trigger . '.';
4169
        }
4170
        if ($GLOBALS['TYPO3_CONF_VARS']['FE']['disableNoCacheParameter']) {
4171
            $warning .= ' However, $TYPO3_CONF_VARS[\'FE\'][\'disableNoCacheParameter\'] is set, so it will be ignored!';
4172
            $this->getTimeTracker()->setTSlogMessage($warning, 2);
4173
        } else {
4174
            $warning .= ' Caching is disabled!';
4175
            $this->disableCache();
4176
        }
4177
        if ($internal && isset($GLOBALS['BE_USER'])) {
4178
            $this->logger->notice($warning);
4179
        } else {
4180
            $this->logger->warning($warning);
4181
        }
4182
    }
4183
4184
    /**
4185
     * Disables caching of the current page.
4186
     *
4187
     * @internal
4188
     */
4189
    protected function disableCache()
4190
    {
4191
        $this->no_cache = true;
4192
    }
4193
4194
    /**
4195
     * Sets the cache-timeout in seconds
4196
     *
4197
     * @param int $seconds Cache-timeout in seconds
4198
     */
4199
    public function set_cache_timeout_default($seconds)
4200
    {
4201
        $this->cacheTimeOutDefault = (int)$seconds;
4202
    }
4203
4204
    /**
4205
     * Get the cache timeout for the current page.
4206
     *
4207
     * @return int The cache timeout for the current page.
4208
     */
4209
    public function get_cache_timeout()
4210
    {
4211
        /** @var $runtimeCache \TYPO3\CMS\Core\Cache\Frontend\AbstractFrontend */
4212
        $runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_runtime');
4213
        $cachedCacheLifetimeIdentifier = 'core-tslib_fe-get_cache_timeout';
4214
        $cachedCacheLifetime = $runtimeCache->get($cachedCacheLifetimeIdentifier);
4215
        if ($cachedCacheLifetime === false) {
4216
            if ($this->page['cache_timeout']) {
4217
                // Cache period was set for the page:
4218
                $cacheTimeout = $this->page['cache_timeout'];
4219
            } elseif ($this->cacheTimeOutDefault) {
4220
                // Cache period was set for the whole site:
4221
                $cacheTimeout = $this->cacheTimeOutDefault;
4222
            } else {
4223
                // No cache period set at all, so we take one day (60*60*24 seconds = 86400 seconds):
4224
                $cacheTimeout = 86400;
4225
            }
4226
            if ($this->config['config']['cache_clearAtMidnight']) {
4227
                $timeOutTime = $GLOBALS['EXEC_TIME'] + $cacheTimeout;
4228
                $midnightTime = mktime(0, 0, 0, date('m', $timeOutTime), date('d', $timeOutTime), date('Y', $timeOutTime));
0 ignored issues
show
Bug introduced by
date('d', $timeOutTime) of type string is incompatible with the type integer expected by parameter $day of mktime(). ( Ignorable by Annotation )

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

4228
                $midnightTime = mktime(0, 0, 0, date('m', $timeOutTime), /** @scrutinizer ignore-type */ date('d', $timeOutTime), date('Y', $timeOutTime));
Loading history...
Bug introduced by
date('Y', $timeOutTime) of type string is incompatible with the type integer expected by parameter $year of mktime(). ( Ignorable by Annotation )

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

4228
                $midnightTime = mktime(0, 0, 0, date('m', $timeOutTime), date('d', $timeOutTime), /** @scrutinizer ignore-type */ date('Y', $timeOutTime));
Loading history...
Bug introduced by
date('m', $timeOutTime) of type string is incompatible with the type integer expected by parameter $month of mktime(). ( Ignorable by Annotation )

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

4228
                $midnightTime = mktime(0, 0, 0, /** @scrutinizer ignore-type */ date('m', $timeOutTime), date('d', $timeOutTime), date('Y', $timeOutTime));
Loading history...
4229
                // If the midnight time of the expire-day is greater than the current time,
4230
                // we may set the timeOutTime to the new midnighttime.
4231
                if ($midnightTime > $GLOBALS['EXEC_TIME']) {
4232
                    $cacheTimeout = $midnightTime - $GLOBALS['EXEC_TIME'];
4233
                }
4234
            }
4235
4236
            // Calculate the timeout time for records on the page and adjust cache timeout if necessary
4237
            $cacheTimeout = min($this->calculatePageCacheTimeout(), $cacheTimeout);
4238
4239
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['get_cache_timeout'] ?? [] as $_funcRef) {
4240
                $params = ['cacheTimeout' => $cacheTimeout];
4241
                $cacheTimeout = GeneralUtility::callUserFunction($_funcRef, $params, $this);
4242
            }
4243
            $runtimeCache->set($cachedCacheLifetimeIdentifier, $cacheTimeout);
4244
            $cachedCacheLifetime = $cacheTimeout;
4245
        }
4246
        return $cachedCacheLifetime;
4247
    }
4248
4249
    /**
4250
     * Returns a unique id to be used as a XML ID (in HTML / XHTML mode)
4251
     *
4252
     * @param string $desired The desired id. If already used it is suffixed with a number
4253
     * @return string The unique id
4254
     */
4255
    public function getUniqueId($desired = '')
4256
    {
4257
        if ($desired === '') {
4258
            // id has to start with a letter to reach XHTML compliance
4259
            $uniqueId = 'a' . $this->uniqueHash();
4260
        } else {
4261
            $uniqueId = $desired;
4262
            for ($i = 1; isset($this->usedUniqueIds[$uniqueId]); $i++) {
4263
                $uniqueId = $desired . '_' . $i;
4264
            }
4265
        }
4266
        $this->usedUniqueIds[$uniqueId] = true;
4267
        return $uniqueId;
4268
    }
4269
4270
    /*********************************************
4271
     *
4272
     * Localization and character set conversion
4273
     *
4274
     *********************************************/
4275
    /**
4276
     * Split Label function for front-end applications.
4277
     *
4278
     * @param string $input Key string. Accepts the "LLL:" prefix.
4279
     * @return string Label value, if any.
4280
     */
4281
    public function sL($input)
4282
    {
4283
        return $this->languageService->sL($input);
4284
    }
4285
4286
    /**
4287
     * Read locallang files - for frontend applications
4288
     *
4289
     * @param string $fileRef Reference to a relative filename to include.
4290
     * @return array Returns the $LOCAL_LANG array found in the file. If no array found, returns empty array.
4291
     * @deprecated since TYPO3 v9, will be removed in TYPO3 v10
4292
     */
4293
    public function readLLfile($fileRef)
4294
    {
4295
        trigger_error('This method will be removed in TYPO3 v10, as the method LanguageService->includeLLFile() can be used directly.', E_USER_DEPRECATED);
4296
        return $this->languageService->includeLLFile($fileRef, false, true);
4297
    }
4298
4299
    /**
4300
     * Returns 'locallang' label - may need initializing by initLLvars
4301
     *
4302
     * @param string $index Local_lang key for which to return label (language is determined by $this->lang)
4303
     * @param array $LOCAL_LANG The locallang array in which to search
4304
     * @return string|false Label value of $index key.
4305
     * @deprecated since TYPO3 v9, will be removed in TYPO3 v10, use LanguageService->getLLL() directly
4306
     */
4307
    public function getLLL($index, $LOCAL_LANG)
4308
    {
4309
        trigger_error('This method will be removed in TYPO3 v10, as the method LanguageService->getLLL() can be used directly.', E_USER_DEPRECATED);
4310
        if (isset($LOCAL_LANG[$this->lang][$index][0]['target'])) {
4311
            return $LOCAL_LANG[$this->lang][$index][0]['target'];
4312
        }
4313
        if (isset($LOCAL_LANG['default'][$index][0]['target'])) {
4314
            return $LOCAL_LANG['default'][$index][0]['target'];
4315
        }
4316
        return false;
4317
    }
4318
4319
    /**
4320
     * Initializing the getLL variables needed.
4321
     *
4322
     * @see settingLanguage()
4323
     * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.
4324
     */
4325
    public function initLLvars()
4326
    {
4327
        trigger_error('This method will be removed in TYPO3 v10, the initialization can be altered via hooks within settingLanguage().', E_USER_DEPRECATED);
4328
        $this->lang = $this->config['config']['language'] ?: 'default';
4329
        $this->setOutputLanguage($this->lang);
4330
4331
        // Rendering charset of HTML page.
4332
        if ($this->config['config']['metaCharset']) {
4333
            $this->metaCharset = trim(strtolower($this->config['config']['metaCharset']));
4334
        }
4335
    }
4336
4337
    /**
4338
     * Sets all internal measures what language the page should be rendered.
4339
     * This is not for records, but rather the HTML / charset and the locallang labels
4340
     *
4341
     * @param string $language - usually set via TypoScript config.language = dk
4342
     */
4343
    protected function setOutputLanguage($language = 'default')
4344
    {
4345
        $this->pageRenderer->setLanguage($language);
4346
        $this->languageService = GeneralUtility::makeInstance(LanguageService::class);
4347
        // Always disable debugging for TSFE
4348
        $this->languageService->debugKey = false;
4349
        $this->languageService->init($language);
4350
    }
4351
4352
    /**
4353
     * Converts input string from utf-8 to metaCharset IF the two charsets are different.
4354
     *
4355
     * @param string $content Content to be converted.
4356
     * @return string Converted content string.
4357
     * @throws \RuntimeException if an invalid charset was configured
4358
     */
4359
    public function convOutputCharset($content)
4360
    {
4361
        if ($this->metaCharset !== 'utf-8') {
4362
            /** @var CharsetConverter $charsetConverter */
4363
            $charsetConverter = GeneralUtility::makeInstance(CharsetConverter::class);
4364
            try {
4365
                $content = $charsetConverter->conv($content, 'utf-8', $this->metaCharset, true);
4366
            } catch (UnknownCharsetException $e) {
4367
                throw new \RuntimeException('Invalid config.metaCharset: ' . $e->getMessage(), 1508916185);
4368
            }
4369
        }
4370
        return $content;
4371
    }
4372
4373
    /**
4374
     * Converts the $_POST array from metaCharset (page HTML charset from input form) to utf-8 (internal processing) IF the two charsets are different.
4375
     */
4376
    public function convPOSTCharset()
4377
    {
4378
        if ($this->metaCharset !== 'utf-8' && is_array($_POST) && !empty($_POST)) {
4379
            $this->convertCharsetRecursivelyToUtf8($_POST, $this->metaCharset);
4380
            $GLOBALS['HTTP_POST_VARS'] = $_POST;
4381
        }
4382
    }
4383
4384
    /**
4385
     * Small helper function to convert charsets for arrays to UTF-8
4386
     *
4387
     * @param mixed $data given by reference (string/array usually)
4388
     * @param string $fromCharset convert FROM this charset
4389
     */
4390
    protected function convertCharsetRecursivelyToUtf8(&$data, string $fromCharset)
4391
    {
4392
        foreach ($data as $key => $value) {
4393
            if (is_array($data[$key])) {
4394
                $this->convertCharsetRecursivelyToUtf8($data[$key], $fromCharset);
4395
            } elseif (is_string($data[$key])) {
4396
                $data[$key] = mb_convert_encoding($data[$key], 'utf-8', $fromCharset);
4397
            }
4398
        }
4399
    }
4400
4401
    /**
4402
     * Calculates page cache timeout according to the records with starttime/endtime on the page.
4403
     *
4404
     * @return int Page cache timeout or PHP_INT_MAX if cannot be determined
4405
     */
4406
    protected function calculatePageCacheTimeout()
4407
    {
4408
        $result = PHP_INT_MAX;
4409
        // Get the configuration
4410
        $tablesToConsider = $this->getCurrentPageCacheConfiguration();
4411
        // Get the time, rounded to the minute (do not pollute MySQL cache!)
4412
        // It is ok that we do not take seconds into account here because this
4413
        // value will be subtracted later. So we never get the time "before"
4414
        // the cache change.
4415
        $now = $GLOBALS['ACCESS_TIME'];
4416
        // Find timeout by checking every table
4417
        foreach ($tablesToConsider as $tableDef) {
4418
            $result = min($result, $this->getFirstTimeValueForRecord($tableDef, $now));
4419
        }
4420
        // We return + 1 second just to ensure that cache is definitely regenerated
4421
        return $result === PHP_INT_MAX ? PHP_INT_MAX : $result - $now + 1;
4422
    }
4423
4424
    /**
4425
     * Obtains a list of table/pid pairs to consider for page caching.
4426
     *
4427
     * TS configuration looks like this:
4428
     *
4429
     * The cache lifetime of all pages takes starttime and endtime of news records of page 14 into account:
4430
     * config.cache.all = tt_news:14
4431
     *
4432
     * The cache lifetime of page 42 takes starttime and endtime of news records of page 15 and addresses of page 16 into account:
4433
     * config.cache.42 = tt_news:15,tt_address:16
4434
     *
4435
     * @return array Array of 'tablename:pid' pairs. There is at least a current page id in the array
4436
     * @see TypoScriptFrontendController::calculatePageCacheTimeout()
4437
     */
4438
    protected function getCurrentPageCacheConfiguration()
4439
    {
4440
        $result = ['tt_content:' . $this->id];
4441
        if (isset($this->config['config']['cache.'][$this->id])) {
4442
            $result = array_merge($result, GeneralUtility::trimExplode(',', $this->config['config']['cache.'][$this->id]));
4443
        }
4444
        if (isset($this->config['config']['cache.']['all'])) {
4445
            $result = array_merge($result, GeneralUtility::trimExplode(',', $this->config['config']['cache.']['all']));
4446
        }
4447
        return array_unique($result);
4448
    }
4449
4450
    /**
4451
     * Find the minimum starttime or endtime value in the table and pid that is greater than the current time.
4452
     *
4453
     * @param string $tableDef Table definition (format tablename:pid)
4454
     * @param int $now "Now" time value
4455
     * @throws \InvalidArgumentException
4456
     * @return int Value of the next start/stop time or PHP_INT_MAX if not found
4457
     * @see TypoScriptFrontendController::calculatePageCacheTimeout()
4458
     */
4459
    protected function getFirstTimeValueForRecord($tableDef, $now)
4460
    {
4461
        $now = (int)$now;
4462
        $result = PHP_INT_MAX;
4463
        list($tableName, $pid) = GeneralUtility::trimExplode(':', $tableDef);
4464
        if (empty($tableName) || empty($pid)) {
4465
            throw new \InvalidArgumentException('Unexpected value for parameter $tableDef. Expected <tablename>:<pid>, got \'' . htmlspecialchars($tableDef) . '\'.', 1307190365);
4466
        }
4467
4468
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
4469
            ->getQueryBuilderForTable($tableName);
4470
        $queryBuilder->getRestrictions()
4471
            ->removeByType(StartTimeRestriction::class)
4472
            ->removeByType(EndTimeRestriction::class);
4473
        $timeFields = [];
4474
        $timeConditions = $queryBuilder->expr()->orX();
4475
        foreach (['starttime', 'endtime'] as $field) {
4476
            if (isset($GLOBALS['TCA'][$tableName]['ctrl']['enablecolumns'][$field])) {
4477
                $timeFields[$field] = $GLOBALS['TCA'][$tableName]['ctrl']['enablecolumns'][$field];
4478
                $queryBuilder->addSelectLiteral(
4479
                    'MIN('
4480
                        . 'CASE WHEN '
4481
                        . $queryBuilder->expr()->lte(
4482
                            $timeFields[$field],
4483
                            $queryBuilder->createNamedParameter($now, \PDO::PARAM_INT)
4484
                        )
4485
                        . ' THEN NULL ELSE ' . $queryBuilder->quoteIdentifier($timeFields[$field]) . ' END'
4486
                        . ') AS ' . $queryBuilder->quoteIdentifier($timeFields[$field])
4487
                );
4488
                $timeConditions->add(
4489
                    $queryBuilder->expr()->gt(
4490
                        $timeFields[$field],
4491
                        $queryBuilder->createNamedParameter($now, \PDO::PARAM_INT)
4492
                    )
4493
                );
4494
            }
4495
        }
4496
4497
        // if starttime or endtime are defined, evaluate them
4498
        if (!empty($timeFields)) {
4499
            // find the timestamp, when the current page's content changes the next time
4500
            $row = $queryBuilder
4501
                ->from($tableName)
4502
                ->where(
4503
                    $queryBuilder->expr()->eq(
4504
                        'pid',
4505
                        $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)
4506
                    ),
4507
                    $timeConditions
4508
                )
4509
                ->execute()
4510
                ->fetch();
4511
4512
            if ($row) {
4513
                foreach ($timeFields as $timeField => $_) {
4514
                    // if a MIN value is found, take it into account for the
4515
                    // cache lifetime we have to filter out start/endtimes < $now,
4516
                    // as the SQL query also returns rows with starttime < $now
4517
                    // and endtime > $now (and using a starttime from the past
4518
                    // would be wrong)
4519
                    if ($row[$timeField] !== null && (int)$row[$timeField] > $now) {
4520
                        $result = min($result, (int)$row[$timeField]);
4521
                    }
4522
                }
4523
            }
4524
        }
4525
4526
        return $result;
4527
    }
4528
4529
    /**
4530
     * Fetches/returns the cached contents of the sys_domain database table.
4531
     *
4532
     * @return array Domain data
4533
     */
4534
    protected function getSysDomainCache()
4535
    {
4536
        $entryIdentifier = 'core-database-sys_domain-complete';
4537
        /** @var $runtimeCache \TYPO3\CMS\Core\Cache\Frontend\AbstractFrontend */
4538
        $runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_runtime');
4539
4540
        $sysDomainData = [];
4541
        if ($runtimeCache->has($entryIdentifier)) {
4542
            $sysDomainData = $runtimeCache->get($entryIdentifier);
4543
        } else {
4544
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_domain');
4545
            $queryBuilder->setRestrictions(GeneralUtility::makeInstance(DefaultRestrictionContainer::class));
4546
            $result = $queryBuilder
4547
                ->select('uid', 'pid', 'domainName')
4548
                ->from('sys_domain')
4549
                ->orderBy('sorting', 'ASC')
4550
                ->execute();
4551
4552
            while ($row = $result->fetch()) {
4553
                // If there is already an entry for this pid, we should not override it
4554
                // Except if it is the current domain
4555
                if (isset($sysDomainData[$row['pid']]) && !$this->domainNameMatchesCurrentRequest($row['domainName'])) {
4556
                    continue;
4557
                }
4558
4559
                // as we passed all previous checks, we save this domain for the current pid
4560
                $sysDomainData[$row['pid']] = [
4561
                    'uid' => $row['uid'],
4562
                    'pid' => $row['pid'],
4563
                    'domainName' => rtrim($row['domainName'], '/'),
4564
                ];
4565
            }
4566
            $runtimeCache->set($entryIdentifier, $sysDomainData);
4567
        }
4568
        return $sysDomainData;
4569
    }
4570
4571
    /**
4572
     * Whether the given domain name (potentially including a path segment) matches currently requested host or
4573
     * the host including the path segment
4574
     *
4575
     * @param string $domainName
4576
     * @return bool
4577
     */
4578
    public function domainNameMatchesCurrentRequest($domainName)
4579
    {
4580
        $currentDomain = GeneralUtility::getIndpEnv('HTTP_HOST');
4581
        $currentPathSegment = trim(preg_replace('|/[^/]*$|', '', GeneralUtility::getIndpEnv('SCRIPT_NAME')));
4582
        return $currentDomain === $domainName || $currentDomain . $currentPathSegment === $domainName;
4583
    }
4584
4585
    /**
4586
     * Obtains domain data for the target pid. Domain data is an array with
4587
     * 'pid' and 'domainName' members (see sys_domain table for meaning of these fields).
4588
     *
4589
     * @param int $targetPid Target page id
4590
     * @return mixed Return domain data or NULL
4591
     */
4592
    public function getDomainDataForPid($targetPid)
4593
    {
4594
        // Using array_key_exists() here, nice $result can be NULL
4595
        // (happens, if there's no domain records defined)
4596
        if (!array_key_exists($targetPid, $this->domainDataCache)) {
4597
            $result = null;
4598
            $sysDomainData = $this->getSysDomainCache();
4599
            $rootline = $this->sys_page->getRootLine($targetPid);
4600
            // walk the rootline downwards from the target page
4601
            // to the root page, until a domain record is found
4602
            foreach ($rootline as $pageInRootline) {
4603
                $pidInRootline = $pageInRootline['uid'];
4604
                if (isset($sysDomainData[$pidInRootline])) {
4605
                    $result = $sysDomainData[$pidInRootline];
4606
                    break;
4607
                }
4608
            }
4609
            $this->domainDataCache[$targetPid] = $result;
4610
        }
4611
4612
        return $this->domainDataCache[$targetPid];
4613
    }
4614
4615
    /**
4616
     * Obtains the domain name for the target pid. If there are several domains,
4617
     * the first is returned.
4618
     *
4619
     * @param int $targetPid Target page id
4620
     * @return mixed Return domain name or NULL if not found
4621
     * @deprecated will be removed in TYPO3 v10, as getDomainDataForPid could work
4622
     */
4623
    public function getDomainNameForPid($targetPid)
4624
    {
4625
        trigger_error('This method will be removed in TYPO3 v10, use $TSFE->getDomainDataForPid() instead.', E_USER_DEPRECATED);
4626
        $domainData = $this->getDomainDataForPid($targetPid);
4627
        return $domainData ? $domainData['domainName'] : null;
4628
    }
4629
4630
    /**
4631
     * Fetches the originally requested id, fallsback to $this->id
4632
     *
4633
     * @return int the originally requested page uid
4634
     * @see fetch_the_id()
4635
     */
4636
    public function getRequestedId()
4637
    {
4638
        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...
4639
    }
4640
4641
    /**
4642
     * Acquire a page specific lock
4643
     *
4644
     * @param string $type
4645
     * @param string $key
4646
     * @throws \InvalidArgumentException
4647
     * @throws \RuntimeException
4648
     * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
4649
     */
4650
    protected function acquireLock($type, $key)
4651
    {
4652
        $lockFactory = GeneralUtility::makeInstance(LockFactory::class);
4653
        $this->locks[$type]['accessLock'] = $lockFactory->createLocker($type);
4654
4655
        $this->locks[$type]['pageLock'] = $lockFactory->createLocker(
4656
            $key,
4657
            LockingStrategyInterface::LOCK_CAPABILITY_EXCLUSIVE | LockingStrategyInterface::LOCK_CAPABILITY_NOBLOCK
4658
        );
4659
4660
        do {
4661
            if (!$this->locks[$type]['accessLock']->acquire()) {
4662
                throw new \RuntimeException('Could not acquire access lock for "' . $type . '"".', 1294586098);
4663
            }
4664
4665
            try {
4666
                $locked = $this->locks[$type]['pageLock']->acquire(
4667
                    LockingStrategyInterface::LOCK_CAPABILITY_EXCLUSIVE | LockingStrategyInterface::LOCK_CAPABILITY_NOBLOCK
4668
                );
4669
            } catch (LockAcquireWouldBlockException $e) {
4670
                // somebody else has the lock, we keep waiting
4671
4672
                // first release the access lock
4673
                $this->locks[$type]['accessLock']->release();
4674
                // now lets make a short break (100ms) until we try again, since
4675
                // the page generation by the lock owner will take a while anyways
4676
                usleep(100000);
4677
                continue;
4678
            }
4679
            $this->locks[$type]['accessLock']->release();
4680
            if ($locked) {
4681
                break;
4682
            }
4683
            throw new \RuntimeException('Could not acquire page lock for ' . $key . '.', 1460975877);
4684
        } while (true);
4685
    }
4686
4687
    /**
4688
     * Release a page specific lock
4689
     *
4690
     * @param string $type
4691
     * @throws \InvalidArgumentException
4692
     * @throws \RuntimeException
4693
     * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
4694
     */
4695
    protected function releaseLock($type)
4696
    {
4697
        if ($this->locks[$type]['accessLock']) {
4698
            if (!$this->locks[$type]['accessLock']->acquire()) {
4699
                throw new \RuntimeException('Could not acquire access lock for "' . $type . '"".', 1460975902);
4700
            }
4701
4702
            $this->locks[$type]['pageLock']->release();
4703
            $this->locks[$type]['pageLock']->destroy();
4704
            $this->locks[$type]['pageLock'] = null;
4705
4706
            $this->locks[$type]['accessLock']->release();
4707
            $this->locks[$type]['accessLock'] = null;
4708
        }
4709
    }
4710
4711
    /**
4712
     * Send additional headers from config.additionalHeaders
4713
     *
4714
     * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::processOutput()
4715
     */
4716
    protected function sendAdditionalHeaders()
4717
    {
4718
        if (!isset($this->config['config']['additionalHeaders.'])) {
4719
            return;
4720
        }
4721
        ksort($this->config['config']['additionalHeaders.']);
4722
        foreach ($this->config['config']['additionalHeaders.'] as $options) {
4723
            if (!is_array($options)) {
4724
                continue;
4725
            }
4726
            $header = $options['header'] ?? '';
4727
            $header = isset($options['header.'])
4728
                ? $this->cObj->stdWrap(trim($header), $options['header.'])
4729
                : trim($header);
4730
            if ($header === '') {
4731
                continue;
4732
            }
4733
            $replace = $options['replace'] ?? '';
4734
            $replace = isset($options['replace.'])
4735
                ? $this->cObj->stdWrap($replace, $options['replace.'])
4736
                : $replace;
4737
            $httpResponseCode = $options['httpResponseCode'] ?? '';
4738
            $httpResponseCode = isset($options['httpResponseCode.'])
4739
                ? $this->cObj->stdWrap($httpResponseCode, $options['httpResponseCode.'])
4740
                : $httpResponseCode;
4741
            $httpResponseCode = (int)$httpResponseCode;
4742
4743
            header(
4744
                $header,
4745
                // "replace existing headers" is turned on by default, unless turned off
4746
                $replace !== '0',
4747
                $httpResponseCode ?: null
4748
            );
4749
        }
4750
    }
4751
4752
    /**
4753
     * Helper method to kill the request. Exits.
4754
     * Should not be used from the outside, rather return the response object
4755
     * Ideally, this method will be dropped by TYPO3 v9 LTS.
4756
     *
4757
     * @param ResponseInterface $response
4758
     */
4759
    protected function sendResponseAndExit(ResponseInterface $response)
4760
    {
4761
        // If the response code was not changed by legacy code (still is 200)
4762
        // then allow the PSR-7 response object to explicitly set it.
4763
        // Otherwise let legacy code take precedence.
4764
        // This code path can be deprecated once we expose the response object to third party code
4765
        if (http_response_code() === 200) {
4766
            header('HTTP/' . $response->getProtocolVersion() . ' ' . $response->getStatusCode() . ' ' . $response->getReasonPhrase());
4767
        }
4768
4769
        foreach ($response->getHeaders() as $name => $values) {
4770
            header($name . ': ' . implode(', ', $values));
4771
        }
4772
        echo $response->getBody()->__toString();
4773
        die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
4774
    }
4775
4776
    /**
4777
     * Returns the current BE user.
4778
     *
4779
     * @return \TYPO3\CMS\Backend\FrontendBackendUserAuthentication
4780
     */
4781
    protected function getBackendUser()
4782
    {
4783
        return $GLOBALS['BE_USER'];
4784
    }
4785
4786
    /**
4787
     * @return TimeTracker
4788
     */
4789
    protected function getTimeTracker()
4790
    {
4791
        return GeneralUtility::makeInstance(TimeTracker::class);
4792
    }
4793
4794
    /**
4795
     * Returns the currently configured "site language" if a site is configured (= resolved) in the current request.
4796
     *
4797
     * @internal
4798
     */
4799
    protected function getCurrentSiteLanguage(): ?SiteLanguage
4800
    {
4801
        if ($GLOBALS['TYPO3_REQUEST'] instanceof ServerRequestInterface
4802
            && $GLOBALS['TYPO3_REQUEST']->getAttribute('language') instanceof SiteLanguage) {
4803
            return $GLOBALS['TYPO3_REQUEST']->getAttribute('language');
4804
        }
4805
        return null;
4806
    }
4807
}
4808