Test Failed
Branch master (137376)
by Tymoteusz
20:39
created

TypoScriptFrontendController::determineId()   F

Complexity

Conditions 31
Paths 10032

Size

Total Lines 110
Code Lines 63

Duplication

Lines 4
Ratio 3.64 %

Importance

Changes 0
Metric Value
cc 31
eloc 63
nc 10032
nop 0
dl 4
loc 110
rs 2
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Exception\ConnectionException;
18
use Psr\Log\LoggerAwareInterface;
19
use Psr\Log\LoggerAwareTrait;
20
use TYPO3\CMS\Backend\FrontendBackendUserAuthentication;
21
use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
22
use TYPO3\CMS\Core\Cache\CacheManager;
23
use TYPO3\CMS\Core\Charset\CharsetConverter;
24
use TYPO3\CMS\Core\Charset\UnknownCharsetException;
25
use TYPO3\CMS\Core\Controller\ErrorPageController;
26
use TYPO3\CMS\Core\Database\ConnectionPool;
27
use TYPO3\CMS\Core\Database\Query\QueryHelper;
28
use TYPO3\CMS\Core\Database\Query\Restriction\DefaultRestrictionContainer;
29
use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
30
use TYPO3\CMS\Core\Database\Query\Restriction\EndTimeRestriction;
31
use TYPO3\CMS\Core\Database\Query\Restriction\StartTimeRestriction;
32
use TYPO3\CMS\Core\Error\Http\PageNotFoundException;
33
use TYPO3\CMS\Core\Error\Http\ServiceUnavailableException;
34
use TYPO3\CMS\Core\Localization\LanguageService;
35
use TYPO3\CMS\Core\Locking\Exception\LockAcquireWouldBlockException;
36
use TYPO3\CMS\Core\Locking\LockFactory;
37
use TYPO3\CMS\Core\Locking\LockingStrategyInterface;
38
use TYPO3\CMS\Core\Log\LogManager;
39
use TYPO3\CMS\Core\Page\PageRenderer;
40
use TYPO3\CMS\Core\Resource\StorageRepository;
41
use TYPO3\CMS\Core\Service\DependencyOrderingService;
42
use TYPO3\CMS\Core\TimeTracker\TimeTracker;
43
use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
44
use TYPO3\CMS\Core\TypoScript\TemplateService;
45
use TYPO3\CMS\Core\Utility\ArrayUtility;
46
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
47
use TYPO3\CMS\Core\Utility\GeneralUtility;
48
use TYPO3\CMS\Core\Utility\HttpUtility;
49
use TYPO3\CMS\Core\Utility\MathUtility;
50
use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
51
use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
52
use TYPO3\CMS\Frontend\Http\UrlHandlerInterface;
53
use TYPO3\CMS\Frontend\Page\CacheHashCalculator;
54
use TYPO3\CMS\Frontend\Page\PageGenerator;
55
use TYPO3\CMS\Frontend\Page\PageRepository;
56
use TYPO3\CMS\Frontend\View\AdminPanelView;
57
58
/**
59
 * Class for the built TypoScript based frontend. Instantiated in
60
 * \TYPO3\CMS\Frontend\Http\RequestHandler as the global object TSFE.
61
 *
62
 * Main frontend class, instantiated in \TYPO3\CMS\Frontend\Http\RequestHandler
63
 * as the global object TSFE.
64
 *
65
 * This class has a lot of functions and internal variable which are used from
66
 * \TYPO3\CMS\Frontend\Http\RequestHandler
67
 *
68
 * The class is instantiated as $GLOBALS['TSFE'] in \TYPO3\CMS\Frontend\Http\RequestHandler.
69
 *
70
 * The use of this class should be inspired by the order of function calls as
71
 * found in \TYPO3\CMS\Frontend\Http\RequestHandler.
72
 */
73
class TypoScriptFrontendController implements LoggerAwareInterface
74
{
75
    use LoggerAwareTrait;
76
77
    /**
78
     * The page id (int)
79
     * @var string
80
     */
81
    public $id = '';
82
83
    /**
84
     * The type (read-only)
85
     * @var int
86
     */
87
    public $type = '';
88
89
    /**
90
     * The submitted cHash
91
     * @var string
92
     */
93
    public $cHash = '';
94
95
    /**
96
     * Page will not be cached. Write only TRUE. Never clear value (some other
97
     * code might have reasons to set it TRUE).
98
     * @var bool
99
     */
100
    public $no_cache = false;
101
102
    /**
103
     * The rootLine (all the way to tree root, not only the current site!)
104
     * @var array
105
     */
106
    public $rootLine = '';
107
108
    /**
109
     * The pagerecord
110
     * @var array
111
     */
112
    public $page = '';
113
114
    /**
115
     * This will normally point to the same value as id, but can be changed to
116
     * point to another page from which content will then be displayed instead.
117
     * @var int
118
     */
119
    public $contentPid = 0;
120
121
    /**
122
     * Gets set when we are processing a page of type mounpoint with enabled overlay in getPageAndRootline()
123
     * Used later in checkPageForMountpointRedirect() to determine the final target URL where the user
124
     * should be redirected to.
125
     *
126
     * @var array|null
127
     */
128
    protected $originalMountPointPage = null;
129
130
    /**
131
     * Gets set when we are processing a page of type shortcut in the early stages
132
     * of the request when we do not know about languages yet, used later in the request
133
     * to determine the correct shortcut in case a translation changes the shortcut
134
     * target
135
     * @var array|null
136
     * @see checkTranslatedShortcut()
137
     */
138
    protected $originalShortcutPage = null;
139
140
    /**
141
     * sys_page-object, pagefunctions
142
     *
143
     * @var PageRepository
144
     */
145
    public $sys_page = '';
146
147
    /**
148
     * Contains all URL handler instances that are active for the current request.
149
     *
150
     * The methods isGeneratePage(), isOutputting() and isINTincScript() depend on this property.
151
     *
152
     * @var \TYPO3\CMS\Frontend\Http\UrlHandlerInterface[]
153
     * @see initializeRedirectUrlHandlers()
154
     */
155
    protected $activeUrlHandlers = [];
156
157
    /**
158
     * Is set to 1 if a pageNotFound handler could have been called.
159
     * @var int
160
     */
161
    public $pageNotFound = 0;
162
163
    /**
164
     * Domain start page
165
     * @var int
166
     */
167
    public $domainStartPage = 0;
168
169
    /**
170
     * Array containing a history of why a requested page was not accessible.
171
     * @var array
172
     */
173
    public $pageAccessFailureHistory = [];
174
175
    /**
176
     * @var string
177
     */
178
    public $MP = '';
179
180
    /**
181
     * This can be set from applications as a way to tag cached versions of a page
182
     * and later perform some external cache management, like clearing only a part
183
     * of the cache of a page...
184
     * @var int
185
     */
186
    public $page_cache_reg1 = 0;
187
188
    /**
189
     * Contains the value of the current script path that activated the frontend.
190
     * Typically "index.php" but by rewrite rules it could be something else! Used
191
     * for Speaking Urls / Simulate Static Documents.
192
     * @var string
193
     */
194
    public $siteScript = '';
195
196
    /**
197
     * The frontend user
198
     *
199
     * @var FrontendUserAuthentication
200
     */
201
    public $fe_user = '';
202
203
    /**
204
     * Global flag indicating that a frontend user is logged in. This is set only if
205
     * a user really IS logged in. The group-list may show other groups (like added
206
     * by IP filter or so) even though there is no user.
207
     * @var bool
208
     */
209
    public $loginUser = false;
210
211
    /**
212
     * (RO=readonly) The group list, sorted numerically. Group '0,-1' is the default
213
     * group, but other groups may be added by other means than a user being logged
214
     * in though...
215
     * @var string
216
     */
217
    public $gr_list = '';
218
219
    /**
220
     * Flag that indicates if a backend user is logged in!
221
     * @var bool
222
     */
223
    public $beUserLogin = false;
224
225
    /**
226
     * Integer, that indicates which workspace is being previewed.
227
     * @var int
228
     */
229
    public $workspacePreview = 0;
230
231
    /**
232
     * Shows whether logins are allowed in branch
233
     * @var bool
234
     */
235
    public $loginAllowedInBranch = true;
236
237
    /**
238
     * Shows specific mode (all or groups)
239
     * @var string
240
     */
241
    public $loginAllowedInBranch_mode = '';
242
243
    /**
244
     * Set to backend user ID to initialize when keyword-based preview is used
245
     * @var int
246
     */
247
    public $ADMCMD_preview_BEUSER_uid = 0;
248
249
    /**
250
     * Flag indication that preview is active. This is based on the login of a
251
     * backend user and whether the backend user has read access to the current
252
     * page. A value of 1 means ordinary preview, 2 means preview of a non-live
253
     * workspace
254
     * @var int
255
     */
256
    public $fePreview = 0;
257
258
    /**
259
     * Flag indicating that hidden pages should be shown, selected and so on. This
260
     * goes for almost all selection of pages!
261
     * @var bool
262
     */
263
    public $showHiddenPage = false;
264
265
    /**
266
     * Flag indicating that hidden records should be shown. This includes
267
     * sys_template and even fe_groups in addition to all
268
     * other regular content. So in effect, this includes everything except pages.
269
     * @var bool
270
     */
271
    public $showHiddenRecords = false;
272
273
    /**
274
     * Value that contains the simulated usergroup if any
275
     * @var int
276
     */
277
    public $simUserGroup = 0;
278
279
    /**
280
     * "CONFIG" object from TypoScript. Array generated based on the TypoScript
281
     * configuration of the current page. Saved with the cached pages.
282
     * @var array
283
     */
284
    public $config = [];
285
286
    /**
287
     * The TypoScript template object. Used to parse the TypoScript template
288
     *
289
     * @var TemplateService
290
     */
291
    public $tmpl = null;
292
293
    /**
294
     * Is set to the time-to-live time of cached pages. If FALSE, default is
295
     * 60*60*24, which is 24 hours.
296
     * @var bool|int
297
     */
298
    public $cacheTimeOutDefault = false;
299
300
    /**
301
     * Set internally if cached content is fetched from the database
302
     * @var bool
303
     * @internal
304
     */
305
    public $cacheContentFlag = false;
306
307
    /**
308
     * Set to the expire time of cached content
309
     * @var int
310
     */
311
    public $cacheExpires = 0;
312
313
    /**
314
     * Set if cache headers allowing caching are sent.
315
     * @var bool
316
     */
317
    public $isClientCachable = false;
318
319
    /**
320
     * Used by template fetching system. This array is an identification of
321
     * the template. If $this->all is empty it's because the template-data is not
322
     * cached, which it must be.
323
     * @var array
324
     */
325
    public $all = [];
326
327
    /**
328
     * Toplevel - objArrayName, eg 'page'
329
     * @var string
330
     */
331
    public $sPre = '';
332
333
    /**
334
     * TypoScript configuration of the page-object pointed to by sPre.
335
     * $this->tmpl->setup[$this->sPre.'.']
336
     * @var array
337
     */
338
    public $pSetup = '';
339
340
    /**
341
     * This hash is unique to the template, the $this->id and $this->type vars and
342
     * the gr_list (list of groups). Used to get and later store the cached data
343
     * @var string
344
     */
345
    public $newHash = '';
346
347
    /**
348
     * If config.ftu (Frontend Track User) is set in TypoScript for the current
349
     * page, the string value of this var is substituted in the rendered source-code
350
     * with the string, '&ftu=[token...]' which enables GET-method usertracking as
351
     * opposed to cookie based
352
     * @var string
353
     */
354
    public $getMethodUrlIdToken = '';
355
356
    /**
357
     * This flag is set before inclusion of pagegen.php IF no_cache is set. If this
358
     * flag is set after the inclusion of pagegen.php, no_cache is forced to be set.
359
     * This is done in order to make sure that php-code from pagegen does not falsely
360
     * clear the no_cache flag.
361
     * @var bool
362
     */
363
    public $no_cacheBeforePageGen = false;
364
365
    /**
366
     * This flag indicates if temporary content went into the cache during
367
     * page-generation.
368
     * @var mixed
369
     */
370
    public $tempContent = false;
371
372
    /**
373
     * Passed to TypoScript template class and tells it to force template rendering
374
     * @var bool
375
     */
376
    public $forceTemplateParsing = false;
377
378
    /**
379
     * The array which cHash_calc is based on, see ->makeCacheHash().
380
     * @var array
381
     */
382
    public $cHash_array = [];
383
384
    /**
385
     * May be set to the pagesTSconfig
386
     * @var array
387
     */
388
    public $pagesTSconfig = '';
389
390
    /**
391
     * Eg. insert JS-functions in this array ($additionalHeaderData) to include them
392
     * once. Use associative keys.
393
     *
394
     * Keys in use:
395
     *
396
     * used to accumulate additional HTML-code for the header-section,
397
     * <head>...</head>. Insert either associative keys (like
398
     * additionalHeaderData['myStyleSheet'], see reserved keys above) or num-keys
399
     * (like additionalHeaderData[] = '...')
400
     *
401
     * @var array
402
     */
403
    public $additionalHeaderData = [];
404
405
    /**
406
     * Used to accumulate additional HTML-code for the footer-section of the template
407
     * @var array
408
     */
409
    public $additionalFooterData = [];
410
411
    /**
412
     * Used to accumulate additional JavaScript-code. Works like
413
     * additionalHeaderData. Reserved keys at 'openPic' and 'mouseOver'
414
     *
415
     * @var array
416
     */
417
    public $additionalJavaScript = [];
418
419
    /**
420
     * Used to accumulate additional Style code. Works like additionalHeaderData.
421
     *
422
     * @var array
423
     */
424
    public $additionalCSS = [];
425
426
    /**
427
     * @var  string
428
     */
429
    public $JSCode;
430
431
    /**
432
     * @var string
433
     */
434
    public $inlineJS;
435
436
    /**
437
     * Used to accumulate DHTML-layers.
438
     * @var string
439
     */
440
    public $divSection = '';
441
442
    /**
443
     * Debug flag. If TRUE special debug-output maybe be shown (which includes html-formatting).
444
     * @var bool
445
     */
446
    public $debug = false;
447
448
    /**
449
     * Default internal target
450
     * @var string
451
     */
452
    public $intTarget = '';
453
454
    /**
455
     * Default external target
456
     * @var string
457
     */
458
    public $extTarget = '';
459
460
    /**
461
     * Default file link target
462
     * @var string
463
     */
464
    public $fileTarget = '';
465
466
    /**
467
     * Keys are page ids and values are default &MP (mount point) values to set
468
     * when using the linking features...)
469
     * @var array
470
     */
471
    public $MP_defaults = [];
472
473
    /**
474
     * If set, typolink() function encrypts email addresses. Is set in pagegen-class.
475
     * @var string|int
476
     */
477
    public $spamProtectEmailAddresses = 0;
478
479
    /**
480
     * Absolute Reference prefix
481
     * @var string
482
     */
483
    public $absRefPrefix = '';
484
485
    /**
486
     * Lock file path
487
     * @var string
488
     */
489
    public $lockFilePath = '';
490
491
    /**
492
     * <A>-tag parameters
493
     * @var string
494
     */
495
    public $ATagParams = '';
496
497
    /**
498
     * Search word regex, calculated if there has been search-words send. This is
499
     * used to mark up the found search words on a page when jumped to from a link
500
     * in a search-result.
501
     * @var string
502
     */
503
    public $sWordRegEx = '';
504
505
    /**
506
     * Is set to the incoming array sword_list in case of a page-view jumped to from
507
     * a search-result.
508
     * @var string
509
     */
510
    public $sWordList = '';
511
512
    /**
513
     * A string prepared for insertion in all links on the page as url-parameters.
514
     * Based on configuration in TypoScript where you defined which GET_VARS you
515
     * would like to pass on.
516
     * @var string
517
     */
518
    public $linkVars = '';
519
520
    /**
521
     * If set, edit icons are rendered aside content records. Must be set only if
522
     * the ->beUserLogin flag is set and set_no_cache() must be called as well.
523
     * @var string
524
     */
525
    public $displayEditIcons = '';
526
527
    /**
528
     * If set, edit icons are rendered aside individual fields of content. Must be
529
     * set only if the ->beUserLogin flag is set and set_no_cache() must be called as
530
     * well.
531
     * @var string
532
     */
533
    public $displayFieldEditIcons = '';
534
535
    /**
536
     * Site language, 0 (zero) is default, int+ is uid pointing to a sys_language
537
     * record. Should reflect which language menus, templates etc is displayed in
538
     * (master language) - but not necessarily the content which could be falling
539
     * back to default (see sys_language_content)
540
     * @var int
541
     */
542
    public $sys_language_uid = 0;
543
544
    /**
545
     * Site language mode for content fall back.
546
     * @var string
547
     */
548
    public $sys_language_mode = '';
549
550
    /**
551
     * Site content selection uid (can be different from sys_language_uid if content
552
     * is to be selected from a fall-back language. Depends on sys_language_mode)
553
     * @var int
554
     */
555
    public $sys_language_content = 0;
556
557
    /**
558
     * Site content overlay flag; If set - and sys_language_content is > 0 - ,
559
     * records selected will try to look for a translation pointing to their uid. (If
560
     * configured in [ctrl][languageField] / [ctrl][transOrigP...]
561
     * Possible values: [0,1,hideNonTranslated]
562
     * This flag is set based on TypoScript config.sys_language_overlay setting
563
     *
564
     * @var int|string
565
     */
566
    public $sys_language_contentOL = 0;
567
568
    /**
569
     * Is set to the iso code of the sys_language_content if that is properly defined
570
     * by the sys_language record representing the sys_language_uid.
571
     * @var string
572
     */
573
    public $sys_language_isocode = '';
574
575
    /**
576
     * 'Global' Storage for various applications. Keys should be 'tx_'.extKey for
577
     * extensions.
578
     * @var array
579
     */
580
    public $applicationData = [];
581
582
    /**
583
     * @var array
584
     */
585
    public $register = [];
586
587
    /**
588
     * Stack used for storing array and retrieving register arrays (see
589
     * LOAD_REGISTER and RESTORE_REGISTER)
590
     * @var array
591
     */
592
    public $registerStack = [];
593
594
    /**
595
     * Checking that the function is not called eternally. This is done by
596
     * interrupting at a depth of 50
597
     * @var int
598
     */
599
    public $cObjectDepthCounter = 50;
600
601
    /**
602
     * Used by RecordContentObject and ContentContentObject to ensure the a records is NOT
603
     * rendered twice through it!
604
     * @var array
605
     */
606
    public $recordRegister = [];
607
608
    /**
609
     * This is set to the [table]:[uid] of the latest record rendered. Note that
610
     * class ContentObjectRenderer has an equal value, but that is pointing to the
611
     * record delivered in the $data-array of the ContentObjectRenderer instance, if
612
     * the cObjects CONTENT or RECORD created that instance
613
     * @var string
614
     */
615
    public $currentRecord = '';
616
617
    /**
618
     * Used by class \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject
619
     * to keep track of access-keys.
620
     * @var array
621
     */
622
    public $accessKey = [];
623
624
    /**
625
     * Numerical array where image filenames are added if they are referenced in the
626
     * rendered document. This includes only TYPO3 generated/inserted images.
627
     * @var array
628
     */
629
    public $imagesOnPage = [];
630
631
    /**
632
     * Is set in ContentObjectRenderer->cImage() function to the info-array of the
633
     * most recent rendered image. The information is used in ImageTextContentObject
634
     * @var array
635
     */
636
    public $lastImageInfo = [];
637
638
    /**
639
     * Used to generate page-unique keys. Point is that uniqid() functions is very
640
     * slow, so a unikey key is made based on this, see function uniqueHash()
641
     * @var int
642
     */
643
    public $uniqueCounter = 0;
644
645
    /**
646
     * @var string
647
     */
648
    public $uniqueString = '';
649
650
    /**
651
     * This value will be used as the title for the page in the indexer (if
652
     * indexing happens)
653
     * @var string
654
     */
655
    public $indexedDocTitle = '';
656
657
    /**
658
     * Alternative page title (normally the title of the page record). Can be set
659
     * from applications you make.
660
     * @var string
661
     */
662
    public $altPageTitle = '';
663
664
    /**
665
     * The base URL set for the page header.
666
     * @var string
667
     */
668
    public $baseUrl = '';
669
670
    /**
671
     * IDs we already rendered for this page (to make sure they are unique)
672
     * @var array
673
     */
674
    private $usedUniqueIds = [];
675
676
    /**
677
     * Page content render object
678
     *
679
     * @var ContentObjectRenderer
680
     */
681
    public $cObj = '';
682
683
    /**
684
     * All page content is accumulated in this variable. See pagegen.php
685
     * @var string
686
     */
687
    public $content = '';
688
689
    /**
690
     * Output charset of the websites content. This is the charset found in the
691
     * header, meta tag etc. If different than utf-8 a conversion
692
     * happens before output to browser. Defaults to utf-8.
693
     * @var string
694
     */
695
    public $metaCharset = 'utf-8';
696
697
    /**
698
     * Set to the system language key (used on the site)
699
     * @var string
700
     */
701
    public $lang = '';
702
703
    /**
704
     * Internal calculations for labels
705
     *
706
     * @var LanguageService
707
     */
708
    protected $languageService;
709
710
    /**
711
     * @var LockingStrategyInterface[][]
712
     */
713
    protected $locks = [];
714
715
    /**
716
     * @var PageRenderer
717
     */
718
    protected $pageRenderer = null;
719
720
    /**
721
     * The page cache object, use this to save pages to the cache and to
722
     * retrieve them again
723
     *
724
     * @var \TYPO3\CMS\Core\Cache\Backend\AbstractBackend
725
     */
726
    protected $pageCache;
727
728
    /**
729
     * @var array
730
     */
731
    protected $pageCacheTags = [];
732
733
    /**
734
     * The cHash Service class used for cHash related functionality
735
     *
736
     * @var CacheHashCalculator
737
     */
738
    protected $cacheHash;
739
740
    /**
741
     * Runtime cache of domains per processed page ids.
742
     *
743
     * @var array
744
     */
745
    protected $domainDataCache = [];
746
747
    /**
748
     * Content type HTTP header being sent in the request.
749
     * @todo Ticket: #63642 Should be refactored to a request/response model later
750
     * @internal Should only be used by TYPO3 core for now
751
     *
752
     * @var string
753
     */
754
    protected $contentType = 'text/html';
755
756
    /**
757
     * Doctype to use
758
     *
759
     * @var string
760
     */
761
    public $xhtmlDoctype = '';
762
763
    /**
764
     * @var int
765
     */
766
    public $xhtmlVersion;
767
768
    /**
769
     * Originally requested id from the initial $_GET variable
770
     *
771
     * @var int
772
     */
773
    protected $requestedId;
774
775
    /**
776
     * Class constructor
777
     * Takes a number of GET/POST input variable as arguments and stores them internally.
778
     * The processing of these variables goes on later in this class.
779
     * Also sets a unique string (->uniqueString) for this script instance; A md5 hash of the microtime()
780
     *
781
     * @param array $_ unused, previously defined to set TYPO3_CONF_VARS
782
     * @param mixed $id The value of GeneralUtility::_GP('id')
783
     * @param int $type The value of GeneralUtility::_GP('type')
784
     * @param bool|string $no_cache The value of GeneralUtility::_GP('no_cache'), evaluated to 1/0
785
     * @param string $cHash The value of GeneralUtility::_GP('cHash')
786
     * @param string $_2 previously was used to define the jumpURL
787
     * @param string $MP The value of GeneralUtility::_GP('MP')
788
     * @see \TYPO3\CMS\Frontend\Http\RequestHandler
789
     */
790
    public function __construct($_ = null, $id, $type, $no_cache = '', $cHash = '', $_2 = null, $MP = '')
791
    {
792
        // Setting some variables:
793
        $this->id = $id;
794
        $this->type = $type;
795
        if ($no_cache) {
796
            if ($GLOBALS['TYPO3_CONF_VARS']['FE']['disableNoCacheParameter']) {
797
                $warning = '&no_cache=1 has been ignored because $TYPO3_CONF_VARS[\'FE\'][\'disableNoCacheParameter\'] is set!';
798
                $this->getTimeTracker()->setTSlogMessage($warning, 2);
799
            } else {
800
                $warning = '&no_cache=1 has been supplied, so caching is disabled! URL: "' . GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL') . '"';
801
                $this->disableCache();
802
            }
803
            // note: we need to instantiate the logger manually here since the injection happens after the constructor
804
            GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__)->warning($warning);
805
        }
806
        $this->cHash = $cHash;
807
        $this->MP = $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] ? (string)$MP : '';
808
        $this->uniqueString = md5(microtime());
809
        $this->initPageRenderer();
810
        // Call post processing function for constructor:
811
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-PostProc'] ?? [] as $_funcRef) {
812
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
813
        }
814
        $this->cacheHash = GeneralUtility::makeInstance(CacheHashCalculator::class);
815
        $this->initCaches();
816
    }
817
818
    /**
819
     * Initializes the page renderer object
820
     */
821 View Code Duplication
    protected function initPageRenderer()
822
    {
823
        if ($this->pageRenderer !== null) {
824
            return;
825
        }
826
        $this->pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
827
        $this->pageRenderer->setTemplateFile('EXT:frontend/Resources/Private/Templates/MainPage.html');
828
    }
829
830
    /**
831
     * @param string $contentType
832
     * @internal Should only be used by TYPO3 core for now
833
     */
834
    public function setContentType($contentType)
835
    {
836
        $this->contentType = $contentType;
837
    }
838
839
    /**
840
     * Connect to SQL database. May exit after outputting an error message
841
     * or some JavaScript redirecting to the install tool.
842
     *
843
     * @throws \RuntimeException
844
     * @throws ServiceUnavailableException
845
     */
846
    public function connectToDB()
847
    {
848
        $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('pages');
849
        try {
850
            $connection->connect();
851
        } catch (ConnectionException $exception) {
852
            // Cannot connect to current database
853
            $message = 'Cannot connect to the configured database "' . $connection->getDatabase() . '"';
854
            if ($this->checkPageUnavailableHandler()) {
855
                $this->pageUnavailableAndExit($message);
856
            } else {
857
                $this->logger->emergency($message, ['exception' => $exception]);
858
                throw new ServiceUnavailableException($message, 1301648782);
859
            }
860
        }
861
        // Call post processing function for DB connection:
862
        $_params = ['pObj' => &$this];
863
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['connectToDB'] ?? [] as $_funcRef) {
864
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
865
        }
866
    }
867
868
    /********************************************
869
     *
870
     * Initializing, resolving page id
871
     *
872
     ********************************************/
873
    /**
874
     * Initializes the caching system.
875
     */
876
    protected function initCaches()
877
    {
878
        $this->pageCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_pages');
879
    }
880
881
    /**
882
     * Initializes the front-end login user.
883
     */
884
    public function initFEuser()
885
    {
886
        $this->fe_user = GeneralUtility::makeInstance(FrontendUserAuthentication::class);
887
        // List of pid's acceptable
888
        $pid = GeneralUtility::_GP('pid');
889
        $this->fe_user->checkPid_value = $pid ? implode(',', GeneralUtility::intExplode(',', $pid)) : 0;
890
        // Check if a session is transferred:
891
        if (GeneralUtility::_GP('FE_SESSION_KEY')) {
0 ignored issues
show
Bug Best Practice introduced by
The expression TYPO3\CMS\Core\Utility\G...::_GP('FE_SESSION_KEY') of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
892
            $fe_sParts = explode('-', GeneralUtility::_GP('FE_SESSION_KEY'));
893
            // If the session key hash check is OK:
894
            if (md5(($fe_sParts[0] . '/' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'])) === (string)$fe_sParts[1]) {
895
                $cookieName = FrontendUserAuthentication::getCookieName();
896
                $_COOKIE[$cookieName] = $fe_sParts[0];
897
                if (isset($_SERVER['HTTP_COOKIE'])) {
898
                    // See http://forge.typo3.org/issues/27740
899
                    $_SERVER['HTTP_COOKIE'] .= ';' . $cookieName . '=' . $fe_sParts[0];
900
                }
901
                $this->fe_user->forceSetCookie = 1;
902
                $this->fe_user->dontSetCookie = false;
903
                unset($cookieName);
904
            }
905
        }
906
        $this->fe_user->start();
907
        $this->fe_user->unpack_uc();
908
909
        // Call hook for possible manipulation of frontend user object
910
        $_params = ['pObj' => &$this];
911
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['initFEuser'] ?? [] as $_funcRef) {
912
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
913
        }
914
    }
915
916
    /**
917
     * Initializes the front-end user groups.
918
     * Sets ->loginUser and ->gr_list based on front-end user status.
919
     */
920
    public function initUserGroups()
921
    {
922
        // This affects the hidden-flag selecting the fe_groups for the user!
923
        $this->fe_user->showHiddenRecords = $this->showHiddenRecords;
924
        // no matter if we have an active user we try to fetch matching groups which can be set without an user (simulation for instance!)
925
        $this->fe_user->fetchGroupData();
926
        if (is_array($this->fe_user->user) && !empty($this->fe_user->groupData['uid'])) {
927
            // global flag!
928
            $this->loginUser = true;
929
            // 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!
930
            $this->gr_list = '0,-2';
931
            $gr_array = $this->fe_user->groupData['uid'];
932
        } else {
933
            $this->loginUser = false;
934
            // 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!
935
            $this->gr_list = '0,-1';
936
            if ($this->loginAllowedInBranch) {
937
                // 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.
938
                $gr_array = $this->fe_user->groupData['uid'];
939
            } else {
940
                // Set to blank since we will NOT risk any groups being set when no logins are allowed!
941
                $gr_array = [];
942
            }
943
        }
944
        // Clean up.
945
        // Make unique...
946
        $gr_array = array_unique($gr_array);
947
        // sort
948
        sort($gr_array);
949
        if (!empty($gr_array) && !$this->loginAllowedInBranch_mode) {
950
            $this->gr_list .= ',' . implode(',', $gr_array);
951
        }
952
953
        // For every 60 seconds the is_online timestamp for a logged-in user is updated
954
        if ($this->loginUser) {
955
            $this->fe_user->updateOnlineTimestamp();
956
        }
957
958
        $this->logger->debug('Valid usergroups for TSFE: ' . $this->gr_list);
959
    }
960
961
    /**
962
     * Checking if a user is logged in or a group constellation different from "0,-1"
963
     *
964
     * @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!)
965
     */
966
    public function isUserOrGroupSet()
967
    {
968
        return is_array($this->fe_user->user) || $this->gr_list !== '0,-1';
969
    }
970
971
    /**
972
     * Provides ways to bypass the '?id=[xxx]&type=[xx]' format, using either PATH_INFO or virtual HTML-documents (using Apache mod_rewrite)
973
     *
974
     * Two options:
975
     * 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)
976
     * 2) Using hook which enables features like those provided from "realurl" extension (AKA "Speaking URLs")
977
     */
978
    public function checkAlternativeIdMethods()
979
    {
980
        $this->siteScript = GeneralUtility::getIndpEnv('TYPO3_SITE_SCRIPT');
981
        // Call post processing function for custom URL methods.
982
        $_params = ['pObj' => &$this];
983
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc'] ?? [] as $_funcRef) {
984
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
985
        }
986
    }
987
988
    /**
989
     * Clears the preview-flags, sets sim_exec_time to current time.
990
     * Hidden pages must be hidden as default, $GLOBALS['SIM_EXEC_TIME'] is set to $GLOBALS['EXEC_TIME']
991
     * in bootstrap initializeGlobalTimeVariables(). Alter it by adding or subtracting seconds.
992
     */
993
    public function clear_preview()
994
    {
995
        $this->showHiddenPage = false;
996
        $this->showHiddenRecords = false;
997
        $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
998
        $GLOBALS['SIM_ACCESS_TIME'] = $GLOBALS['ACCESS_TIME'];
999
        $this->fePreview = 0;
1000
    }
1001
1002
    /**
1003
     * Checks if a backend user is logged in
1004
     *
1005
     * @return bool whether a backend user is logged in
1006
     */
1007
    public function isBackendUserLoggedIn()
1008
    {
1009
        return (bool)$this->beUserLogin;
1010
    }
1011
1012
    /**
1013
     * Creates the backend user object and returns it.
1014
     *
1015
     * @return FrontendBackendUserAuthentication the backend user object
1016
     */
1017
    public function initializeBackendUser()
1018
    {
1019
        // PRE BE_USER HOOK
1020
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['preBeUser'] ?? [] as $_funcRef) {
1021
            $_params = [];
1022
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1023
        }
1024
        $backendUserObject = null;
1025
        // If the backend cookie is set,
1026
        // we proceed and check if a backend user is logged in.
1027
        if ($_COOKIE[BackendUserAuthentication::getCookieName()]) {
1028
            $GLOBALS['TYPO3_MISC']['microtime_BE_USER_start'] = microtime(true);
1029
            $this->getTimeTracker()->push('Back End user initialized', '');
1030
            $this->beUserLogin = false;
1031
            // New backend user object
1032
            $backendUserObject = GeneralUtility::makeInstance(FrontendBackendUserAuthentication::class);
1033
            $backendUserObject->start();
1034
            $backendUserObject->unpack_uc();
1035
            if (!empty($backendUserObject->user['uid'])) {
1036
                $backendUserObject->fetchGroupData();
1037
            }
1038
            // Unset the user initialization if any setting / restriction applies
1039
            if (!$backendUserObject->checkBackendAccessSettingsFromInitPhp()) {
1040
                $backendUserObject = null;
1041
            } elseif (!empty($backendUserObject->user['uid'])) {
1042
                // If the user is active now, let the controller know
1043
                $this->beUserLogin = true;
1044
            } else {
1045
                $backendUserObject = null;
1046
            }
1047
            $this->getTimeTracker()->pull();
1048
            $GLOBALS['TYPO3_MISC']['microtime_BE_USER_end'] = microtime(true);
1049
        }
1050
        // POST BE_USER HOOK
1051
        $_params = [
1052
            'BE_USER' => &$backendUserObject
1053
        ];
1054
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['postBeUser'] ?? [] as $_funcRef) {
1055
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1056
        }
1057
        return $backendUserObject;
1058
    }
1059
1060
    /**
1061
     * Determines the id and evaluates any preview settings
1062
     * Basically this function is about determining whether a backend user is logged in,
1063
     * if he has read access to the page and if he's previewing the page.
1064
     * That all determines which id to show and how to initialize the id.
1065
     */
1066
    public function determineId()
1067
    {
1068
        // Call pre processing function for id determination
1069 View Code Duplication
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PreProcessing'] ?? [] as $functionReference) {
1070
            $parameters = ['parentObject' => $this];
1071
            GeneralUtility::callUserFunction($functionReference, $parameters, $this);
1072
        }
1073
        // If there is a Backend login we are going to check for any preview settings:
1074
        $this->getTimeTracker()->push('beUserLogin', '');
1075
        $originalFrontendUser = null;
1076
        $backendUser = $this->getBackendUser();
1077
        if ($this->beUserLogin || $this->doWorkspacePreview()) {
1078
            // Backend user preview features:
1079
            if ($this->beUserLogin && $backendUser->adminPanel instanceof AdminPanelView) {
1080
                $this->fePreview = (int)$backendUser->adminPanel->extGetFeAdminValue('preview');
1081
                // If admin panel preview is enabled...
1082
                if ($this->fePreview) {
1083
                    if ($this->fe_user->user) {
1084
                        $originalFrontendUser = $this->fe_user->user;
1085
                    }
1086
                    $this->showHiddenPage = (bool)$backendUser->adminPanel->extGetFeAdminValue('preview', 'showHiddenPages');
1087
                    $this->showHiddenRecords = (bool)$backendUser->adminPanel->extGetFeAdminValue('preview', 'showHiddenRecords');
1088
                    // Simulate date
1089
                    $simTime = $backendUser->adminPanel->extGetFeAdminValue('preview', 'simulateDate');
1090
                    if ($simTime) {
1091
                        $GLOBALS['SIM_EXEC_TIME'] = $simTime;
1092
                        $GLOBALS['SIM_ACCESS_TIME'] = $simTime - $simTime % 60;
1093
                    }
1094
                    // simulate user
1095
                    $simUserGroup = $backendUser->adminPanel->extGetFeAdminValue('preview', 'simulateUserGroup');
1096
                    $this->simUserGroup = $simUserGroup;
0 ignored issues
show
Documentation Bug introduced by
It seems like $simUserGroup can also be of type true. However, the property $simUserGroup is declared as type integer. Maybe add an additional type check?

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

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
1097
                    if ($simUserGroup) {
1098
                        if ($this->fe_user->user) {
1099
                            $this->fe_user->user[$this->fe_user->usergroup_column] = $simUserGroup;
1100
                        } else {
1101
                            $this->fe_user->user = [
1102
                                $this->fe_user->usergroup_column => $simUserGroup
1103
                            ];
1104
                        }
1105
                    }
1106
                    if (!$simUserGroup && !$simTime && !$this->showHiddenPage && !$this->showHiddenRecords) {
1107
                        $this->fePreview = 0;
1108
                    }
1109
                }
1110
            }
1111
            if ($this->id && $this->determineIdIsHiddenPage()) {
1112
                // The preview flag is set only if the current page turns out to actually be hidden!
1113
                $this->fePreview = 1;
1114
                $this->showHiddenPage = true;
1115
            }
1116
            // The preview flag will be set if a backend user is in an offline workspace
1117
            if (
1118
                    (
1119
                        $backendUser->user['workspace_preview']
1120
                        || GeneralUtility::_GP('ADMCMD_view')
0 ignored issues
show
Bug Best Practice introduced by
The expression TYPO3\CMS\Core\Utility\G...ity::_GP('ADMCMD_view') of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1121
                        || $this->doWorkspacePreview()
1122
                    )
1123
                    && (
1124
                        $this->whichWorkspace() === -1
1125
                        || $this->whichWorkspace() > 0
1126
                    )
1127
                    && !GeneralUtility::_GP('ADMCMD_noBeUser')
0 ignored issues
show
Bug Best Practice introduced by
The expression TYPO3\CMS\Core\Utility\G...:_GP('ADMCMD_noBeUser') of type null|string is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
1128
            ) {
1129
                // Will show special preview message.
1130
                $this->fePreview = 2;
1131
            }
1132
            // If the front-end is showing a preview, caching MUST be disabled.
1133
            if ($this->fePreview) {
1134
                $this->disableCache();
1135
            }
1136
        }
1137
        $this->getTimeTracker()->pull();
1138
        // Now, get the id, validate access etc:
1139
        $this->fetch_the_id();
1140
        // Check if backend user has read access to this page. If not, recalculate the id.
1141
        if ($this->beUserLogin && $this->fePreview) {
1142
            if (!$backendUser->doesUserHaveAccess($this->page, 1)) {
1143
                // Resetting
1144
                $this->clear_preview();
1145
                $this->fe_user->user = $originalFrontendUser;
1146
                // Fetching the id again, now with the preview settings reset.
1147
                $this->fetch_the_id();
1148
            }
1149
        }
1150
        // Checks if user logins are blocked for a certain branch and if so, will unset user login and re-fetch ID.
1151
        $this->loginAllowedInBranch = $this->checkIfLoginAllowedInBranch();
1152
        // Logins are not allowed:
1153
        if (!$this->loginAllowedInBranch) {
1154
            // Only if there is a login will we run this...
1155
            if ($this->isUserOrGroupSet()) {
1156
                if ($this->loginAllowedInBranch_mode === 'all') {
1157
                    // Clear out user and group:
1158
                    $this->fe_user->hideActiveLogin();
1159
                    $this->gr_list = '0,-1';
1160
                } else {
1161
                    $this->gr_list = '0,-2';
1162
                }
1163
                // Fetching the id again, now with the preview settings reset.
1164
                $this->fetch_the_id();
1165
            }
1166
        }
1167
        // Final cleaning.
1168
        // Make sure it's an integer
1169
        $this->id = ($this->contentPid = (int)$this->id);
1170
        // Make sure it's an integer
1171
        $this->type = (int)$this->type;
1172
        // Call post processing function for id determination:
1173
        $_params = ['pObj' => &$this];
1174
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'] ?? [] as $_funcRef) {
1175
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1176
        }
1177
    }
1178
1179
    /**
1180
     * Checks if the page is hidden in the active workspace.
1181
     * If it is hidden, preview flags will be set.
1182
     *
1183
     * @return bool
1184
     */
1185
    protected function determineIdIsHiddenPage()
1186
    {
1187
        $field = MathUtility::canBeInterpretedAsInteger($this->id) ? 'uid' : 'alias';
1188
1189
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1190
            ->getQueryBuilderForTable('pages');
1191
        $queryBuilder
1192
            ->getRestrictions()
1193
            ->removeAll()
1194
            ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1195
1196
        $page = $queryBuilder
1197
            ->select('uid', 'hidden', 'starttime', 'endtime')
1198
            ->from('pages')
1199
            ->where(
1200
                $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($this->id)),
1201
                $queryBuilder->expr()->gte('pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
1202
            )
1203
            ->setMaxResults(1)
1204
            ->execute()
1205
            ->fetch();
1206
1207
        $workspace = $this->whichWorkspace();
1208
        if ($workspace !== 0 && $workspace !== false) {
1209
            // Fetch overlay of page if in workspace and check if it is hidden
1210
            $pageSelectObject = GeneralUtility::makeInstance(PageRepository::class);
1211
            $pageSelectObject->versioningPreview = true;
1212
            $pageSelectObject->init(false);
1213
            $targetPage = $pageSelectObject->getWorkspaceVersionOfRecord($this->whichWorkspace(), 'pages', $page['uid']);
1214
            $result = $targetPage === -1 || $targetPage === -2;
1215
        } else {
1216
            $result = is_array($page) && ($page['hidden'] || $page['starttime'] > $GLOBALS['SIM_EXEC_TIME'] || $page['endtime'] != 0 && $page['endtime'] <= $GLOBALS['SIM_EXEC_TIME']);
1217
        }
1218
        return $result;
1219
    }
1220
1221
    /**
1222
     * Resolves the page id and sets up several related properties.
1223
     *
1224
     * If $this->id is not set at all or is not a plain integer, the method
1225
     * does it's best to set the value to an integer. Resolving is based on
1226
     * this options:
1227
     *
1228
     * - Splitting $this->id if it contains an additional type parameter.
1229
     * - Getting the id for an alias in $this->id
1230
     * - Finding the domain record start page
1231
     * - First visible page
1232
     * - Relocating the id below the domain record if outside
1233
     *
1234
     * The following properties may be set up or updated:
1235
     *
1236
     * - id
1237
     * - requestedId
1238
     * - type
1239
     * - domainStartPage
1240
     * - sys_page
1241
     * - sys_page->where_groupAccess
1242
     * - sys_page->where_hid_del
1243
     * - loginUser
1244
     * - gr_list
1245
     * - no_cache
1246
     * - register['SYS_LASTCHANGED']
1247
     * - pageNotFound
1248
     *
1249
     * Via getPageAndRootlineWithDomain()
1250
     *
1251
     * - rootLine
1252
     * - page
1253
     * - MP
1254
     * - originalShortcutPage
1255
     * - originalMountPointPage
1256
     * - pageAccessFailureHistory['direct_access']
1257
     * - pageNotFound
1258
     *
1259
     * @todo:
1260
     *
1261
     * On the first impression the method does to much. This is increased by
1262
     * the fact, that is is called repeated times by the method determineId.
1263
     * The reasons are manifold.
1264
     *
1265
     * 1.) The first part, the creation of sys_page, the type and alias
1266
     * resolution don't need to be repeated. They could be separated to be
1267
     * called only once.
1268
     *
1269
     * 2.) The user group setup could be done once on a higher level.
1270
     *
1271
     * 3.) The workflow of the resolution could be elaborated to be less
1272
     * tangled. Maybe the check of the page id to be below the domain via the
1273
     * root line doesn't need to be done each time, but for the final result
1274
     * only.
1275
     *
1276
     * 4.) The root line does not need to be directly addressed by this class.
1277
     * A root line is always related to one page. The rootline could be handled
1278
     * indirectly by page objects. Page objects still don't exist.
1279
     *
1280
     * @throws ServiceUnavailableException
1281
     * @access private
1282
     */
1283
    public function fetch_the_id()
1284
    {
1285
        $timeTracker = $this->getTimeTracker();
1286
        $timeTracker->push('fetch_the_id initialize/', '');
1287
        // Initialize the page-select functions.
1288
        $this->sys_page = GeneralUtility::makeInstance(PageRepository::class);
1289
        $this->sys_page->versioningPreview = $this->fePreview === 2 || (int)$this->workspacePreview || (bool)GeneralUtility::_GP('ADMCMD_view');
1290
        $this->sys_page->versioningWorkspaceId = $this->whichWorkspace();
1291
        $this->sys_page->init($this->showHiddenPage);
1292
        // Set the valid usergroups for FE
1293
        $this->initUserGroups();
1294
        // Sets sys_page where-clause
1295
        $this->setSysPageWhereClause();
1296
        // Splitting $this->id by a period (.).
1297
        // First part is 'id' and second part (if exists) will overrule the &type param
1298
        $idParts = explode('.', $this->id, 2);
1299
        $this->id = $idParts[0];
1300
        if (isset($idParts[1])) {
1301
            $this->type = $idParts[1];
1302
        }
1303
1304
        // If $this->id is a string, it's an alias
1305
        $this->checkAndSetAlias();
1306
        // The id and type is set to the integer-value - just to be sure...
1307
        $this->id = (int)$this->id;
1308
        $this->type = (int)$this->type;
1309
        $timeTracker->pull();
1310
        // We find the first page belonging to the current domain
1311
        $timeTracker->push('fetch_the_id domain/', '');
1312
        // The page_id of the current domain
1313
        $this->domainStartPage = $this->findDomainRecord($GLOBALS['TYPO3_CONF_VARS']['SYS']['recursiveDomainSearch']);
1314
        if (!$this->id) {
1315
            if ($this->domainStartPage) {
1316
                // If the id was not previously set, set it to the id of the domain.
1317
                $this->id = $this->domainStartPage;
1318
            } else {
1319
                // Find the first 'visible' page in that domain
1320
                $theFirstPage = $this->sys_page->getFirstWebPage($this->id);
1321 View Code Duplication
                if ($theFirstPage) {
1322
                    $this->id = $theFirstPage['uid'];
1323
                } else {
1324
                    $message = 'No pages are found on the rootlevel!';
1325
                    if ($this->checkPageUnavailableHandler()) {
1326
                        $this->pageUnavailableAndExit($message);
1327
                    } else {
1328
                        $this->logger->alert($message);
1329
                        throw new ServiceUnavailableException($message, 1301648975);
1330
                    }
1331
                }
1332
            }
1333
        }
1334
        $timeTracker->pull();
1335
        $timeTracker->push('fetch_the_id rootLine/', '');
1336
        // We store the originally requested id
1337
        $this->requestedId = $this->id;
1338
        $this->getPageAndRootlineWithDomain($this->domainStartPage);
1339
        $timeTracker->pull();
1340
        if ($this->pageNotFound && $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling']) {
1341
            $pNotFoundMsg = [
1342
                1 => 'ID was not an accessible page',
1343
                2 => 'Subsection was found and not accessible',
1344
                3 => 'ID was outside the domain',
1345
                4 => 'The requested page alias does not exist'
1346
            ];
1347
            $header = '';
1348
            if ($this->pageNotFound === 1 || $this->pageNotFound === 2) {
1349
                $header = $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling_accessdeniedheader'];
1350
            }
1351
            $this->pageNotFoundAndExit($pNotFoundMsg[$this->pageNotFound], $header);
1352
        }
1353
        // Init SYS_LASTCHANGED
1354
        $this->register['SYS_LASTCHANGED'] = (int)$this->page['tstamp'];
1355
        if ($this->register['SYS_LASTCHANGED'] < (int)$this->page['SYS_LASTCHANGED']) {
1356
            $this->register['SYS_LASTCHANGED'] = (int)$this->page['SYS_LASTCHANGED'];
1357
        }
1358 View Code Duplication
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['fetchPageId-PostProcessing'] ?? [] as $functionReference) {
1359
            $parameters = ['parentObject' => $this];
1360
            GeneralUtility::callUserFunction($functionReference, $parameters, $this);
1361
        }
1362
    }
1363
1364
    /**
1365
     * Loads the page and root line records based on $this->id
1366
     *
1367
     * A final page and the matching root line are determined and loaded by
1368
     * the algorithm defined by this method.
1369
     *
1370
     * First it loads the initial page from the page repository for $this->id.
1371
     * If that can't be loaded directly, it gets the root line for $this->id.
1372
     * It walks up the root line towards the root page until the page
1373
     * repository can deliver a page record. (The loading restrictions of
1374
     * the root line records are more liberal than that of the page record.)
1375
     *
1376
     * Now the page type is evaluated and handled if necessary. If the page is
1377
     * a short cut, it is replaced by the target page. If the page is a mount
1378
     * point in overlay mode, the page is replaced by the mounted page.
1379
     *
1380
     * After this potential replacements are done, the root line is loaded
1381
     * (again) for this page record. It walks up the root line up to
1382
     * the first viewable record.
1383
     *
1384
     * (While upon the first accessibility check of the root line it was done
1385
     * by loading page by page from the page repository, this time the method
1386
     * checkRootlineForIncludeSection() is used to find the most distant
1387
     * accessible page within the root line.)
1388
     *
1389
     * Having found the final page id, the page record and the root line are
1390
     * loaded for last time by this method.
1391
     *
1392
     * Exceptions may be thrown for DOKTYPE_SPACER and not loadable page records
1393
     * or root lines.
1394
     *
1395
     * If $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'] is set,
1396
     * instead of throwing an exception it's handled by a page unavailable
1397
     * handler.
1398
     *
1399
     * May set or update this properties:
1400
     *
1401
     * @see TypoScriptFrontendController::$id
1402
     * @see TypoScriptFrontendController::$MP
1403
     * @see TypoScriptFrontendController::$page
1404
     * @see TypoScriptFrontendController::$pageNotFound
1405
     * @see TypoScriptFrontendController::$pageAccessFailureHistory
1406
     * @see TypoScriptFrontendController::$originalMountPointPage
1407
     * @see TypoScriptFrontendController::$originalShortcutPage
1408
     *
1409
     * @throws ServiceUnavailableException
1410
     * @throws PageNotFoundException
1411
     * @access private
1412
     */
1413
    public function getPageAndRootline()
1414
    {
1415
        $this->resolveTranslatedPageId();
1416
        if (empty($this->page)) {
1417
            // If no page, we try to find the page before in the rootLine.
1418
            // Page is 'not found' in case the id itself was not an accessible page. code 1
1419
            $this->pageNotFound = 1;
1420
            $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

1420
            $this->rootLine = $this->sys_page->getRootLine(/** @scrutinizer ignore-type */ $this->id, $this->MP);
Loading history...
1421
            if (!empty($this->rootLine)) {
1422
                $c = count($this->rootLine) - 1;
1423
                while ($c > 0) {
1424
                    // Add to page access failure history:
1425
                    $this->pageAccessFailureHistory['direct_access'][] = $this->rootLine[$c];
1426
                    // Decrease to next page in rootline and check the access to that, if OK, set as page record and ID value.
1427
                    $c--;
1428
                    $this->id = $this->rootLine[$c]['uid'];
1429
                    $this->page = $this->sys_page->getPage($this->id);
1430
                    if (!empty($this->page)) {
1431
                        break;
1432
                    }
1433
                }
1434
            }
1435
            // If still no page...
1436 View Code Duplication
            if (empty($this->page)) {
1437
                $message = 'The requested page does not exist!';
1438
                if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling']) {
1439
                    $this->pageNotFoundAndExit($message);
1440
                } else {
1441
                    $this->logger->error($message);
1442
                    throw new PageNotFoundException($message, 1301648780);
1443
                }
1444
            }
1445
        }
1446
        // Spacer is not accessible in frontend
1447 View Code Duplication
        if ($this->page['doktype'] == PageRepository::DOKTYPE_SPACER) {
1448
            $message = 'The requested page does not exist!';
1449
            if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling']) {
1450
                $this->pageNotFoundAndExit($message);
1451
            } else {
1452
                $this->logger->error($message);
1453
                throw new PageNotFoundException($message, 1301648781);
1454
            }
1455
        }
1456
        // Is the ID a link to another page??
1457
        if ($this->page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1458
            // 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.
1459
            $this->MP = '';
1460
            // saving the page so that we can check later - when we know
1461
            // about languages - whether we took the correct shortcut or
1462
            // whether a translation of the page overwrites the shortcut
1463
            // target and we need to follow the new target
1464
            $this->originalShortcutPage = $this->page;
1465
            $this->page = $this->getPageShortcut($this->page['shortcut'], $this->page['shortcut_mode'], $this->page['uid']);
1466
            $this->id = $this->page['uid'];
1467
        }
1468
        // If the page is a mountpoint which should be overlaid with the contents of the mounted page,
1469
        // it must never be accessible directly, but only in the mountpoint context. Therefore we change
1470
        // the current ID and the user is redirected by checkPageForMountpointRedirect().
1471
        if ($this->page['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT && $this->page['mount_pid_ol']) {
1472
            $this->originalMountPointPage = $this->page;
1473
            $this->page = $this->sys_page->getPage($this->page['mount_pid']);
1474
            if (empty($this->page)) {
1475
                $message = 'This page (ID ' . $this->originalMountPointPage['uid'] . ') is of type "Mount point" and '
1476
                    . 'mounts a page which is not accessible (ID ' . $this->originalMountPointPage['mount_pid'] . ').';
1477
                throw new PageNotFoundException($message, 1402043263);
1478
            }
1479
            $this->MP = $this->page['uid'] . '-' . $this->originalMountPointPage['uid'];
1480
            $this->id = $this->page['uid'];
1481
        }
1482
        // Gets the rootLine
1483
        $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
0 ignored issues
show
Bug introduced by
It seems like $this->id can also be of type array; however, parameter $uid of TYPO3\CMS\Frontend\Page\...pository::getRootLine() does only seem to accept integer, 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

1483
        $this->rootLine = $this->sys_page->getRootLine(/** @scrutinizer ignore-type */ $this->id, $this->MP);
Loading history...
1484
        // If not rootline we're off...
1485 View Code Duplication
        if (empty($this->rootLine)) {
1486
            $message = 'The requested page didn\'t have a proper connection to the tree-root!';
1487
            if ($this->checkPageUnavailableHandler()) {
1488
                $this->pageUnavailableAndExit($message);
1489
            } else {
1490
                $this->logger->error($message);
1491
                throw new ServiceUnavailableException($message, 1301648167);
1492
            }
1493
        }
1494
        // Checking for include section regarding the hidden/starttime/endtime/fe_user (that is access control of a whole subbranch!)
1495
        if ($this->checkRootlineForIncludeSection()) {
1496
            if (empty($this->rootLine)) {
1497
                $message = 'The requested page was not accessible!';
1498
                if ($this->checkPageUnavailableHandler()) {
1499
                    $this->pageUnavailableAndExit($message);
1500
                } else {
1501
                    $this->logger->warning($message);
1502
                    throw new ServiceUnavailableException($message, 1301648234);
1503
                }
1504
            } else {
1505
                $el = reset($this->rootLine);
1506
                $this->id = $el['uid'];
1507
                $this->page = $this->sys_page->getPage($this->id);
1508
                $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1509
            }
1510
        }
1511
    }
1512
1513
    /**
1514
     * If $this->id contains a translated page record, this needs to be resolved to the default language
1515
     * in order for all rootline functionality and access restrictions to be in place further on.
1516
     *
1517
     * Additionally, if a translated page is found, $this->sys_language_uid/sys_language_content is set as well.
1518
     */
1519
    protected function resolveTranslatedPageId()
1520
    {
1521
        $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

1521
        $this->page = $this->sys_page->getPage(/** @scrutinizer ignore-type */ $this->id);
Loading history...
1522
        // Accessed a default language page record, nothing to resolve
1523
        if (empty($this->page) || (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']] === 0) {
1524
            return;
1525
        }
1526
        $this->sys_language_uid = (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
1527
        $this->sys_language_content = $this->sys_language_uid;
1528
        $this->page = $this->sys_page->getPage($this->page[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']]);
1529
        $this->id = $this->page['uid'];
1530
        // For common best-practice reasons, this is set, however, will be optional for new routing mechanisms
1531
        $this->mergingWithGetVars(['L' => $this->sys_language_uid]);
1532
    }
1533
1534
    /**
1535
     * Get page shortcut; Finds the records pointed to by input value $SC (the shortcut value)
1536
     *
1537
     * @param int $SC The value of the "shortcut" field from the pages record
1538
     * @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
1539
     * @param int $thisUid The current page UID of the page which is a shortcut
1540
     * @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...)
1541
     * @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.
1542
     * @param bool $disableGroupCheck If true, the group check is disabled when fetching the target page (needed e.g. for menu generation)
1543
     * @throws \RuntimeException
1544
     * @throws PageNotFoundException
1545
     * @return mixed Returns the page record of the page that the shortcut pointed to.
1546
     * @access private
1547
     * @see getPageAndRootline()
1548
     */
1549
    public function getPageShortcut($SC, $mode, $thisUid, $itera = 20, $pageLog = [], $disableGroupCheck = false)
1550
    {
1551
        $idArray = GeneralUtility::intExplode(',', $SC);
1552
        // Find $page record depending on shortcut mode:
1553
        switch ($mode) {
1554
            case PageRepository::SHORTCUT_MODE_FIRST_SUBPAGE:
1555
1556
            case PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE:
1557
                $pageArray = $this->sys_page->getMenu($idArray[0] ? $idArray[0] : $thisUid, '*', 'sorting', 'AND pages.doktype<199 AND pages.doktype!=' . PageRepository::DOKTYPE_BE_USER_SECTION);
1558
                $pO = 0;
1559
                if ($mode == PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE && !empty($pageArray)) {
1560
                    $randval = (int)rand(0, count($pageArray) - 1);
1561
                    $pO = $randval;
1562
                }
1563
                $c = 0;
1564
                $page = [];
1565
                foreach ($pageArray as $pV) {
1566
                    if ($c === $pO) {
1567
                        $page = $pV;
1568
                        break;
1569
                    }
1570
                    $c++;
1571
                }
1572 View Code Duplication
                if (empty($page)) {
1573
                    $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a subpage. ' . 'However, this page has no accessible subpages.';
1574
                    throw new PageNotFoundException($message, 1301648328);
1575
                }
1576
                break;
1577
            case PageRepository::SHORTCUT_MODE_PARENT_PAGE:
1578
                $parent = $this->sys_page->getPage($idArray[0] ? $idArray[0] : $thisUid, $disableGroupCheck);
1579
                $page = $this->sys_page->getPage($parent['pid'], $disableGroupCheck);
1580 View Code Duplication
                if (empty($page)) {
1581
                    $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to its parent page. ' . 'However, the parent page is not accessible.';
1582
                    throw new PageNotFoundException($message, 1301648358);
1583
                }
1584
                break;
1585
            default:
1586
                $page = $this->sys_page->getPage($idArray[0], $disableGroupCheck);
1587 View Code Duplication
                if (empty($page)) {
1588
                    $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a page, which is not accessible (ID ' . $idArray[0] . ').';
1589
                    throw new PageNotFoundException($message, 1301648404);
1590
                }
1591
        }
1592
        // Check if short cut page was a shortcut itself, if so look up recursively:
1593
        if ($page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1594
            if (!in_array($page['uid'], $pageLog) && $itera > 0) {
1595
                $pageLog[] = $page['uid'];
1596
                $page = $this->getPageShortcut($page['shortcut'], $page['shortcut_mode'], $page['uid'], $itera - 1, $pageLog, $disableGroupCheck);
1597
            } else {
1598
                $pageLog[] = $page['uid'];
1599
                $message = 'Page shortcuts were looping in uids ' . implode(',', $pageLog) . '...!';
1600
                $this->logger->error($message);
1601
                throw new \RuntimeException($message, 1294587212);
1602
            }
1603
        }
1604
        // Return resulting page:
1605
        return $page;
1606
    }
1607
1608
    /**
1609
     * Checks the current rootline for defined sections.
1610
     *
1611
     * @return bool
1612
     * @access private
1613
     */
1614
    public function checkRootlineForIncludeSection()
1615
    {
1616
        $c = count($this->rootLine);
1617
        $removeTheRestFlag = 0;
1618
        for ($a = 0; $a < $c; $a++) {
1619
            if (!$this->checkPagerecordForIncludeSection($this->rootLine[$a])) {
1620
                // Add to page access failure history:
1621
                $this->pageAccessFailureHistory['sub_section'][] = $this->rootLine[$a];
1622
                $removeTheRestFlag = 1;
1623
            }
1624
1625
            if ($this->rootLine[$a]['doktype'] == PageRepository::DOKTYPE_BE_USER_SECTION) {
1626
                // If there is a backend user logged in, check if he has read access to the page:
1627
                if ($this->beUserLogin) {
1628
                    $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1629
                        ->getQueryBuilderForTable('pages');
1630
1631
                    $queryBuilder
1632
                        ->getRestrictions()
1633
                        ->removeAll();
1634
1635
                    $row = $queryBuilder
1636
                        ->select('uid')
1637
                        ->from('pages')
1638
                        ->where(
1639
                            $queryBuilder->expr()->eq(
1640
                                'uid',
1641
                                $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
1642
                            ),
1643
                            $this->getBackendUser()->getPagePermsClause(1)
1644
                        )
1645
                        ->execute()
1646
                        ->fetch();
1647
1648
                    // versionOL()?
1649
                    if (!$row) {
1650
                        // 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...
1651
                        $removeTheRestFlag = 1;
1652
                    }
1653
                } else {
1654
                    // Don't go here, if there is no backend user logged in.
1655
                    $removeTheRestFlag = 1;
1656
                }
1657
            }
1658
            if ($removeTheRestFlag) {
1659
                // Page is 'not found' in case a subsection was found and not accessible, code 2
1660
                $this->pageNotFound = 2;
1661
                unset($this->rootLine[$a]);
1662
            }
1663
        }
1664
        return $removeTheRestFlag;
1665
    }
1666
1667
    /**
1668
     * Checks page record for enableFields
1669
     * Returns TRUE if enableFields does not disable the page record.
1670
     * Takes notice of the ->showHiddenPage flag and uses SIM_ACCESS_TIME for start/endtime evaluation
1671
     *
1672
     * @param array $row The page record to evaluate (needs fields: hidden, starttime, endtime, fe_group)
1673
     * @param bool $bypassGroupCheck Bypass group-check
1674
     * @return bool TRUE, if record is viewable.
1675
     * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList(), checkPagerecordForIncludeSection()
1676
     */
1677
    public function checkEnableFields($row, $bypassGroupCheck = false)
1678
    {
1679
        $_params = ['pObj' => $this, 'row' => &$row, 'bypassGroupCheck' => &$bypassGroupCheck];
1680 View Code Duplication
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_checkEnableFields'] ?? [] as $_funcRef) {
1681
            // Call hooks: If one returns FALSE, method execution is aborted with result "This record is not available"
1682
            $return = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1683
            if ($return === false) {
1684
                return false;
1685
            }
1686
        }
1687
        if ((!$row['hidden'] || $this->showHiddenPage) && $row['starttime'] <= $GLOBALS['SIM_ACCESS_TIME'] && ($row['endtime'] == 0 || $row['endtime'] > $GLOBALS['SIM_ACCESS_TIME']) && ($bypassGroupCheck || $this->checkPageGroupAccess($row))) {
1688
            return true;
1689
        }
1690
        return false;
1691
    }
1692
1693
    /**
1694
     * Check group access against a page record
1695
     *
1696
     * @param array $row The page record to evaluate (needs field: fe_group)
1697
     * @param mixed $groupList List of group id's (comma list or array). Default is $this->gr_list
1698
     * @return bool TRUE, if group access is granted.
1699
     * @access private
1700
     */
1701
    public function checkPageGroupAccess($row, $groupList = null)
1702
    {
1703
        if (is_null($groupList)) {
1704
            $groupList = $this->gr_list;
1705
        }
1706
        if (!is_array($groupList)) {
1707
            $groupList = explode(',', $groupList);
1708
        }
1709
        $pageGroupList = explode(',', $row['fe_group'] ?: 0);
1710
        return count(array_intersect($groupList, $pageGroupList)) > 0;
1711
    }
1712
1713
    /**
1714
     * Checks page record for include section
1715
     *
1716
     * @param array $row The page record to evaluate (needs fields: extendToSubpages + hidden, starttime, endtime, fe_group)
1717
     * @return bool Returns TRUE if either extendToSubpages is not checked or if the enableFields does not disable the page record.
1718
     * @access private
1719
     * @see checkEnableFields(), \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList(), checkRootlineForIncludeSection()
1720
     */
1721
    public function checkPagerecordForIncludeSection($row)
1722
    {
1723
        return !$row['extendToSubpages'] || $this->checkEnableFields($row);
1724
    }
1725
1726
    /**
1727
     * 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!)
1728
     *
1729
     * @return bool returns TRUE if logins are OK, otherwise FALSE (and then the login user must be unset!)
1730
     */
1731
    public function checkIfLoginAllowedInBranch()
1732
    {
1733
        // Initialize:
1734
        $c = count($this->rootLine);
1735
        $loginAllowed = true;
1736
        // Traverse root line from root and outwards:
1737
        for ($a = 0; $a < $c; $a++) {
1738
            // If a value is set for login state:
1739
            if ($this->rootLine[$a]['fe_login_mode'] > 0) {
1740
                // Determine state from value:
1741
                if ((int)$this->rootLine[$a]['fe_login_mode'] === 1) {
1742
                    $loginAllowed = false;
1743
                    $this->loginAllowedInBranch_mode = 'all';
1744
                } elseif ((int)$this->rootLine[$a]['fe_login_mode'] === 3) {
1745
                    $loginAllowed = false;
1746
                    $this->loginAllowedInBranch_mode = 'groups';
1747
                } else {
1748
                    $loginAllowed = true;
1749
                }
1750
            }
1751
        }
1752
        return $loginAllowed;
1753
    }
1754
1755
    /**
1756
     * 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
1757
     *
1758
     * @return array Summary of why page access was not allowed.
1759
     */
1760
    public function getPageAccessFailureReasons()
1761
    {
1762
        $output = [];
1763
        $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'] : []);
1764
        if (!empty($combinedRecords)) {
1765
            foreach ($combinedRecords as $k => $pagerec) {
1766
                // 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
1767
                // 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!
1768
                if (!$k || $pagerec['extendToSubpages']) {
1769
                    if ($pagerec['hidden']) {
1770
                        $output['hidden'][$pagerec['uid']] = true;
1771
                    }
1772
                    if ($pagerec['starttime'] > $GLOBALS['SIM_ACCESS_TIME']) {
1773
                        $output['starttime'][$pagerec['uid']] = $pagerec['starttime'];
1774
                    }
1775
                    if ($pagerec['endtime'] != 0 && $pagerec['endtime'] <= $GLOBALS['SIM_ACCESS_TIME']) {
1776
                        $output['endtime'][$pagerec['uid']] = $pagerec['endtime'];
1777
                    }
1778
                    if (!$this->checkPageGroupAccess($pagerec)) {
1779
                        $output['fe_group'][$pagerec['uid']] = $pagerec['fe_group'];
1780
                    }
1781
                }
1782
            }
1783
        }
1784
        return $output;
1785
    }
1786
1787
    /**
1788
     * Gets ->page and ->rootline information based on ->id. ->id may change during this operation.
1789
     * If not inside domain, then default to first page in domain.
1790
     *
1791
     * @param int $domainStartPage Page uid of the page where the found domain record is (pid of the domain record)
1792
     * @access private
1793
     */
1794
    public function getPageAndRootlineWithDomain($domainStartPage)
1795
    {
1796
        $this->getPageAndRootline();
1797
        // 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.
1798
        if ($domainStartPage && is_array($this->rootLine)) {
1799
            $idFound = 0;
1800
            foreach ($this->rootLine as $key => $val) {
1801
                if ($val['uid'] == $domainStartPage) {
1802
                    $idFound = 1;
1803
                    break;
1804
                }
1805
            }
1806
            if (!$idFound) {
1807
                // Page is 'not found' in case the id was outside the domain, code 3
1808
                $this->pageNotFound = 3;
1809
                $this->id = $domainStartPage;
1810
                // re-get the page and rootline if the id was not found.
1811
                $this->getPageAndRootline();
1812
            }
1813
        }
1814
    }
1815
1816
    /**
1817
     * Sets sys_page where-clause
1818
     *
1819
     * @access private
1820
     */
1821
    public function setSysPageWhereClause()
1822
    {
1823
        $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1824
            ->getConnectionForTable('pages')
1825
            ->getExpressionBuilder();
1826
        $this->sys_page->where_hid_del = ' AND ' . (string)$expressionBuilder->andX(
1827
            QueryHelper::stripLogicalOperatorPrefix($this->sys_page->where_hid_del),
1828
            $expressionBuilder->lt('pages.doktype', 200)
1829
        );
1830
        $this->sys_page->where_groupAccess = $this->sys_page->getMultipleGroupsWhereClause('pages.fe_group', 'pages');
1831
    }
1832
1833
    /**
1834
     * Looking up a domain record based on HTTP_HOST
1835
     *
1836
     * @param bool $recursive If set, it looks "recursively" meaning that a domain like "123.456.typo3.com" would find a domain record like "typo3.com" if "123.456.typo3.com" or "456.typo3.com" did not exist.
1837
     * @return int Returns the page id of the page where the domain record was found.
1838
     * @access private
1839
     */
1840
    public function findDomainRecord($recursive = false)
1841
    {
1842
        if ($recursive) {
1843
            $pageUid = 0;
1844
            $host = explode('.', GeneralUtility::getIndpEnv('HTTP_HOST'));
1845
            while (count($host)) {
1846
                $pageUid = $this->sys_page->getDomainStartPage(implode('.', $host), GeneralUtility::getIndpEnv('SCRIPT_NAME'), GeneralUtility::getIndpEnv('REQUEST_URI'));
1847
                if ($pageUid) {
1848
                    return $pageUid;
1849
                }
1850
                array_shift($host);
1851
            }
1852
            return $pageUid;
1853
        }
1854
        return $this->sys_page->getDomainStartPage(GeneralUtility::getIndpEnv('HTTP_HOST'), GeneralUtility::getIndpEnv('SCRIPT_NAME'), GeneralUtility::getIndpEnv('REQUEST_URI'));
1855
    }
1856
1857
    /**
1858
     * Page unavailable handler for use in frontend plugins from extensions.
1859
     *
1860
     * @param string $reason Reason text
1861
     * @param string $header HTTP header to send
1862
     */
1863
    public function pageUnavailableAndExit($reason = '', $header = '')
1864
    {
1865
        $header = $header ?: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling_statheader'];
1866
        $this->pageUnavailableHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling'], $header, $reason);
1867
        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...
1868
    }
1869
1870
    /**
1871
     * Page-not-found handler for use in frontend plugins from extensions.
1872
     *
1873
     * @param string $reason Reason text
1874
     * @param string $header HTTP header to send
1875
     */
1876
    public function pageNotFoundAndExit($reason = '', $header = '')
1877
    {
1878
        $header = $header ?: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling_statheader'];
1879
        $this->pageNotFoundHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'], $header, $reason);
1880
        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...
1881
    }
1882
1883
    /**
1884
     * Checks whether the pageUnavailableHandler should be used. To be used, pageUnavailable_handling must be set
1885
     * and devIPMask must not match the current visitor's IP address.
1886
     *
1887
     * @return bool TRUE/FALSE whether the pageUnavailable_handler should be used.
1888
     */
1889
    public function checkPageUnavailableHandler()
1890
    {
1891
        if (
1892
            $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling']
1893
            && !GeneralUtility::cmpIP(
1894
                GeneralUtility::getIndpEnv('REMOTE_ADDR'),
1895
                $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']
1896
            )
1897
        ) {
1898
            $checkPageUnavailableHandler = true;
1899
        } else {
1900
            $checkPageUnavailableHandler = false;
1901
        }
1902
        return $checkPageUnavailableHandler;
1903
    }
1904
1905
    /**
1906
     * Page unavailable handler. Acts a wrapper for the pageErrorHandler method.
1907
     *
1908
     * @param mixed $code See ['FE']['pageUnavailable_handling'] for possible values
1909
     * @param string $header If set, this is passed directly to the PHP function, header()
1910
     * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1911
     */
1912
    public function pageUnavailableHandler($code, $header, $reason)
1913
    {
1914
        $this->pageErrorHandler($code, $header, $reason);
1915
    }
1916
1917
    /**
1918
     * Page not found handler. Acts a wrapper for the pageErrorHandler method.
1919
     *
1920
     * @param mixed $code See docs of ['FE']['pageNotFound_handling'] for 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
     */
1924
    public function pageNotFoundHandler($code, $header = '', $reason = '')
1925
    {
1926
        $this->pageErrorHandler($code, $header, $reason);
1927
    }
1928
1929
    /**
1930
     * Generic error page handler.
1931
     * Exits.
1932
     *
1933
     * @param mixed $code See docs of ['FE']['pageNotFound_handling'] and ['FE']['pageUnavailable_handling'] for all possible values
1934
     * @param string $header If set, this is passed directly to the PHP function, header()
1935
     * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1936
     * @throws \RuntimeException
1937
     */
1938
    public function pageErrorHandler($code, $header = '', $reason = '')
1939
    {
1940
        // Issue header in any case:
1941
        if ($header) {
1942
            $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY);
1943
            foreach ($headerArr as $header) {
1944
                header($header);
1945
            }
1946
        }
1947
        // Create response:
1948
        // Simply boolean; Just shows TYPO3 error page with reason:
1949
        if (strtolower($code) === 'true' || (string)$code === '1' || gettype($code) === 'boolean') {
1950
            echo GeneralUtility::makeInstance(ErrorPageController::class)->errorAction(
1951
                'Page Not Found',
1952
                'The page did not exist or was inaccessible.' . ($reason ? ' Reason: ' . $reason : '')
1953
            );
1954
        } elseif (GeneralUtility::isFirstPartOfStr($code, 'USER_FUNCTION:')) {
1955
            $funcRef = trim(substr($code, 14));
0 ignored issues
show
Bug introduced by
It seems like substr($code, 14) can also be of type false; however, parameter $str of trim() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

1955
            $funcRef = trim(/** @scrutinizer ignore-type */ substr($code, 14));
Loading history...
1956
            $params = [
1957
                'currentUrl' => GeneralUtility::getIndpEnv('REQUEST_URI'),
1958
                'reasonText' => $reason,
1959
                'pageAccessFailureReasons' => $this->getPageAccessFailureReasons()
1960
            ];
1961
            try {
1962
                echo GeneralUtility::callUserFunction($funcRef, $params, $this);
1963
            } catch (\Exception $e) {
1964
                throw new \RuntimeException('Error: 404 page by USER_FUNCTION "' . $funcRef . '" failed.', 1509296032, $e);
1965
            }
1966
        } elseif (GeneralUtility::isFirstPartOfStr($code, 'READFILE:')) {
1967
            $readFile = GeneralUtility::getFileAbsFileName(trim(substr($code, 9)));
1968
            if (@is_file($readFile)) {
1969
                echo str_replace(
1970
                    [
1971
                        '###CURRENT_URL###',
1972
                        '###REASON###'
1973
                    ],
1974
                    [
1975
                        GeneralUtility::getIndpEnv('REQUEST_URI'),
1976
                        htmlspecialchars($reason)
1977
                    ],
1978
                    file_get_contents($readFile)
1979
                );
1980
            } else {
1981
                throw new \RuntimeException('Configuration Error: 404 page "' . $readFile . '" could not be found.', 1294587214);
1982
            }
1983
        } elseif (GeneralUtility::isFirstPartOfStr($code, 'REDIRECT:')) {
1984
            HttpUtility::redirect(substr($code, 9));
0 ignored issues
show
Bug introduced by
It seems like substr($code, 9) can also be of type false; however, parameter $url of TYPO3\CMS\Core\Utility\HttpUtility::redirect() 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

1984
            HttpUtility::redirect(/** @scrutinizer ignore-type */ substr($code, 9));
Loading history...
1985
        } elseif ($code !== '') {
1986
            // Check if URL is relative
1987
            $url_parts = parse_url($code);
1988
            // parse_url could return an array without the key "host", the empty check works better than strict check
1989
            if (empty($url_parts['host'])) {
1990
                $url_parts['host'] = GeneralUtility::getIndpEnv('HTTP_HOST');
1991 View Code Duplication
                if ($code[0] === '/') {
1992
                    $code = GeneralUtility::getIndpEnv('TYPO3_REQUEST_HOST') . $code;
1993
                } else {
1994
                    $code = GeneralUtility::getIndpEnv('TYPO3_REQUEST_DIR') . $code;
1995
                }
1996
                $checkBaseTag = false;
1997
            } else {
1998
                $checkBaseTag = true;
1999
            }
2000
            // Check recursion
2001
            if ($code == GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')) {
2002
                if ($reason == '') {
2003
                    $reason = 'Page cannot be found.';
2004
                }
2005
                $reason .= LF . LF . 'Additionally, ' . $code . ' was not found while trying to retrieve the error document.';
2006
                throw new \RuntimeException(nl2br(htmlspecialchars($reason)), 1294587215);
2007
            }
2008
            // Prepare headers
2009
            $headerArr = [
2010
                'User-agent: ' . GeneralUtility::getIndpEnv('HTTP_USER_AGENT'),
2011
                'Referer: ' . GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')
2012
            ];
2013
            $report = [];
2014
            $res = GeneralUtility::getUrl($code, 1, $headerArr, $report);
2015
            if ((int)$report['error'] !== 0 && (int)$report['error'] !== 200) {
2016
                throw new \RuntimeException('Failed to fetch error page "' . $code . '", reason: ' . $report['message'], 1509296606);
2017
            }
2018
            // Header and content are separated by an empty line
2019
            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

2019
            list($header, $content) = explode(CRLF . CRLF, /** @scrutinizer ignore-type */ $res, 2);
Loading history...
2020
            $content .= CRLF;
2021
            if (false === $res) {
2022
                // Last chance -- redirect
2023
                HttpUtility::redirect($code);
2024
            } else {
2025
                // Forward these response headers to the client
2026
                $forwardHeaders = [
2027
                    'Content-Type:'
2028
                ];
2029
                $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY);
2030
                foreach ($headerArr as $header) {
2031
                    foreach ($forwardHeaders as $h) {
2032
                        if (preg_match('/^' . $h . '/', $header)) {
2033
                            header($header);
2034
                        }
2035
                    }
2036
                }
2037
                // Put <base> if necessary
2038
                if ($checkBaseTag) {
2039
                    // If content already has <base> tag, we do not need to do anything
2040
                    if (false === stristr($content, '<base ')) {
2041
                        // Generate href for base tag
2042
                        $base = $url_parts['scheme'] . '://';
2043
                        if ($url_parts['user'] != '') {
2044
                            $base .= $url_parts['user'];
2045
                            if ($url_parts['pass'] != '') {
2046
                                $base .= ':' . $url_parts['pass'];
2047
                            }
2048
                            $base .= '@';
2049
                        }
2050
                        $base .= $url_parts['host'];
2051
                        // Add path portion skipping possible file name
2052
                        $base .= preg_replace('/(.*\\/)[^\\/]*/', '${1}', $url_parts['path']);
2053
                        // Put it into content (generate also <head> if necessary)
2054
                        $replacement = LF . '<base href="' . htmlentities($base) . '" />' . LF;
2055
                        if (stristr($content, '<head>')) {
2056
                            $content = preg_replace('/(<head>)/i', '\\1' . $replacement, $content);
2057
                        } else {
2058
                            $content = preg_replace('/(<html[^>]*>)/i', '\\1<head>' . $replacement . '</head>', $content);
2059
                        }
2060
                    }
2061
                }
2062
                // Output the content
2063
                echo $content;
2064
            }
2065
        } else {
2066
            echo GeneralUtility::makeInstance(ErrorPageController::class)->errorAction(
2067
                'Page Not Found',
2068
                $reason ? 'Reason: ' . $reason : 'Page cannot be found.'
2069
            );
2070
        }
2071
        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...
2072
    }
2073
2074
    /**
2075
     * Fetches the integer page id for a page alias.
2076
     * 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
2077
     *
2078
     * @access private
2079
     */
2080
    public function checkAndSetAlias()
2081
    {
2082
        if ($this->id && !MathUtility::canBeInterpretedAsInteger($this->id)) {
2083
            $aid = $this->sys_page->getPageIdFromAlias($this->id);
2084
            if ($aid) {
2085
                $this->id = $aid;
2086
            } else {
2087
                $this->pageNotFound = 4;
2088
            }
2089
        }
2090
    }
2091
2092
    /**
2093
     * Merging values into the global $_GET
2094
     *
2095
     * @param array $GET_VARS Array of key/value pairs that will be merged into the current GET-vars. (Non-escaped values)
2096
     */
2097
    public function mergingWithGetVars($GET_VARS)
2098
    {
2099
        if (is_array($GET_VARS)) {
2100
            // Getting $_GET var, unescaped.
2101
            $realGet = GeneralUtility::_GET();
2102
            if (!is_array($realGet)) {
2103
                $realGet = [];
2104
            }
2105
            // Merge new values on top:
2106
            ArrayUtility::mergeRecursiveWithOverrule($realGet, $GET_VARS);
2107
            // Write values back to $_GET:
2108
            GeneralUtility::_GETset($realGet);
2109
            // Setting these specifically (like in the init-function):
2110
            if (isset($GET_VARS['type'])) {
2111
                $this->type = (int)$GET_VARS['type'];
2112
            }
2113
            if (isset($GET_VARS['cHash'])) {
2114
                $this->cHash = $GET_VARS['cHash'];
2115
            }
2116
            if (isset($GET_VARS['MP'])) {
2117
                $this->MP = $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] ? $GET_VARS['MP'] : '';
2118
            }
2119
            if (isset($GET_VARS['no_cache']) && $GET_VARS['no_cache']) {
2120
                $this->set_no_cache('no_cache is requested via GET parameter');
2121
            }
2122
        }
2123
    }
2124
2125
    /********************************************
2126
     *
2127
     * Template and caching related functions.
2128
     *
2129
     *******************************************/
2130
    /**
2131
     * Calculates a hash string based on additional parameters in the url.
2132
     *
2133
     * Calculated hash is stored in $this->cHash_array.
2134
     * This is used to cache pages with more parameters than just id and type.
2135
     *
2136
     * @see reqCHash()
2137
     */
2138
    public function makeCacheHash()
2139
    {
2140
        // No need to test anything if caching was already disabled.
2141
        if ($this->no_cache && !$GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2142
            return;
2143
        }
2144
        $GET = GeneralUtility::_GET();
2145
        if ($this->cHash && is_array($GET)) {
2146
            // Make sure we use the page uid and not the page alias
2147
            $GET['id'] = $this->id;
2148
            $this->cHash_array = $this->cacheHash->getRelevantParameters(GeneralUtility::implodeArrayForUrl('', $GET));
2149
            $cHash_calc = $this->cacheHash->calculateCacheHash($this->cHash_array);
2150
            if ($cHash_calc != $this->cHash) {
2151
                if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2152
                    $this->pageNotFoundAndExit('Request parameters could not be validated (&cHash comparison failed)');
2153
                } else {
2154
                    $this->disableCache();
2155
                    $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);
2156
                }
2157
            }
2158
        } elseif (is_array($GET)) {
2159
            // No cHash is set, check if that is correct
2160
            if ($this->cacheHash->doParametersRequireCacheHash(GeneralUtility::implodeArrayForUrl('', $GET))) {
2161
                $this->reqCHash();
2162
            }
2163
        }
2164
    }
2165
2166
    /**
2167
     * Will disable caching if the cHash value was not set.
2168
     * 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)
2169
     *
2170
     * @see makeCacheHash(), \TYPO3\CMS\Frontend\Plugin\AbstractPlugin::pi_cHashCheck()
2171
     */
2172
    public function reqCHash()
2173
    {
2174
        if (!$this->cHash) {
2175
            if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2176
                if ($this->tempContent) {
2177
                    $this->clearPageCacheContent();
2178
                }
2179
                $this->pageNotFoundAndExit('Request parameters could not be validated (&cHash empty)');
2180
            } else {
2181
                $this->disableCache();
2182
                $this->getTimeTracker()->setTSlogMessage('TSFE->reqCHash(): No &cHash parameter was sent for GET vars though required so caching is disabled', 2);
2183
            }
2184
        }
2185
    }
2186
2187
    /**
2188
     * Initialize the TypoScript template parser
2189
     */
2190
    public function initTemplate()
2191
    {
2192
        $this->tmpl = GeneralUtility::makeInstance(TemplateService::class);
2193
        $this->tmpl->setVerbose((bool)$this->beUserLogin);
2194
        $this->tmpl->init();
2195
        $this->tmpl->tt_track = (bool)$this->beUserLogin;
2196
    }
2197
2198
    /**
2199
     * See if page is in cache and get it if so
2200
     * Stores the page content in $this->content if something is found.
2201
     *
2202
     * @throws \InvalidArgumentException
2203
     * @throws \RuntimeException
2204
     */
2205
    public function getFromCache()
2206
    {
2207
        // clearing the content-variable, which will hold the pagecontent
2208
        $this->content = '';
2209
        // Unsetting the lowlevel config
2210
        $this->config = [];
2211
        $this->cacheContentFlag = false;
2212
2213
        if ($this->no_cache) {
2214
            return;
2215
        }
2216
2217
        $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2218
        if (!is_array($pageSectionCacheContent)) {
2219
            // Nothing in the cache, we acquire an "exclusive lock" for the key now.
2220
            // We use the Registry to store this lock centrally,
2221
            // but we protect the access again with a global exclusive lock to avoid race conditions
2222
2223
            $this->acquireLock('pagesection', $this->id . '::' . $this->MP);
2224
            //
2225
            // from this point on we're the only one working on that page ($key)
2226
            //
2227
2228
            // query the cache again to see if the page data are there meanwhile
2229
            $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2230
            if (is_array($pageSectionCacheContent)) {
2231
                // we have the content, nice that some other process did the work for us already
2232
                $this->releaseLock('pagesection');
2233
            }
2234
            // We keep the lock set, because we are the ones generating the page now
2235
                // and filling the cache.
2236
                // This indicates that we have to release the lock in the Registry later in releaseLocks()
2237
        }
2238
2239
        if (is_array($pageSectionCacheContent)) {
2240
            // 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.
2241
            // If this hash is not the same in here in this section and after page-generation, then the page will not be properly cached!
2242
            // 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.
2243
            $pageSectionCacheContent = $this->tmpl->matching($pageSectionCacheContent);
2244
            ksort($pageSectionCacheContent);
2245
            $this->all = $pageSectionCacheContent;
2246
        }
2247
        unset($pageSectionCacheContent);
2248
2249
        // Look for page in cache only if a shift-reload is not sent to the server.
2250
        $lockHash = $this->getLockHash();
2251
        if (!$this->headerNoCache()) {
2252
            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...
2253
                // we got page section information
2254
                $this->newHash = $this->getHash();
2255
                $this->getTimeTracker()->push('Cache Row', '');
2256
                $row = $this->getFromCache_queryRow();
2257
                if (!is_array($row)) {
2258
                    // nothing in the cache, we acquire an exclusive lock now
2259
2260
                    $this->acquireLock('pages', $lockHash);
2261
                    //
2262
                    // from this point on we're the only one working on that page ($lockHash)
2263
                    //
2264
2265
                    // query the cache again to see if the data are there meanwhile
2266
                    $row = $this->getFromCache_queryRow();
2267
                    if (is_array($row)) {
2268
                        // we have the content, nice that some other process did the work for us
2269
                        $this->releaseLock('pages');
2270
                    }
2271
                    // We keep the lock set, because we are the ones generating the page now
2272
                        // and filling the cache.
2273
                        // This indicates that we have to release the lock in the Registry later in releaseLocks()
2274
                }
2275
                if (is_array($row)) {
2276
                    // we have data from cache
2277
2278
                    // Call hook when a page is retrieved from cache:
2279
                    $_params = ['pObj' => &$this, 'cache_pages_row' => &$row];
2280
                    foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'] ?? [] as $_funcRef) {
2281
                        GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2282
                    }
2283
                    // Fetches the lowlevel config stored with the cached data
2284
                    $this->config = $row['cache_data'];
2285
                    // Getting the content
2286
                    $this->content = $row['content'];
2287
                    // Flag for temp content
2288
                    $this->tempContent = $row['temp_content'];
2289
                    // Setting flag, so we know, that some cached content has been loaded
2290
                    $this->cacheContentFlag = true;
2291
                    $this->cacheExpires = $row['expires'];
2292
2293
                    // Restore page title information, this is needed to generate the page title for
2294
                    // partially cached pages.
2295
                    $this->page['title'] = $row['pageTitleInfo']['title'];
2296
                    $this->altPageTitle = $row['pageTitleInfo']['altPageTitle'];
2297
                    $this->indexedDocTitle = $row['pageTitleInfo']['indexedDocTitle'];
2298
2299 View Code Duplication
                    if (isset($this->config['config']['debug'])) {
2300
                        $debugCacheTime = (bool)$this->config['config']['debug'];
2301
                    } else {
2302
                        $debugCacheTime = !empty($GLOBALS['TYPO3_CONF_VARS']['FE']['debug']);
2303
                    }
2304
                    if ($debugCacheTime) {
2305
                        $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
2306
                        $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
2307
                        $this->content .= LF . '<!-- Cached page generated ' . date(($dateFormat . ' ' . $timeFormat), $row['tstamp']) . '. Expires ' . date(($dateFormat . ' ' . $timeFormat), $row['expires']) . ' -->';
0 ignored issues
show
Bug introduced by
Are you sure date($dateFormat . ' ' ....Format, $row['tstamp']) of type false|string can be used in concatenation? ( Ignorable by Annotation )

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

2307
                        $this->content .= LF . '<!-- Cached page generated ' . /** @scrutinizer ignore-type */ date(($dateFormat . ' ' . $timeFormat), $row['tstamp']) . '. Expires ' . date(($dateFormat . ' ' . $timeFormat), $row['expires']) . ' -->';
Loading history...
Bug introduced by
Are you sure date($dateFormat . ' ' ....ormat, $row['expires']) of type false|string can be used in concatenation? ( Ignorable by Annotation )

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

2307
                        $this->content .= LF . '<!-- Cached page generated ' . date(($dateFormat . ' ' . $timeFormat), $row['tstamp']) . '. Expires ' . /** @scrutinizer ignore-type */ date(($dateFormat . ' ' . $timeFormat), $row['expires']) . ' -->';
Loading history...
2308
                    }
2309
                }
2310
                $this->getTimeTracker()->pull();
2311
2312
                return;
2313
            }
2314
        }
2315
        // the user forced rebuilding the page cache or there was no pagesection information
2316
        // get a lock for the page content so other processes will not interrupt the regeneration
2317
        $this->acquireLock('pages', $lockHash);
2318
    }
2319
2320
    /**
2321
     * Returning the cached version of page with hash = newHash
2322
     *
2323
     * @return array Cached row, if any. Otherwise void.
2324
     */
2325
    public function getFromCache_queryRow()
2326
    {
2327
        $this->getTimeTracker()->push('Cache Query', '');
2328
        $row = $this->pageCache->get($this->newHash);
2329
        $this->getTimeTracker()->pull();
2330
        return $row;
2331
    }
2332
2333
    /**
2334
     * Detecting if shift-reload has been clicked
2335
     * Will not be called if re-generation of page happens by other reasons (for instance that the page is not in cache yet!)
2336
     * Also, a backend user MUST be logged in for the shift-reload to be detected due to DoS-attack-security reasons.
2337
     *
2338
     * @return bool If shift-reload in client browser has been clicked, disable getting cached page (and regenerate it).
2339
     */
2340
    public function headerNoCache()
2341
    {
2342
        $disableAcquireCacheData = false;
2343
        if ($this->beUserLogin) {
2344
            if (strtolower($_SERVER['HTTP_CACHE_CONTROL']) === 'no-cache' || strtolower($_SERVER['HTTP_PRAGMA']) === 'no-cache') {
2345
                $disableAcquireCacheData = true;
2346
            }
2347
        }
2348
        // Call hook for possible by-pass of requiring of page cache (for recaching purpose)
2349
        $_params = ['pObj' => &$this, 'disableAcquireCacheData' => &$disableAcquireCacheData];
2350
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'] ?? [] as $_funcRef) {
2351
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2352
        }
2353
        return $disableAcquireCacheData;
2354
    }
2355
2356
    /**
2357
     * Calculates the cache-hash
2358
     * This hash is unique to the template, the variables ->id, ->type, ->gr_list (list of groups), ->MP (Mount Points) and cHash array
2359
     * Used to get and later store the cached data.
2360
     *
2361
     * @return string MD5 hash of serialized hash base from createHashBase()
2362
     * @access private
2363
     * @see getFromCache(), getLockHash()
2364
     */
2365
    public function getHash()
2366
    {
2367
        return md5($this->createHashBase(false));
2368
    }
2369
2370
    /**
2371
     * Calculates the lock-hash
2372
     * This hash is unique to the above hash, except that it doesn't contain the template information in $this->all.
2373
     *
2374
     * @return string MD5 hash
2375
     * @access private
2376
     * @see getFromCache(), getHash()
2377
     */
2378
    public function getLockHash()
2379
    {
2380
        $lockHash = $this->createHashBase(true);
2381
        return md5($lockHash);
2382
    }
2383
2384
    /**
2385
     * Calculates the cache-hash (or the lock-hash)
2386
     * This hash is unique to the template,
2387
     * the variables ->id, ->type, ->gr_list (list of groups),
2388
     * ->MP (Mount Points) and cHash array
2389
     * Used to get and later store the cached data.
2390
     *
2391
     * @param bool $createLockHashBase Whether to create the lock hash, which doesn't contain the "this->all" (the template information)
2392
     * @return string the serialized hash base
2393
     */
2394
    protected function createHashBase($createLockHashBase = false)
2395
    {
2396
        $hashParameters = [
2397
            'id' => (int)$this->id,
2398
            'type' => (int)$this->type,
2399
            'gr_list' => (string)$this->gr_list,
2400
            'MP' => (string)$this->MP,
2401
            'cHash' => $this->cHash_array,
2402
            'domainStartPage' => $this->domainStartPage
2403
        ];
2404
        // Include the template information if we shouldn't create a lock hash
2405
        if (!$createLockHashBase) {
2406
            $hashParameters['all'] = $this->all;
2407
        }
2408
        // Call hook to influence the hash calculation
2409
        $_params = [
2410
            'hashParameters' => &$hashParameters,
2411
            'createLockHashBase' => $createLockHashBase
2412
        ];
2413
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['createHashBase'] ?? [] as $_funcRef) {
2414
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2415
        }
2416
        return serialize($hashParameters);
2417
    }
2418
2419
    /**
2420
     * Checks if config-array exists already but if not, gets it
2421
     *
2422
     * @throws ServiceUnavailableException
2423
     */
2424
    public function getConfigArray()
2425
    {
2426
        // 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
2427
        if (empty($this->config) || is_array($this->config['INTincScript']) || $this->forceTemplateParsing) {
2428
            $timeTracker = $this->getTimeTracker();
2429
            $timeTracker->push('Parse template', '');
2430
            // Force parsing, if set?:
2431
            $this->tmpl->forceTemplateParsing = $this->forceTemplateParsing;
2432
            // Start parsing the TS template. Might return cached version.
2433
            $this->tmpl->start($this->rootLine);
2434
            $timeTracker->pull();
2435
            if ($this->tmpl->loaded) {
2436
                $timeTracker->push('Setting the config-array', '');
2437
                // toplevel - objArrayName
2438
                $this->sPre = $this->tmpl->setup['types.'][$this->type];
2439
                $this->pSetup = $this->tmpl->setup[$this->sPre . '.'];
2440
                if (!is_array($this->pSetup)) {
2441
                    $message = 'The page is not configured! [type=' . $this->type . '][' . $this->sPre . '].';
2442
                    if ($this->checkPageUnavailableHandler()) {
2443
                        $this->pageUnavailableAndExit($message);
2444
                    } else {
2445
                        $explanation = 'This means that there is no TypoScript object of type PAGE with typeNum=' . $this->type . ' configured.';
2446
                        $this->logger->alert($message);
2447
                        throw new ServiceUnavailableException($message . ' ' . $explanation, 1294587217);
2448
                    }
2449
                } else {
2450
                    if (!isset($this->config['config'])) {
2451
                        $this->config['config'] = [];
2452
                    }
2453
                    // Filling the config-array, first with the main "config." part
2454
                    if (is_array($this->tmpl->setup['config.'])) {
2455
                        ArrayUtility::mergeRecursiveWithOverrule($this->tmpl->setup['config.'], $this->config['config']);
2456
                        $this->config['config'] = $this->tmpl->setup['config.'];
2457
                    }
2458
                    // override it with the page/type-specific "config."
2459
                    if (is_array($this->pSetup['config.'])) {
2460
                        ArrayUtility::mergeRecursiveWithOverrule($this->config['config'], $this->pSetup['config.']);
2461
                    }
2462
                    // @deprecated since TYPO3 v9, can be removed in TYPO3 v10
2463
                    if ($this->config['config']['typolinkCheckRootline']) {
2464
                        $this->logDeprecatedTyposcript('config.typolinkCheckRootline', 'The functionality is always enabled since TYPO3 v9 and can be removed from your TypoScript code');
2465
                    }
2466
                    // Set default values for removeDefaultJS and inlineStyle2TempFile so CSS and JS are externalized if compatversion is higher than 4.0
2467
                    if (!isset($this->config['config']['removeDefaultJS'])) {
2468
                        $this->config['config']['removeDefaultJS'] = 'external';
2469
                    }
2470
                    if (!isset($this->config['config']['inlineStyle2TempFile'])) {
2471
                        $this->config['config']['inlineStyle2TempFile'] = 1;
2472
                    }
2473
2474
                    if (!isset($this->config['config']['compressJs'])) {
2475
                        $this->config['config']['compressJs'] = 0;
2476
                    }
2477
                    // Processing for the config_array:
2478
                    $this->config['rootLine'] = $this->tmpl->rootLine;
2479
                    // Class for render Header and Footer parts
2480
                    if ($this->pSetup['pageHeaderFooterTemplateFile']) {
2481
                        $file = $this->tmpl->getFileName($this->pSetup['pageHeaderFooterTemplateFile']);
2482
                        if ($file) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $file of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
2483
                            $this->pageRenderer->setTemplateFile($file);
2484
                        }
2485
                    }
2486
                }
2487
                $timeTracker->pull();
2488
            } else {
2489
                if ($this->checkPageUnavailableHandler()) {
2490
                    $this->pageUnavailableAndExit('No TypoScript template found!');
2491
                } else {
2492
                    $message = 'No TypoScript template found!';
2493
                    $this->logger->alert($message);
2494
                    throw new ServiceUnavailableException($message, 1294587218);
2495
                }
2496
            }
2497
        }
2498
2499
        // No cache
2500
        // Set $this->no_cache TRUE if the config.no_cache value is set!
2501
        if ($this->config['config']['no_cache']) {
2502
            $this->set_no_cache('config.no_cache is set');
2503
        }
2504
        // Merge GET with defaultGetVars
2505
        if (!empty($this->config['config']['defaultGetVars.'])) {
2506
            $modifiedGetVars = GeneralUtility::removeDotsFromTS($this->config['config']['defaultGetVars.']);
2507
            ArrayUtility::mergeRecursiveWithOverrule($modifiedGetVars, GeneralUtility::_GET());
0 ignored issues
show
Bug introduced by
It seems like TYPO3\CMS\Core\Utility\GeneralUtility::_GET() can also be of type string; however, parameter $overrule of TYPO3\CMS\Core\Utility\A...RecursiveWithOverrule() does only seem to accept array, 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

2507
            ArrayUtility::mergeRecursiveWithOverrule($modifiedGetVars, /** @scrutinizer ignore-type */ GeneralUtility::_GET());
Loading history...
2508
            GeneralUtility::_GETset($modifiedGetVars);
2509
        }
2510
        // Hook for postProcessing the configuration array
2511
        $params = ['config' => &$this->config['config']];
2512
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'] ?? [] as $funcRef) {
2513
            GeneralUtility::callUserFunction($funcRef, $params, $this);
2514
        }
2515
    }
2516
2517
    /********************************************
2518
     *
2519
     * Further initialization and data processing
2520
     *
2521
     *******************************************/
2522
2523
    /**
2524
     * Setting the language key that will be used by the current page.
2525
     * 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.
2526
     *
2527
     * @access private
2528
     */
2529
    public function settingLanguage()
2530
    {
2531
        $_params = [];
2532
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'] ?? [] as $_funcRef) {
2533
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2534
        }
2535
2536
        // Initialize charset settings etc.
2537
        $languageKey = $this->config['config']['language'] ?? 'default';
2538
        $this->lang = $languageKey;
2539
        $this->setOutputLanguage($languageKey);
2540
2541
        // Rendering charset of HTML page.
2542
        if (isset($this->config['config']['metaCharset']) && $this->config['config']['metaCharset'] !== 'utf-8') {
2543
            $this->metaCharset = $this->config['config']['metaCharset'];
2544
        }
2545
2546
        // Get values from TypoScript, if not set before
2547
        if ($this->sys_language_uid === 0) {
2548
            $this->sys_language_uid = ($this->sys_language_content = (int)$this->config['config']['sys_language_uid']);
2549
        }
2550
        list($this->sys_language_mode, $sys_language_content) = GeneralUtility::trimExplode(';', $this->config['config']['sys_language_mode']);
2551
        $this->sys_language_contentOL = $this->config['config']['sys_language_overlay'];
2552
        // If sys_language_uid is set to another language than default:
2553
        if ($this->sys_language_uid > 0) {
2554
            // check whether a shortcut is overwritten by a translated page
2555
            // we can only do this now, as this is the place where we get
2556
            // to know about translations
2557
            $this->checkTranslatedShortcut();
2558
            // Request the overlay record for the sys_language_uid:
2559
            $olRec = $this->sys_page->getPageOverlay($this->id, $this->sys_language_uid);
2560
            if (empty($olRec)) {
2561
                // If no OL record exists and a foreign language is asked for...
2562
                if ($this->sys_language_uid) {
2563
                    // If requested translation is not available:
2564
                    if (GeneralUtility::hideIfNotTranslated($this->page['l18n_cfg'])) {
2565
                        $this->pageNotFoundAndExit('Page is not available in the requested language.');
2566
                    } else {
2567
                        switch ((string)$this->sys_language_mode) {
2568
                            case 'strict':
2569
                                $this->pageNotFoundAndExit('Page is not available in the requested language (strict).');
2570
                                break;
2571
                            case 'content_fallback':
2572
                                // Setting content uid (but leaving the sys_language_uid) when a content_fallback
2573
                                // value was found.
2574
                                $fallBackOrder = GeneralUtility::trimExplode(',', $sys_language_content);
2575
                                foreach ($fallBackOrder as $orderValue) {
2576
                                    if ($orderValue === '0' || $orderValue === '') {
2577
                                        $this->sys_language_content = 0;
2578
                                        break;
2579
                                    }
2580
                                    if (MathUtility::canBeInterpretedAsInteger($orderValue) && !empty($this->sys_page->getPageOverlay($this->id, (int)$orderValue))) {
2581
                                        $this->sys_language_content = (int)$orderValue;
2582
                                        break;
2583
                                    }
2584
                                    if ($orderValue === 'pageNotFound') {
2585
                                        // The existing fallbacks have not been found, but instead of continuing
2586
                                        // page rendering with default language, a "page not found" message should be shown
2587
                                        // instead.
2588
                                        $this->pageNotFoundAndExit('Page is not available in the requested language (fallbacks did not apply).');
2589
                                    }
2590
                                }
2591
                                break;
2592
                            case 'ignore':
2593
                                $this->sys_language_content = $this->sys_language_uid;
2594
                                break;
2595
                            default:
2596
                                // Default is that everything defaults to the default language...
2597
                                $this->sys_language_uid = ($this->sys_language_content = 0);
2598
                        }
2599
                    }
2600
                }
2601
            } else {
2602
                // Setting sys_language if an overlay record was found (which it is only if a language is used)
2603
                $this->page = $this->sys_page->getPageOverlay($this->page, $this->sys_language_uid);
2604
            }
2605
        }
2606
        // Setting sys_language_uid inside sys-page:
2607
        $this->sys_page->sys_language_uid = $this->sys_language_uid;
2608
        // If default translation is not available:
2609
        if ((!$this->sys_language_uid || !$this->sys_language_content) && GeneralUtility::hideIfDefaultLanguage($this->page['l18n_cfg'])) {
2610
            $message = 'Page is not available in default language.';
2611
            $this->logger->error($message);
2612
            $this->pageNotFoundAndExit($message);
2613
        }
2614
        $this->updateRootLinesWithTranslations();
2615
2616
        // Finding the ISO code for the currently selected language
2617
        // fetched by the sys_language record when not fetching content from the default language
2618
        if ($this->sys_language_content > 0) {
2619
            // using sys_language_content because the ISO code only (currently) affect content selection from FlexForms - which should follow "sys_language_content"
2620
            // Set the fourth parameter to TRUE in the next two getRawRecord() calls to
2621
            // avoid versioning overlay to be applied as it generates an SQL error
2622
            $sys_language_row = $this->sys_page->getRawRecord('sys_language', $this->sys_language_content, 'language_isocode,static_lang_isocode');
2623
            if (is_array($sys_language_row) && !empty($sys_language_row['language_isocode'])) {
2624
                $this->sys_language_isocode = $sys_language_row['language_isocode'];
2625
            }
2626
            // the DB value is overridden by TypoScript
2627
            if (!empty($this->config['config']['sys_language_isocode'])) {
2628
                $this->sys_language_isocode = $this->config['config']['sys_language_isocode'];
2629
            }
2630
        } else {
2631
            // fallback to the TypoScript option when rendering with sys_language_uid=0
2632
            // also: use "en" by default
2633
            if (!empty($this->config['config']['sys_language_isocode_default'])) {
2634
                $this->sys_language_isocode = $this->config['config']['sys_language_isocode_default'];
2635
            } else {
2636
                $this->sys_language_isocode = $languageKey !== 'default' ? $languageKey : 'en';
2637
            }
2638
        }
2639
2640
        $_params = [];
2641
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'] ?? [] as $_funcRef) {
2642
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2643
        }
2644
    }
2645
2646
    /**
2647
     * Updating content of the two rootLines IF the language key is set!
2648
     */
2649
    protected function updateRootLinesWithTranslations()
2650
    {
2651
        if ($this->sys_language_uid) {
2652
            $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

2652
            $this->rootLine = $this->sys_page->getRootLine(/** @scrutinizer ignore-type */ $this->id, $this->MP);
Loading history...
2653
            $this->tmpl->updateRootlineData($this->rootLine);
2654
        }
2655
    }
2656
2657
    /**
2658
     * Setting locale for frontend rendering
2659
     */
2660
    public function settingLocale()
2661
    {
2662
        // Setting locale
2663
        if ($this->config['config']['locale_all']) {
2664
            $availableLocales = GeneralUtility::trimExplode(',', $this->config['config']['locale_all'], true);
2665
            // If LC_NUMERIC is set e.g. to 'de_DE' PHP parses float values locale-aware resulting in strings with comma
2666
            // as decimal point which causes problems with value conversions - so we set all locale types except LC_NUMERIC
2667
            // @see https://bugs.php.net/bug.php?id=53711
2668
            $locale = setlocale(LC_COLLATE, ...$availableLocales);
0 ignored issues
show
Bug introduced by
$availableLocales is expanded, but the parameter $locale of setlocale() does not expect variable arguments. ( Ignorable by Annotation )

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

2668
            $locale = setlocale(LC_COLLATE, /** @scrutinizer ignore-type */ ...$availableLocales);
Loading history...
2669
            if ($locale) {
2670
                // As str_* methods are locale aware and turkish has no upper case I
2671
                // Class autoloading and other checks depending on case changing break with turkish locale LC_CTYPE
2672
                // @see http://bugs.php.net/bug.php?id=35050
2673
                if (substr($this->config['config']['locale_all'], 0, 2) !== 'tr') {
2674
                    setlocale(LC_CTYPE, ...$availableLocales);
2675
                }
2676
                setlocale(LC_MONETARY, ...$availableLocales);
2677
                setlocale(LC_TIME, ...$availableLocales);
2678
            } else {
2679
                $this->getTimeTracker()->setTSlogMessage('Locale "' . htmlspecialchars($this->config['config']['locale_all']) . '" not found.', 3);
2680
            }
2681
        }
2682
    }
2683
2684
    /**
2685
     * Checks whether a translated shortcut page has a different shortcut
2686
     * target than the original language page.
2687
     * If that is the case, things get corrected to follow that alternative
2688
     * shortcut
2689
     */
2690
    protected function checkTranslatedShortcut()
2691
    {
2692
        if (!is_null($this->originalShortcutPage)) {
2693
            $originalShortcutPageOverlay = $this->sys_page->getPageOverlay($this->originalShortcutPage['uid'], $this->sys_language_uid);
2694
            if (!empty($originalShortcutPageOverlay['shortcut']) && $originalShortcutPageOverlay['shortcut'] != $this->id) {
2695
                // the translation of the original shortcut page has a different shortcut target!
2696
                // set the correct page and id
2697
                $shortcut = $this->getPageShortcut($originalShortcutPageOverlay['shortcut'], $originalShortcutPageOverlay['shortcut_mode'], $originalShortcutPageOverlay['uid']);
2698
                $this->id = ($this->contentPid = $shortcut['uid']);
2699
                $this->page = $this->sys_page->getPage($this->id);
2700
                // Fix various effects on things like menus f.e.
2701
                $this->fetch_the_id();
2702
                $this->tmpl->rootLine = array_reverse($this->rootLine);
2703
            }
2704
        }
2705
    }
2706
2707
    /**
2708
     * Handle data submission
2709
     * This is done at this point, because we need the config values
2710
     */
2711
    public function handleDataSubmission()
2712
    {
2713
        // Hook for processing data submission to extensions
2714
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission'] ?? [] as $className) {
2715
            $_procObj = GeneralUtility::makeInstance($className);
2716
            $_procObj->checkDataSubmission($this);
2717
        }
2718
    }
2719
2720
    /**
2721
     * Loops over all configured URL handlers and registers all active handlers in the redirect URL handler array.
2722
     *
2723
     * @see $activeRedirectUrlHandlers
2724
     */
2725
    public function initializeRedirectUrlHandlers()
2726
    {
2727
        $urlHandlers = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['urlProcessing']['urlHandlers'] ?? false;
2728
        if (!$urlHandlers) {
2729
            return;
2730
        }
2731
2732
        foreach ($urlHandlers as $identifier => $configuration) {
2733
            if (empty($configuration) || !is_array($configuration)) {
2734
                throw new \RuntimeException('Missing configuration for URL handler "' . $identifier . '".', 1442052263);
2735
            }
2736
            if (!is_string($configuration['handler']) || empty($configuration['handler']) || !class_exists($configuration['handler']) || !is_subclass_of($configuration['handler'], UrlHandlerInterface::class)) {
2737
                throw new \RuntimeException('The URL handler "' . $identifier . '" defines an invalid provider. Ensure the class exists and implements the "' . UrlHandlerInterface::class . '".', 1442052249);
2738
            }
2739
        }
2740
2741
        $orderedHandlers = GeneralUtility::makeInstance(DependencyOrderingService::class)->orderByDependencies($urlHandlers);
2742
2743
        foreach ($orderedHandlers as $configuration) {
2744
            /** @var UrlHandlerInterface $urlHandler */
2745
            $urlHandler = GeneralUtility::makeInstance($configuration['handler']);
2746
            if ($urlHandler->canHandleCurrentUrl()) {
2747
                $this->activeUrlHandlers[] = $urlHandler;
2748
            }
2749
        }
2750
    }
2751
2752
    /**
2753
     * Loops over all registered URL handlers and lets them process the current URL.
2754
     *
2755
     * If no handler has stopped the current process (e.g. by redirecting) and a
2756
     * the redirectUrl propert is not empty, the user will be redirected to this URL.
2757
     *
2758
     * @internal Should be called by the FrontendRequestHandler only.
2759
     */
2760
    public function redirectToExternalUrl()
2761
    {
2762
        foreach ($this->activeUrlHandlers as $redirectHandler) {
2763
            $redirectHandler->handle();
2764
        }
2765
2766
        if (!empty($this->activeUrlHandlers)) {
2767
            throw new \RuntimeException('A URL handler is active but did not process the URL.', 1442305505);
2768
        }
2769
    }
2770
2771
    /**
2772
     * Sets the URL_ID_TOKEN in the internal var, $this->getMethodUrlIdToken
2773
     * This feature allows sessions to use a GET-parameter instead of a cookie.
2774
     *
2775
     * @access private
2776
     */
2777
    public function setUrlIdToken()
2778
    {
2779
        if ($this->config['config']['ftu']) {
2780
            $this->getMethodUrlIdToken = $GLOBALS['TYPO3_CONF_VARS']['FE']['get_url_id_token'];
2781
        } else {
2782
            $this->getMethodUrlIdToken = '';
2783
        }
2784
    }
2785
2786
    /**
2787
     * Calculates and sets the internal linkVars based upon the current
2788
     * $_GET parameters and the setting "config.linkVars".
2789
     */
2790
    public function calculateLinkVars()
2791
    {
2792
        $this->linkVars = '';
2793
        if (empty($this->config['config']['linkVars'])) {
2794
            return;
2795
        }
2796
2797
        $linkVars = $this->splitLinkVarsString((string)$this->config['config']['linkVars']);
2798
2799
        if (empty($linkVars)) {
2800
            return;
2801
        }
2802
        $getData = GeneralUtility::_GET();
2803
        foreach ($linkVars as $linkVar) {
2804
            $test = $value = '';
2805
            if (preg_match('/^(.*)\\((.+)\\)$/', $linkVar, $match)) {
2806
                $linkVar = trim($match[1]);
2807
                $test = trim($match[2]);
2808
            }
2809
2810
            $keys = explode('|', $linkVar);
2811
            $numberOfLevels = count($keys);
2812
            $rootKey = trim($keys[0]);
2813
            if (!isset($getData[$rootKey])) {
2814
                continue;
2815
            }
2816
            $value = $getData[$rootKey];
2817
            for ($i = 1; $i < $numberOfLevels; $i++) {
2818
                $currentKey = trim($keys[$i]);
2819
                if (isset($value[$currentKey])) {
2820
                    $value = $value[$currentKey];
2821
                } else {
2822
                    $value = false;
2823
                    break;
2824
                }
2825
            }
2826
            if ($value !== false) {
2827
                $parameterName = $keys[0];
2828
                for ($i = 1; $i < $numberOfLevels; $i++) {
2829
                    $parameterName .= '[' . $keys[$i] . ']';
2830
                }
2831
                if (!is_array($value)) {
2832
                    $temp = rawurlencode($value);
2833
                    if ($test !== '' && !PageGenerator::isAllowedLinkVarValue($temp, $test)) {
2834
                        // Error: This value was not allowed for this key
2835
                        continue;
2836
                    }
2837
                    $value = '&' . $parameterName . '=' . $temp;
2838
                } else {
2839
                    if ($test !== '' && $test !== 'array') {
2840
                        // Error: This key must not be an array!
2841
                        continue;
2842
                    }
2843
                    $value = GeneralUtility::implodeArrayForUrl($parameterName, $value);
2844
                }
2845
                $this->linkVars .= $value;
2846
            }
2847
        }
2848
    }
2849
2850
    /**
2851
     * Split the link vars string by "," but not if the "," is inside of braces
2852
     *
2853
     * @param $string
2854
     *
2855
     * @return array
2856
     */
2857
    protected function splitLinkVarsString(string $string): array
2858
    {
2859
        $tempCommaReplacementString = '###KASPER###';
2860
2861
        // replace every "," wrapped in "()" by a "unique" string
2862
        $string = preg_replace_callback('/\((?>[^()]|(?R))*\)/', function ($result) use ($tempCommaReplacementString) {
2863
            return str_replace(',', $tempCommaReplacementString, $result[0]);
2864
        }, $string);
2865
2866
        $string = GeneralUtility::trimExplode(',', $string);
2867
2868
        // replace all "unique" strings back to ","
2869
        return str_replace($tempCommaReplacementString, ',', $string);
2870
    }
2871
2872
    /**
2873
     * Redirect to target page if the current page is an overlaid mountpoint.
2874
     *
2875
     * If the current page is of type mountpoint and should be overlaid with the contents of the mountpoint page
2876
     * and is accessed directly, the user will be redirected to the mountpoint context.
2877
     */
2878
    public function checkPageForMountpointRedirect()
2879
    {
2880
        if (!empty($this->originalMountPointPage) && $this->originalMountPointPage['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT) {
2881
            $this->redirectToCurrentPage();
2882
        }
2883
    }
2884
2885
    /**
2886
     * Redirect to target page, if the current page is a Shortcut.
2887
     *
2888
     * If the current page is of type shortcut and accessed directly via its URL, this function redirects to the
2889
     * Shortcut target using a Location header.
2890
     */
2891
    public function checkPageForShortcutRedirect()
2892
    {
2893
        if (!empty($this->originalShortcutPage) && $this->originalShortcutPage['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
2894
            $this->redirectToCurrentPage();
2895
        }
2896
    }
2897
2898
    /**
2899
     * Builds a typolink to the current page, appends the type paremeter if required
2900
     * and redirects the user to the generated URL using a Location header.
2901
     */
2902
    protected function redirectToCurrentPage()
2903
    {
2904
        $this->calculateLinkVars();
2905
        // Instantiate \TYPO3\CMS\Frontend\ContentObject to generate the correct target URL
2906
        /** @var $cObj ContentObjectRenderer */
2907
        $cObj = GeneralUtility::makeInstance(ContentObjectRenderer::class);
2908
        $parameter = $this->page['uid'];
2909
        $type = GeneralUtility::_GET('type');
2910
        if ($type && MathUtility::canBeInterpretedAsInteger($type)) {
2911
            $parameter .= ',' . $type;
2912
        }
2913
        $redirectUrl = $cObj->typoLink_URL(['parameter' => $parameter, 'addQueryString' => true,
2914
            'addQueryString.' => ['exclude' => 'id']]);
2915
2916
        // Prevent redirection loop
2917
        if (!empty($redirectUrl)) {
2918
            // redirect and exit
2919
            HttpUtility::redirect($redirectUrl, HttpUtility::HTTP_STATUS_307);
2920
        }
2921
    }
2922
2923
    /********************************************
2924
     *
2925
     * Page generation; cache handling
2926
     *
2927
     *******************************************/
2928
    /**
2929
     * Returns TRUE if the page should be generated.
2930
     * That is if no URL handler is active and the cacheContentFlag is not set.
2931
     *
2932
     * @return bool
2933
     */
2934
    public function isGeneratePage()
2935
    {
2936
        return !$this->cacheContentFlag && empty($this->activeUrlHandlers);
2937
    }
2938
2939
    /**
2940
     * Temp cache content
2941
     * 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.
2942
     */
2943
    public function tempPageCacheContent()
2944
    {
2945
        $this->tempContent = false;
2946
        if (!$this->no_cache) {
2947
            $seconds = 30;
2948
            $title = htmlspecialchars($this->tmpl->printTitle($this->page['title']));
2949
            $request_uri = htmlspecialchars(GeneralUtility::getIndpEnv('REQUEST_URI'));
2950
            $stdMsg = '
2951
		<strong>Page is being generated.</strong><br />
2952
		If this message does not disappear within ' . $seconds . ' seconds, please reload.';
2953
            $message = $this->config['config']['message_page_is_being_generated'];
2954
            if ((string)$message !== '') {
2955
                $message = str_replace('###TITLE###', $title, $message);
2956
                $message = str_replace('###REQUEST_URI###', $request_uri, $message);
2957
            } else {
2958
                $message = $stdMsg;
2959
            }
2960
            $temp_content = '<?xml version="1.0" encoding="UTF-8"?>
2961
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2962
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2963
<html xmlns="http://www.w3.org/1999/xhtml">
2964
	<head>
2965
		<title>' . $title . '</title>
2966
		<meta http-equiv="refresh" content="10" />
2967
	</head>
2968
	<body style="background-color:white; font-family:Verdana,Arial,Helvetica,sans-serif; color:#cccccc; text-align:center;">' . $message . '
2969
	</body>
2970
</html>';
2971
            // Fix 'nice errors' feature in modern browsers
2972
            $padSuffix = '<!--pad-->';
2973
            // prevent any trims
2974
            $padSize = 768 - strlen($padSuffix) - strlen($temp_content);
2975
            if ($padSize > 0) {
2976
                $temp_content = str_pad($temp_content, $padSize, LF) . $padSuffix;
2977
            }
2978
            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...
2979
                // 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.
2980
                // This is either the "Page is being generated" screen or it can be the final result.
2981
                // 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.
2982
                // 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...
2983
                $this->set_no_cache('Another process wrote into the cache since the beginning of the render process', true);
2984
2985
                // Since the new Locking API this should never be the case
2986
            } else {
2987
                $this->tempContent = true;
2988
                // This flag shows that temporary content is put in the cache
2989
                $this->setPageCacheContent($temp_content, $this->config, $GLOBALS['EXEC_TIME'] + $seconds);
2990
            }
2991
        }
2992
    }
2993
2994
    /**
2995
     * Set cache content to $this->content
2996
     */
2997
    public function realPageCacheContent()
2998
    {
2999
        // seconds until a cached page is too old
3000
        $cacheTimeout = $this->get_cache_timeout();
3001
        $timeOutTime = $GLOBALS['EXEC_TIME'] + $cacheTimeout;
3002
        $this->tempContent = false;
3003
        $usePageCache = true;
3004
        // Hook for deciding whether page cache should be written to the cache backend or not
3005
        // NOTE: as hooks are called in a loop, the last hook will have the final word (however each
3006
        // hook receives the current status of the $usePageCache flag)
3007
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['usePageCache'] ?? [] as $className) {
3008
            $_procObj = GeneralUtility::makeInstance($className);
3009
            $usePageCache = $_procObj->usePageCache($this, $usePageCache);
3010
        }
3011
        // Write the page to cache, if necessary
3012
        if ($usePageCache) {
3013
            $this->setPageCacheContent($this->content, $this->config, $timeOutTime);
3014
        }
3015
        // Hook for cache post processing (eg. writing static files!)
3016
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['insertPageIncache'] ?? [] as $className) {
3017
            $_procObj = GeneralUtility::makeInstance($className);
3018
            $_procObj->insertPageIncache($this, $timeOutTime);
3019
        }
3020
    }
3021
3022
    /**
3023
     * Sets cache content; Inserts the content string into the cache_pages cache.
3024
     *
3025
     * @param string $content The content to store in the HTML field of the cache table
3026
     * @param mixed $data The additional cache_data array, fx. $this->config
3027
     * @param int $expirationTstamp Expiration timestamp
3028
     * @see realPageCacheContent(), tempPageCacheContent()
3029
     */
3030
    public function setPageCacheContent($content, $data, $expirationTstamp)
3031
    {
3032
        $cacheData = [
3033
            'identifier' => $this->newHash,
3034
            'page_id' => $this->id,
3035
            'content' => $content,
3036
            'temp_content' => $this->tempContent,
3037
            'cache_data' => $data,
3038
            'expires' => $expirationTstamp,
3039
            'tstamp' => $GLOBALS['EXEC_TIME'],
3040
            'pageTitleInfo' => [
3041
                'title' => $this->page['title'],
3042
                'altPageTitle' => $this->altPageTitle,
3043
                'indexedDocTitle' => $this->indexedDocTitle
3044
            ]
3045
        ];
3046
        $this->cacheExpires = $expirationTstamp;
3047
        $this->pageCacheTags[] = 'pageId_' . $cacheData['page_id'];
3048
        if ($this->page_cache_reg1) {
3049
            $reg1 = (int)$this->page_cache_reg1;
3050
            $cacheData['reg1'] = $reg1;
3051
            $this->pageCacheTags[] = 'reg1_' . $reg1;
3052
        }
3053
        if (!empty($this->page['cache_tags'])) {
3054
            $tags = GeneralUtility::trimExplode(',', $this->page['cache_tags'], true);
3055
            $this->pageCacheTags = array_merge($this->pageCacheTags, $tags);
3056
        }
3057
        $this->pageCache->set($this->newHash, $cacheData, $this->pageCacheTags, $expirationTstamp - $GLOBALS['EXEC_TIME']);
3058
    }
3059
3060
    /**
3061
     * Clears cache content (for $this->newHash)
3062
     */
3063
    public function clearPageCacheContent()
3064
    {
3065
        $this->pageCache->remove($this->newHash);
3066
    }
3067
3068
    /**
3069
     * Clears cache content for a list of page ids
3070
     *
3071
     * @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)
3072
     */
3073
    public function clearPageCacheContent_pidList($pidList)
3074
    {
3075
        $pageIds = GeneralUtility::trimExplode(',', $pidList);
3076
        foreach ($pageIds as $pageId) {
3077
            $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

3077
            $this->pageCache->/** @scrutinizer ignore-call */ 
3078
                              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...
3078
        }
3079
    }
3080
3081
    /**
3082
     * Sets sys last changed
3083
     * 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.
3084
     *
3085
     * @see ContentObjectRenderer::lastChanged()
3086
     */
3087
    public function setSysLastChanged()
3088
    {
3089
        // Draft workspaces are always uid 1 or more. We do not update SYS_LASTCHANGED if we are browsing page from one of theses workspaces
3090
        if ((int)$this->whichWorkspace() < 1 && $this->page['SYS_LASTCHANGED'] < (int)$this->register['SYS_LASTCHANGED']) {
3091
            $connection = GeneralUtility::makeInstance(ConnectionPool::class)
3092
                ->getConnectionForTable('pages');
3093
            $connection->update(
3094
                'pages',
3095
                [
3096
                    'SYS_LASTCHANGED' => (int)$this->register['SYS_LASTCHANGED']
3097
                ],
3098
                [
3099
                    'uid' => (int)$this->id
3100
                ]
3101
            );
3102
        }
3103
    }
3104
3105
    /**
3106
     * Release pending locks
3107
     *
3108
     * @internal
3109
     */
3110
    public function releaseLocks()
3111
    {
3112
        $this->releaseLock('pagesection');
3113
        $this->releaseLock('pages');
3114
    }
3115
3116
    /**
3117
     * Adds tags to this page's cache entry, you can then f.e. remove cache
3118
     * entries by tag
3119
     *
3120
     * @param array $tags An array of tag
3121
     */
3122
    public function addCacheTags(array $tags)
3123
    {
3124
        $this->pageCacheTags = array_merge($this->pageCacheTags, $tags);
3125
    }
3126
3127
    /********************************************
3128
     *
3129
     * Page generation; rendering and inclusion
3130
     *
3131
     *******************************************/
3132
    /**
3133
     * Does some processing BEFORE the pagegen script is included.
3134
     */
3135
    public function generatePage_preProcessing()
3136
    {
3137
        // Same codeline as in getFromCache(). But $this->all has been changed by
3138
        // \TYPO3\CMS\Core\TypoScript\TemplateService::start() in the meantime, so this must be called again!
3139
        $this->newHash = $this->getHash();
3140
3141
        // If the pages_lock is set, we are in charge of generating the page.
3142
        if (is_object($this->locks['pages']['accessLock'])) {
3143
            // Here we put some temporary stuff in the cache in order to let the first hit generate the page.
3144
            // The temporary cache will expire after a few seconds (typ. 30) or will be cleared by the rendered page,
3145
            // which will also clear and rewrite the cache.
3146
            $this->tempPageCacheContent();
3147
        }
3148
        // At this point we have a valid pagesection_cache and also some temporary page_cache content,
3149
        // so let all other processes proceed now. (They are blocked at the pagessection_lock in getFromCache())
3150
        $this->releaseLock('pagesection');
3151
3152
        // Setting cache_timeout_default. May be overridden by PHP include scripts.
3153
        $this->cacheTimeOutDefault = (int)$this->config['config']['cache_period'];
3154
        // Page is generated
3155
        $this->no_cacheBeforePageGen = $this->no_cache;
3156
    }
3157
3158
    /**
3159
     * Previously located in static method in PageGenerator::init. Is solely used to set up TypoScript
3160
     * config. options and set properties in $TSFE for that.
3161
     */
3162
    public function preparePageContentGeneration()
3163
    {
3164
        if ($this->page['content_from_pid'] > 0) {
3165
            // make REAL copy of TSFE object - not reference!
3166
            $temp_copy_TSFE = clone $this;
3167
            // 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!
3168
            $temp_copy_TSFE->id = $this->page['content_from_pid'];
3169
            $temp_copy_TSFE->MP = '';
3170
            $temp_copy_TSFE->getPageAndRootlineWithDomain($this->config['config']['content_from_pid_allowOutsideDomain'] ? 0 : $this->domainStartPage);
3171
            $this->contentPid = (int)$temp_copy_TSFE->id;
3172
            unset($temp_copy_TSFE);
3173
        }
3174
        if ($this->config['config']['MP_defaults']) {
3175
            $temp_parts = GeneralUtility::trimExplode('|', $this->config['config']['MP_defaults'], true);
3176
            foreach ($temp_parts as $temp_p) {
3177
                list($temp_idP, $temp_MPp) = explode(':', $temp_p, 2);
3178
                $temp_ids = GeneralUtility::intExplode(',', $temp_idP);
3179
                foreach ($temp_ids as $temp_id) {
3180
                    $this->MP_defaults[$temp_id] = $temp_MPp;
3181
                }
3182
            }
3183
        }
3184
        // Global vars...
3185
        $this->indexedDocTitle = $this->page['title'];
3186
        $this->debug = !empty($this->config['config']['debug']);
3187
        // Base url:
3188
        if (isset($this->config['config']['baseURL'])) {
3189
            $this->baseUrl = $this->config['config']['baseURL'];
3190
        }
3191
        // Internal and External target defaults
3192
        $this->intTarget = '' . $this->config['config']['intTarget'];
3193
        $this->extTarget = '' . $this->config['config']['extTarget'];
3194
        $this->fileTarget = '' . $this->config['config']['fileTarget'];
3195
        if ($this->config['config']['spamProtectEmailAddresses'] === 'ascii') {
3196
            $this->spamProtectEmailAddresses = 'ascii';
3197
        } else {
3198
            $this->spamProtectEmailAddresses = MathUtility::forceIntegerInRange($this->config['config']['spamProtectEmailAddresses'], -10, 10, 0);
3199
        }
3200
        // calculate the absolute path prefix
3201
        if (!empty($this->config['config']['absRefPrefix'])) {
3202
            $absRefPrefix = trim($this->config['config']['absRefPrefix']);
3203
            if ($absRefPrefix === 'auto') {
3204
                $this->absRefPrefix = GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
3205
            } else {
3206
                $this->absRefPrefix = $absRefPrefix;
3207
            }
3208
        } else {
3209
            $this->absRefPrefix = '';
3210
        }
3211
        $this->lockFilePath = '' . $this->config['config']['lockFilePath'];
3212
        $this->lockFilePath = $this->lockFilePath ?: $GLOBALS['TYPO3_CONF_VARS']['BE']['fileadminDir'];
3213
        $this->ATagParams = trim($this->config['config']['ATagParams']) ? ' ' . trim($this->config['config']['ATagParams']) : '';
3214
        $this->initializeSearchWordDataInTsfe();
3215
        // linkVars
3216
        $this->calculateLinkVars();
3217
        // Setting XHTML-doctype from doctype
3218
        if (!$this->config['config']['xhtmlDoctype']) {
3219
            $this->config['config']['xhtmlDoctype'] = $this->config['config']['doctype'];
3220
        }
3221
        if ($this->config['config']['xhtmlDoctype']) {
3222
            $this->xhtmlDoctype = $this->config['config']['xhtmlDoctype'];
3223
            // Checking XHTML-docytpe
3224
            switch ((string)$this->config['config']['xhtmlDoctype']) {
3225
                case 'xhtml_trans':
3226
                case 'xhtml_strict':
3227
                    $this->xhtmlVersion = 100;
3228
                    break;
3229
                case 'xhtml_basic':
3230
                    $this->xhtmlVersion = 105;
3231
                    break;
3232
                case 'xhtml_11':
3233
                case 'xhtml+rdfa_10':
3234
                    $this->xhtmlVersion = 110;
3235
                    break;
3236
                default:
3237
                    $this->pageRenderer->setRenderXhtml(false);
3238
                    $this->xhtmlDoctype = '';
3239
                    $this->xhtmlVersion = 0;
3240
            }
3241
        } else {
3242
            $this->pageRenderer->setRenderXhtml(false);
3243
        }
3244
3245
        // Global content object
3246
        $this->newCObj();
3247
    }
3248
3249
    /**
3250
     * Fills the sWordList property and builds the regular expression in TSFE that can be used to split
3251
     * strings by the submitted search words.
3252
     *
3253
     * @see sWordList
3254
     * @see sWordRegEx
3255
     */
3256
    protected function initializeSearchWordDataInTsfe()
3257
    {
3258
        $this->sWordRegEx = '';
3259
        $this->sWordList = GeneralUtility::_GP('sword_list');
3260
        if (is_array($this->sWordList)) {
3261
            $space = !empty($this->config['config']['sword_standAlone']) ? '[[:space:]]' : '';
3262
            foreach ($this->sWordList as $val) {
3263
                if (trim($val) !== '') {
3264
                    $this->sWordRegEx .= $space . preg_quote($val, '/') . $space . '|';
3265
                }
3266
            }
3267
            $this->sWordRegEx = rtrim($this->sWordRegEx, '|');
3268
        }
3269
    }
3270
3271
    /**
3272
     * Does some processing AFTER the pagegen script is included.
3273
     * This includes caching the page, indexing the page (if configured) and setting sysLastChanged
3274
     */
3275
    public function generatePage_postProcessing()
3276
    {
3277
        // 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.
3278
        if ($this->no_cacheBeforePageGen) {
3279
            $this->set_no_cache('no_cache has been set before the page was generated - safety check', true);
3280
        }
3281
        // Hook for post-processing of page content cached/non-cached:
3282
        $_params = ['pObj' => &$this];
3283
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-all'] ?? [] as $_funcRef) {
3284
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
3285
        }
3286
        // Processing if caching is enabled:
3287
        if (!$this->no_cache) {
3288
            // Hook for post-processing of page content before being cached:
3289
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-cached'] ?? [] as $_funcRef) {
3290
                GeneralUtility::callUserFunction($_funcRef, $_params, $this);
3291
            }
3292
        }
3293
        // Convert char-set for output: (should be BEFORE indexing of the content (changed 22/4 2005)),
3294
        // because otherwise indexed search might convert from the wrong charset!
3295
        // One thing is that the charset mentioned in the HTML header would be wrong since the output charset (metaCharset)
3296
        // has not been converted to from utf-8. And indexed search will internally convert from metaCharset
3297
        // to utf-8 so the content MUST be in metaCharset already!
3298
        $this->content = $this->convOutputCharset($this->content);
3299
        // Hook for indexing pages
3300
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageIndexing'] ?? [] as $className) {
3301
            $_procObj = GeneralUtility::makeInstance($className);
3302
            $_procObj->hook_indexContent($this);
3303
        }
3304
        // Storing for cache:
3305
        if (!$this->no_cache) {
3306
            $this->realPageCacheContent();
3307
        } elseif ($this->tempContent) {
3308
            // 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)
3309
            $this->clearPageCacheContent();
3310
            $this->tempContent = false;
3311
        }
3312
        // Sets sys-last-change:
3313
        $this->setSysLastChanged();
3314
    }
3315
3316
    /**
3317
     * Generate the page title again as TSFE->altPageTitle might have been modified by an inc script
3318
     */
3319
    protected function regeneratePageTitle()
3320
    {
3321
        PageGenerator::generatePageTitle();
3322
    }
3323
3324
    /**
3325
     * Processes the INTinclude-scripts
3326
     */
3327
    public function INTincScript()
3328
    {
3329
        // Deprecated stuff:
3330
        // @deprecated: annotation added TYPO3 4.6
3331
        $this->additionalHeaderData = is_array($this->config['INTincScript_ext']['additionalHeaderData']) ? $this->config['INTincScript_ext']['additionalHeaderData'] : [];
3332
        $this->additionalFooterData = is_array($this->config['INTincScript_ext']['additionalFooterData']) ? $this->config['INTincScript_ext']['additionalFooterData'] : [];
3333
        $this->additionalJavaScript = $this->config['INTincScript_ext']['additionalJavaScript'];
3334
        $this->additionalCSS = $this->config['INTincScript_ext']['additionalCSS'];
3335
        $this->divSection = '';
3336
        if (empty($this->config['INTincScript_ext']['pageRenderer'])) {
3337
            $this->initPageRenderer();
3338
        } else {
3339
            /** @var PageRenderer $pageRenderer */
3340
            $pageRenderer = unserialize($this->config['INTincScript_ext']['pageRenderer']);
3341
            $this->pageRenderer = $pageRenderer;
3342
            GeneralUtility::setSingletonInstance(PageRenderer::class, $pageRenderer);
3343
        }
3344
3345
        $this->recursivelyReplaceIntPlaceholdersInContent();
3346
        $this->getTimeTracker()->push('Substitute header section');
3347
        $this->INTincScript_loadJSCode();
3348
        $this->regeneratePageTitle();
3349
3350
        $this->content = str_replace(
3351
            [
3352
                '<!--HD_' . $this->config['INTincScript_ext']['divKey'] . '-->',
3353
                '<!--FD_' . $this->config['INTincScript_ext']['divKey'] . '-->',
3354
                '<!--TDS_' . $this->config['INTincScript_ext']['divKey'] . '-->'
3355
            ],
3356
            [
3357
                $this->convOutputCharset(implode(LF, $this->additionalHeaderData)),
3358
                $this->convOutputCharset(implode(LF, $this->additionalFooterData)),
3359
                $this->convOutputCharset($this->divSection),
3360
            ],
3361
            $this->pageRenderer->renderJavaScriptAndCssForProcessingOfUncachedContentObjects($this->content, $this->config['INTincScript_ext']['divKey'])
3362
        );
3363
        // Replace again, because header and footer data and page renderer replacements may introduce additional placeholders (see #44825)
3364
        $this->recursivelyReplaceIntPlaceholdersInContent();
3365
        $this->setAbsRefPrefix();
3366
        $this->getTimeTracker()->pull();
3367
    }
3368
3369
    /**
3370
     * Replaces INT placeholders (COA_INT and USER_INT) in $this->content
3371
     * In case the replacement adds additional placeholders, it loops
3372
     * until no new placeholders are found any more.
3373
     */
3374
    protected function recursivelyReplaceIntPlaceholdersInContent()
3375
    {
3376
        do {
3377
            $INTiS_config = $this->config['INTincScript'];
3378
            $this->INTincScript_process($INTiS_config);
3379
            // Check if there were new items added to INTincScript during the previous execution:
3380
            $INTiS_config = array_diff_assoc($this->config['INTincScript'], $INTiS_config);
3381
            $reprocess = count($INTiS_config) > 0;
3382
        } while ($reprocess);
3383
    }
3384
3385
    /**
3386
     * Processes the INTinclude-scripts and substitue in content.
3387
     *
3388
     * @param array $INTiS_config $GLOBALS['TSFE']->config['INTincScript'] or part of it
3389
     * @see INTincScript()
3390
     */
3391
    protected function INTincScript_process($INTiS_config)
3392
    {
3393
        $timeTracker = $this->getTimeTracker();
3394
        $timeTracker->push('Split content');
3395
        // Splits content with the key.
3396
        $INTiS_splitC = explode('<!--INT_SCRIPT.', $this->content);
3397
        $this->content = '';
3398
        $timeTracker->setTSlogMessage('Parts: ' . count($INTiS_splitC));
3399
        $timeTracker->pull();
3400
        foreach ($INTiS_splitC as $INTiS_c => $INTiS_cPart) {
3401
            // If the split had a comment-end after 32 characters it's probably a split-string
3402
            if (substr($INTiS_cPart, 32, 3) === '-->') {
3403
                $INTiS_key = 'INT_SCRIPT.' . substr($INTiS_cPart, 0, 32);
0 ignored issues
show
Bug introduced by
Are you sure substr($INTiS_cPart, 0, 32) of type false|string can be used in concatenation? ( Ignorable by Annotation )

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

3403
                $INTiS_key = 'INT_SCRIPT.' . /** @scrutinizer ignore-type */ substr($INTiS_cPart, 0, 32);
Loading history...
3404
                if (is_array($INTiS_config[$INTiS_key])) {
3405
                    $label = 'Include ' . $INTiS_config[$INTiS_key]['type'];
3406
                    $label = $label . isset($INTiS_config[$INTiS_key]['file']) ? ' ' . $INTiS_config[$INTiS_key]['file'] : '';
3407
                    $timeTracker->push($label, '');
3408
                    $incContent = '';
3409
                    $INTiS_cObj = unserialize($INTiS_config[$INTiS_key]['cObj']);
3410
                    /* @var $INTiS_cObj ContentObjectRenderer */
3411
                    switch ($INTiS_config[$INTiS_key]['type']) {
3412
                        case 'COA':
3413
                            $incContent = $INTiS_cObj->cObjGetSingle('COA', $INTiS_config[$INTiS_key]['conf']);
3414
                            break;
3415
                        case 'FUNC':
3416
                            $incContent = $INTiS_cObj->cObjGetSingle('USER', $INTiS_config[$INTiS_key]['conf']);
3417
                            break;
3418
                        case 'POSTUSERFUNC':
3419
                            $incContent = $INTiS_cObj->callUserFunction($INTiS_config[$INTiS_key]['postUserFunc'], $INTiS_config[$INTiS_key]['conf'], $INTiS_config[$INTiS_key]['content']);
3420
                            break;
3421
                    }
3422
                    $this->content .= $this->convOutputCharset($incContent);
3423
                    $this->content .= substr($INTiS_cPart, 35);
3424
                    $timeTracker->pull($incContent);
3425
                } else {
3426
                    $this->content .= substr($INTiS_cPart, 35);
3427
                }
3428
            } else {
3429
                $this->content .= ($INTiS_c ? '<!--INT_SCRIPT.' : '') . $INTiS_cPart;
3430
            }
3431
        }
3432
    }
3433
3434
    /**
3435
     * Loads the JavaScript code for INTincScript
3436
     */
3437
    public function INTincScript_loadJSCode()
3438
    {
3439
        // Add javascript
3440
        $jsCode = trim($this->JSCode);
3441
        $additionalJavaScript = is_array($this->additionalJavaScript)
3442
            ? implode(LF, $this->additionalJavaScript)
3443
            : $this->additionalJavaScript;
3444
        $additionalJavaScript = trim($additionalJavaScript);
3445
        if ($jsCode !== '' || $additionalJavaScript !== '') {
3446
            $this->additionalHeaderData['JSCode'] = '
3447
<script type="text/javascript">
3448
	/*<![CDATA[*/
3449
<!--
3450
' . $additionalJavaScript . '
3451
' . $jsCode . '
3452
// -->
3453
	/*]]>*/
3454
</script>';
3455
        }
3456
        // Add CSS
3457
        $additionalCss = is_array($this->additionalCSS) ? implode(LF, $this->additionalCSS) : $this->additionalCSS;
3458
        $additionalCss = trim($additionalCss);
3459
        if ($additionalCss !== '') {
3460
            $this->additionalHeaderData['_CSS'] = '
3461
<style type="text/css">
3462
' . $additionalCss . '
3463
</style>';
3464
        }
3465
    }
3466
3467
    /**
3468
     * Determines if there are any INTincScripts to include.
3469
     *
3470
     * @return bool Returns TRUE if scripts are found and no URL handler is active.
3471
     */
3472
    public function isINTincScript()
3473
    {
3474
        return is_array($this->config['INTincScript']) && empty($this->activeUrlHandlers);
3475
    }
3476
3477
    /********************************************
3478
     *
3479
     * Finished off; outputting, storing session data, statistics...
3480
     *
3481
     *******************************************/
3482
    /**
3483
     * Determines if content should be outputted.
3484
     * Outputting content is done only if no URL handler is active and no hook disables the output.
3485
     *
3486
     * @return bool Returns TRUE if no redirect URL is set and no hook disables the output.
3487
     */
3488
    public function isOutputting()
3489
    {
3490
        // Initialize by status if there is a Redirect URL
3491
        $enableOutput = empty($this->activeUrlHandlers);
3492
        // Call hook for possible disabling of output:
3493
        $_params = ['pObj' => &$this, 'enableOutput' => &$enableOutput];
3494
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['isOutputting'] ?? [] as $_funcRef) {
3495
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
3496
        }
3497
        return $enableOutput;
3498
    }
3499
3500
    /**
3501
     * Process the output before it's actually outputted. Sends headers also.
3502
     *
3503
     * This includes substituting the "username" comment, sending additional headers
3504
     * (as defined in the TypoScript "config.additionalheaders" object), XHTML cleaning content (if configured)
3505
     * Works on $this->content.
3506
     */
3507
    public function processOutput()
3508
    {
3509
        // Set header for charset-encoding unless disabled
3510 View Code Duplication
        if (empty($this->config['config']['disableCharsetHeader'])) {
3511
            $headLine = 'Content-Type: ' . $this->contentType . '; charset=' . trim($this->metaCharset);
3512
            header($headLine);
3513
        }
3514
        // Set header for content language unless disabled
3515 View Code Duplication
        if (empty($this->config['config']['disableLanguageHeader']) && !empty($this->sys_language_isocode)) {
3516
            $headLine = 'Content-Language: ' . trim($this->sys_language_isocode);
3517
            header($headLine);
3518
        }
3519
        // Set cache related headers to client (used to enable proxy / client caching!)
3520
        if (!empty($this->config['config']['sendCacheHeaders'])) {
3521
            $this->sendCacheHeaders();
3522
        }
3523
        // Set headers, if any
3524
        $this->sendAdditionalHeaders();
3525
        // Send appropriate status code in case of temporary content
3526
        if ($this->tempContent) {
3527
            $this->addTempContentHttpHeaders();
3528
        }
3529
        // Make substitution of eg. username/uid in content only if cache-headers for client/proxy caching is NOT sent!
3530
        if (!$this->isClientCachable) {
3531
            $this->contentStrReplace();
3532
        }
3533
        // Hook for post-processing of page content before output:
3534
        $_params = ['pObj' => &$this];
3535
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['contentPostProc-output'] ?? [] as $_funcRef) {
3536
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
3537
        }
3538
    }
3539
3540
    /**
3541
     * Send cache headers good for client/reverse proxy caching
3542
     * This function should not be called if the page content is
3543
     * temporary (like for "Page is being generated..." message,
3544
     * but in that case it is ok because the config-variables
3545
     * are not yet available and so will not allow to send
3546
     * cache headers)
3547
     */
3548
    public function sendCacheHeaders()
3549
    {
3550
        // Getting status whether we can send cache control headers for proxy caching:
3551
        $doCache = $this->isStaticCacheble();
3552
        // 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...
3553
        $loginsDeniedCfg = empty($this->config['config']['sendCacheHeaders_onlyWhenLoginDeniedInBranch']) || empty($this->loginAllowedInBranch);
3554
        // Finally, when backend users are logged in, do not send cache headers at all (Admin Panel might be displayed for instance).
3555
        if ($doCache && !$this->beUserLogin && !$this->doWorkspacePreview() && $loginsDeniedCfg) {
3556
            // Build headers:
3557
            $headers = [
3558
                'Expires: ' . gmdate('D, d M Y H:i:s T', $this->cacheExpires),
0 ignored issues
show
Bug introduced by
Are you sure gmdate('D, d M Y H:i:s T', $this->cacheExpires) of type false|string can be used in concatenation? ( Ignorable by Annotation )

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

3558
                'Expires: ' . /** @scrutinizer ignore-type */ gmdate('D, d M Y H:i:s T', $this->cacheExpires),
Loading history...
3559
                'ETag: "' . md5($this->content) . '"',
3560
                'Cache-Control: max-age=' . ($this->cacheExpires - $GLOBALS['EXEC_TIME']),
3561
                // no-cache
3562
                'Pragma: public'
3563
            ];
3564
            $this->isClientCachable = true;
3565
        } else {
3566
            // Build headers
3567
            // "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
3568
            $headers = [
3569
                'Cache-Control: private, no-store'
3570
            ];
3571
            $this->isClientCachable = false;
3572
            // Now, if a backend user is logged in, tell him in the Admin Panel log what the caching status would have been:
3573
            if ($this->beUserLogin) {
3574
                if ($doCache) {
3575
                    $this->getTimeTracker()->setTSlogMessage('Cache-headers with max-age "' . ($this->cacheExpires - $GLOBALS['EXEC_TIME']) . '" would have been sent');
3576
                } else {
3577
                    $reasonMsg = '';
3578
                    $reasonMsg .= !$this->no_cache ? '' : 'Caching disabled (no_cache). ';
3579
                    $reasonMsg .= !$this->isINTincScript() ? '' : '*_INT object(s) on page. ';
3580
                    $reasonMsg .= !is_array($this->fe_user->user) ? '' : 'Frontend user logged in. ';
3581
                    $this->getTimeTracker()->setTSlogMessage('Cache-headers would disable proxy caching! Reason(s): "' . $reasonMsg . '"', 1);
3582
                }
3583
            }
3584
        }
3585
        // Send headers:
3586
        foreach ($headers as $hL) {
3587
            header($hL);
3588
        }
3589
    }
3590
3591
    /**
3592
     * Reporting status whether we can send cache control headers for proxy caching or publishing to static files
3593
     *
3594
     * Rules are:
3595
     * no_cache cannot be set: If it is, the page might contain dynamic content and should never be cached.
3596
     * There can be no USER_INT objects on the page ("isINTincScript()") because they implicitly indicate dynamic content
3597
     * 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)
3598
     *
3599
     * @return bool
3600
     */
3601
    public function isStaticCacheble()
3602
    {
3603
        $doCache = !$this->no_cache && !$this->isINTincScript() && !$this->isUserOrGroupSet();
3604
        return $doCache;
3605
    }
3606
3607
    /**
3608
     * Substitute various tokens in content. This should happen only if the content is not cached by proxies or client browsers.
3609
     */
3610
    public function contentStrReplace()
3611
    {
3612
        $search = [];
3613
        $replace = [];
3614
        // Substitutes username mark with the username
3615
        if (!empty($this->fe_user->user['uid'])) {
3616
            // User name:
3617
            $token = isset($this->config['config']['USERNAME_substToken']) ? trim($this->config['config']['USERNAME_substToken']) : '';
3618
            $search[] = $token ? $token : '<!--###USERNAME###-->';
3619
            $replace[] = $this->fe_user->user['username'];
3620
            // User uid (if configured):
3621
            $token = isset($this->config['config']['USERUID_substToken']) ? trim($this->config['config']['USERUID_substToken']) : '';
3622
            if ($token) {
3623
                $search[] = $token;
3624
                $replace[] = $this->fe_user->user['uid'];
3625
            }
3626
        }
3627
        // Substitutes get_URL_ID in case of GET-fallback
3628
        if ($this->getMethodUrlIdToken) {
3629
            $search[] = $this->getMethodUrlIdToken;
3630
            $replace[] = $this->fe_user->get_URL_ID;
3631
        }
3632
        // Hook for supplying custom search/replace data
3633
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-contentStrReplace'] ?? [] as $_funcRef) {
3634
            $_params = [
3635
                'search' => &$search,
3636
                'replace' => &$replace
3637
            ];
3638
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
3639
        }
3640
        if (!empty($search)) {
3641
            $this->content = str_replace($search, $replace, $this->content);
3642
        }
3643
    }
3644
3645
    /**
3646
     * Stores session data for the front end user
3647
     */
3648
    public function storeSessionData()
3649
    {
3650
        $this->fe_user->storeSessionData();
3651
    }
3652
3653
    /**
3654
     * Outputs preview info.
3655
     */
3656
    public function previewInfo()
3657
    {
3658
        if ($this->fePreview !== 0) {
3659
            $previewInfo = '';
3660
            $_params = ['pObj' => &$this];
3661
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_previewInfo'] ?? [] as $_funcRef) {
3662
                $previewInfo .= GeneralUtility::callUserFunction($_funcRef, $_params, $this);
3663
            }
3664
            $this->content = str_ireplace('</body>', $previewInfo . '</body>', $this->content);
3665
        }
3666
    }
3667
3668
    /**
3669
     * End-Of-Frontend hook
3670
     */
3671
    public function hook_eofe()
3672
    {
3673
        $_params = ['pObj' => &$this];
3674
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_eofe'] ?? [] as $_funcRef) {
3675
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
3676
        }
3677
    }
3678
3679
    /**
3680
     * Sends HTTP headers for temporary content. These headers prevent search engines from caching temporary content and asks them to revisit this page again.
3681
     */
3682
    public function addTempContentHttpHeaders()
3683
    {
3684
        header('HTTP/1.0 503 Service unavailable');
3685
        header('Retry-after: 3600');
3686
        header('Pragma: no-cache');
3687
        header('Cache-control: no-cache');
3688
        header('Expire: 0');
3689
    }
3690
3691
    /********************************************
3692
     *
3693
     * Various internal API functions
3694
     *
3695
     *******************************************/
3696
3697
    /**
3698
     * Creates an instance of ContentObjectRenderer in $this->cObj
3699
     * This instance is used to start the rendering of the TypoScript template structure
3700
     *
3701
     * @see pagegen.php
3702
     */
3703
    public function newCObj()
3704
    {
3705
        $this->cObj = GeneralUtility::makeInstance(ContentObjectRenderer::class);
3706
        $this->cObj->start($this->page, 'pages');
3707
    }
3708
3709
    /**
3710
     * Converts relative paths in the HTML source to absolute paths for fileadmin/, typo3conf/ext/ and media/ folders.
3711
     *
3712
     * @access private
3713
     * @see pagegen.php, INTincScript()
3714
     */
3715
    public function setAbsRefPrefix()
3716
    {
3717
        if (!$this->absRefPrefix) {
3718
            return;
3719
        }
3720
        $search = [
3721
            '"typo3temp/',
3722
            '"typo3conf/ext/',
3723
            '"' . TYPO3_mainDir . 'ext/',
3724
            '"' . TYPO3_mainDir . 'sysext/'
3725
        ];
3726
        $replace = [
3727
            '"' . $this->absRefPrefix . 'typo3temp/',
3728
            '"' . $this->absRefPrefix . 'typo3conf/ext/',
3729
            '"' . $this->absRefPrefix . TYPO3_mainDir . 'ext/',
3730
            '"' . $this->absRefPrefix . TYPO3_mainDir . 'sysext/'
3731
        ];
3732
        /** @var $storageRepository StorageRepository */
3733
        $storageRepository = GeneralUtility::makeInstance(StorageRepository::class);
3734
        $storages = $storageRepository->findAll();
3735
        foreach ($storages as $storage) {
3736
            if ($storage->getDriverType() === 'Local' && $storage->isPublic() && $storage->isOnline()) {
3737
                $folder = $storage->getPublicUrl($storage->getRootLevelFolder(), true);
3738
                $search[] = '"' . $folder;
3739
                $replace[] = '"' . $this->absRefPrefix . $folder;
3740
            }
3741
        }
3742
        // Process additional directories
3743
        $directories = GeneralUtility::trimExplode(',', $GLOBALS['TYPO3_CONF_VARS']['FE']['additionalAbsRefPrefixDirectories'], true);
3744
        foreach ($directories as $directory) {
3745
            $search[] = '"' . $directory;
3746
            $replace[] = '"' . $this->absRefPrefix . $directory;
3747
        }
3748
        $this->content = str_replace(
3749
            $search,
3750
            $replace,
3751
            $this->content
3752
        );
3753
    }
3754
3755
    /**
3756
     * Prefixing the input URL with ->baseUrl If ->baseUrl is set and the input url is not absolute in some way.
3757
     * 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!
3758
     *
3759
     * @param string $url Input URL, relative or absolute
3760
     * @return string Processed input value.
3761
     */
3762
    public function baseUrlWrap($url)
3763
    {
3764
        if ($this->baseUrl) {
3765
            $urlParts = parse_url($url);
3766
            if (empty($urlParts['scheme']) && $url[0] !== '/') {
3767
                $url = $this->baseUrl . $url;
3768
            }
3769
        }
3770
        return $url;
3771
    }
3772
3773
    /**
3774
     * Logs access to deprecated TypoScript objects and properties.
3775
     *
3776
     * Dumps message to the TypoScript message log (admin panel) and the TYPO3 deprecation log.
3777
     *
3778
     * @param string $typoScriptProperty Deprecated object or property
3779
     * @param string $explanation Message or additional information
3780
     */
3781
    public function logDeprecatedTyposcript($typoScriptProperty, $explanation = '')
3782
    {
3783
        $explanationText = $explanation !== '' ? ' - ' . $explanation : '';
3784
        $this->getTimeTracker()->setTSlogMessage($typoScriptProperty . ' is deprecated.' . $explanationText, 2);
3785
        trigger_error('TypoScript property ' . $typoScriptProperty . ' is deprecated' . $explanationText, E_USER_DEPRECATED);
3786
    }
3787
3788
    /********************************************
3789
     * PUBLIC ACCESSIBLE WORKSPACES FUNCTIONS
3790
     *******************************************/
3791
3792
    /**
3793
     * Returns TRUE if workspace preview is enabled
3794
     *
3795
     * @return bool Returns TRUE if workspace preview is enabled
3796
     */
3797
    public function doWorkspacePreview()
3798
    {
3799
        return $this->workspacePreview !== 0;
3800
    }
3801
3802
    /**
3803
     * Returns the uid of the current workspace
3804
     *
3805
     * @return int|null returns workspace integer for which workspace is being preview. NULL if none.
3806
     */
3807
    public function whichWorkspace()
3808
    {
3809
        $ws = null;
3810
        if ($this->doWorkspacePreview()) {
3811
            $ws = (int)$this->workspacePreview;
3812
        } elseif ($this->beUserLogin) {
3813
            $ws = $this->getBackendUser()->workspace;
3814
        }
3815
        return $ws;
3816
    }
3817
3818
    /********************************************
3819
     *
3820
     * Various external API functions - for use in plugins etc.
3821
     *
3822
     *******************************************/
3823
3824
    /**
3825
     * Returns the pages TSconfig array based on the currect ->rootLine
3826
     *
3827
     * @return array
3828
     */
3829
    public function getPagesTSconfig()
3830
    {
3831
        if (!is_array($this->pagesTSconfig)) {
3832
            $TSdataArray = [];
3833
            foreach ($this->rootLine as $k => $v) {
3834
                if (trim($v['tsconfig_includes'])) {
3835
                    $includeTsConfigFileList = GeneralUtility::trimExplode(',', $v['tsconfig_includes'], true);
3836
                    // Traversing list
3837
                    foreach ($includeTsConfigFileList as $key => $includeTsConfigFile) {
3838
                        if (strpos($includeTsConfigFile, 'EXT:') === 0) {
3839
                            list($includeTsConfigFileExtensionKey, $includeTsConfigFilename) = explode(
3840
                                '/',
3841
                                substr($includeTsConfigFile, 4),
3842
                                2
3843
                            );
3844
                            if ((string)$includeTsConfigFileExtensionKey !== ''
3845
                                && (string)$includeTsConfigFilename !== ''
3846
                                && ExtensionManagementUtility::isLoaded($includeTsConfigFileExtensionKey)
3847
                            ) {
3848
                                $includeTsConfigFileAndPath = ExtensionManagementUtility::extPath($includeTsConfigFileExtensionKey)
3849
                                    . $includeTsConfigFilename;
3850
                                if (file_exists($includeTsConfigFileAndPath)) {
3851
                                    $TSdataArray[] = file_get_contents($includeTsConfigFileAndPath);
3852
                                }
3853
                            }
3854
                        }
3855
                    }
3856
                }
3857
                $TSdataArray[] = $v['TSconfig'];
3858
            }
3859
            // Adding the default configuration:
3860
            $TSdataArray[] = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];
3861
            // Bring everything in the right order. Default first, then the Rootline down to the current page
3862
            $TSdataArray = array_reverse($TSdataArray);
3863
            // Parsing the user TS (or getting from cache)
3864
            $TSdataArray = TypoScriptParser::checkIncludeLines_array($TSdataArray);
3865
            $userTS = implode(LF . '[GLOBAL]' . LF, $TSdataArray);
3866
            $identifier = md5('pageTS:' . $userTS);
3867
            $contentHashCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_hash');
3868
            $this->pagesTSconfig = $contentHashCache->get($identifier);
3869 View Code Duplication
            if (!is_array($this->pagesTSconfig)) {
3870
                $parseObj = GeneralUtility::makeInstance(TypoScriptParser::class);
3871
                $parseObj->parse($userTS);
3872
                $this->pagesTSconfig = $parseObj->setup;
3873
                $contentHashCache->set($identifier, $this->pagesTSconfig, ['PAGES_TSconfig'], 0);
3874
            }
3875
        }
3876
        return $this->pagesTSconfig;
3877
    }
3878
3879
    /**
3880
     * Sets JavaScript code in the additionalJavaScript array
3881
     *
3882
     * @param string $key is the key in the array, for num-key let the value be empty. Note reserved keys 'openPic' and 'mouseOver'
3883
     * @param string $content is the content if you want any
3884
     * @see \TYPO3\CMS\Frontend\ContentObject\Menu\GraphicalMenuContentObject::writeMenu(), ContentObjectRenderer::imageLinkWrap()
3885
     */
3886
    public function setJS($key, $content = '')
3887
    {
3888
        if ($key) {
3889
            switch ($key) {
3890
                case 'mouseOver':
3891
                    $this->additionalJavaScript[$key] = '		// JS function for mouse-over
3892
		function over(name, imgObj) {	//
3893
			if (document[name]) {document[name].src = eval(name+"_h.src");}
3894
			else if (document.getElementById && document.getElementById(name)) {document.getElementById(name).src = eval(name+"_h.src");}
3895
			else if (imgObj)	{imgObj.src = eval(name+"_h.src");}
3896
		}
3897
			// JS function for mouse-out
3898
		function out(name, imgObj) {	//
3899
			if (document[name]) {document[name].src = eval(name+"_n.src");}
3900
			else if (document.getElementById && document.getElementById(name)) {document.getElementById(name).src = eval(name+"_n.src");}
3901
			else if (imgObj)	{imgObj.src = eval(name+"_n.src");}
3902
		}';
3903
                    break;
3904
                case 'openPic':
3905
                    $this->additionalJavaScript[$key] = '	function openPic(url, winName, winParams) {	//
3906
			var theWindow = window.open(url, winName, winParams);
3907
			if (theWindow)	{theWindow.focus();}
3908
		}';
3909
                    break;
3910
                default:
3911
                    $this->additionalJavaScript[$key] = $content;
3912
            }
3913
        }
3914
    }
3915
3916
    /**
3917
     * Sets CSS data in the additionalCSS array
3918
     *
3919
     * @param string $key Is the key in the array, for num-key let the value be empty
3920
     * @param string $content Is the content if you want any
3921
     * @see setJS()
3922
     */
3923
    public function setCSS($key, $content)
3924
    {
3925
        if ($key) {
3926
            $this->additionalCSS[$key] = $content;
3927
        }
3928
    }
3929
3930
    /**
3931
     * Returns a unique md5 hash.
3932
     * 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.
3933
     *
3934
     * @param string $str Some string to include in what is hashed. Not significant at all.
3935
     * @return string MD5 hash of ->uniqueString, input string and uniqueCounter
3936
     */
3937
    public function uniqueHash($str = '')
3938
    {
3939
        return md5($this->uniqueString . '_' . $str . $this->uniqueCounter++);
3940
    }
3941
3942
    /**
3943
     * Sets the cache-flag to 1. Could be called from user-included php-files in order to ensure that a page is not cached.
3944
     *
3945
     * @param string $reason An optional reason to be written to the log.
3946
     * @param bool $internal Whether the call is done from core itself (should only be used by core).
3947
     */
3948
    public function set_no_cache($reason = '', $internal = false)
3949
    {
3950
        if ($reason !== '') {
3951
            $warning = '$TSFE->set_no_cache() was triggered. Reason: ' . $reason . '.';
3952
        } else {
3953
            $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
3954
            // This is a hack to work around ___FILE___ resolving symbolic links
3955
            $PATH_site_real = dirname(realpath(PATH_site . 'typo3')) . '/';
0 ignored issues
show
Bug introduced by
It seems like realpath(TYPO3\CMS\Front...er\PATH_site . 'typo3') can also be of type false; however, parameter $path of dirname() 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

3955
            $PATH_site_real = dirname(/** @scrutinizer ignore-type */ realpath(PATH_site . 'typo3')) . '/';
Loading history...
3956
            $file = $trace[0]['file'];
3957
            if (strpos($file, $PATH_site_real) === 0) {
3958
                $file = str_replace($PATH_site_real, '', $file);
3959
            } else {
3960
                $file = str_replace(PATH_site, '', $file);
3961
            }
3962
            $line = $trace[0]['line'];
3963
            $trigger = $file . ' on line ' . $line;
3964
            $warning = '$GLOBALS[\'TSFE\']->set_no_cache() was triggered by ' . $trigger . '.';
3965
        }
3966
        if ($GLOBALS['TYPO3_CONF_VARS']['FE']['disableNoCacheParameter']) {
3967
            $warning .= ' However, $TYPO3_CONF_VARS[\'FE\'][\'disableNoCacheParameter\'] is set, so it will be ignored!';
3968
            $this->getTimeTracker()->setTSlogMessage($warning, 2);
3969
        } else {
3970
            $warning .= ' Caching is disabled!';
3971
            $this->disableCache();
3972
        }
3973
        if ($internal && isset($GLOBALS['BE_USER'])) {
3974
            $this->logger->notice($warning);
3975
        } else {
3976
            $this->logger->warning($warning);
3977
        }
3978
    }
3979
3980
    /**
3981
     * Disables caching of the current page.
3982
     *
3983
     * @internal
3984
     */
3985
    protected function disableCache()
3986
    {
3987
        $this->no_cache = true;
3988
    }
3989
3990
    /**
3991
     * Sets the cache-timeout in seconds
3992
     *
3993
     * @param int $seconds Cache-timeout in seconds
3994
     */
3995
    public function set_cache_timeout_default($seconds)
3996
    {
3997
        $this->cacheTimeOutDefault = (int)$seconds;
3998
    }
3999
4000
    /**
4001
     * Get the cache timeout for the current page.
4002
     *
4003
     * @return int The cache timeout for the current page.
4004
     */
4005
    public function get_cache_timeout()
4006
    {
4007
        /** @var $runtimeCache \TYPO3\CMS\Core\Cache\Frontend\AbstractFrontend */
4008
        $runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_runtime');
4009
        $cachedCacheLifetimeIdentifier = 'core-tslib_fe-get_cache_timeout';
4010
        $cachedCacheLifetime = $runtimeCache->get($cachedCacheLifetimeIdentifier);
4011
        if ($cachedCacheLifetime === false) {
4012
            if ($this->page['cache_timeout']) {
4013
                // Cache period was set for the page:
4014
                $cacheTimeout = $this->page['cache_timeout'];
4015
            } elseif ($this->cacheTimeOutDefault) {
4016
                // Cache period was set for the whole site:
4017
                $cacheTimeout = $this->cacheTimeOutDefault;
4018
            } else {
4019
                // No cache period set at all, so we take one day (60*60*24 seconds = 86400 seconds):
4020
                $cacheTimeout = 86400;
4021
            }
4022
            if ($this->config['config']['cache_clearAtMidnight']) {
4023
                $timeOutTime = $GLOBALS['EXEC_TIME'] + $cacheTimeout;
4024
                $midnightTime = mktime(0, 0, 0, date('m', $timeOutTime), date('d', $timeOutTime), date('Y', $timeOutTime));
0 ignored issues
show
Bug introduced by
date('m', $timeOutTime) of type false|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

4024
                $midnightTime = mktime(0, 0, 0, /** @scrutinizer ignore-type */ date('m', $timeOutTime), date('d', $timeOutTime), date('Y', $timeOutTime));
Loading history...
Bug introduced by
date('d', $timeOutTime) of type false|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

4024
                $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 false|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

4024
                $midnightTime = mktime(0, 0, 0, date('m', $timeOutTime), date('d', $timeOutTime), /** @scrutinizer ignore-type */ date('Y', $timeOutTime));
Loading history...
4025
                // If the midnight time of the expire-day is greater than the current time,
4026
                // we may set the timeOutTime to the new midnighttime.
4027
                if ($midnightTime > $GLOBALS['EXEC_TIME']) {
4028
                    $cacheTimeout = $midnightTime - $GLOBALS['EXEC_TIME'];
4029
                }
4030
            }
4031
4032
            // Calculate the timeout time for records on the page and adjust cache timeout if necessary
4033
            $cacheTimeout = min($this->calculatePageCacheTimeout(), $cacheTimeout);
4034
4035
            foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['get_cache_timeout'] ?? [] as $_funcRef) {
4036
                $params = ['cacheTimeout' => $cacheTimeout];
4037
                $cacheTimeout = GeneralUtility::callUserFunction($_funcRef, $params, $this);
4038
            }
4039
            $runtimeCache->set($cachedCacheLifetimeIdentifier, $cacheTimeout);
4040
            $cachedCacheLifetime = $cacheTimeout;
4041
        }
4042
        return $cachedCacheLifetime;
4043
    }
4044
4045
    /**
4046
     * Returns a unique id to be used as a XML ID (in HTML / XHTML mode)
4047
     *
4048
     * @param string $desired The desired id. If already used it is suffixed with a number
4049
     * @return string The unique id
4050
     */
4051
    public function getUniqueId($desired = '')
4052
    {
4053
        if ($desired === '') {
4054
            // id has to start with a letter to reach XHTML compliance
4055
            $uniqueId = 'a' . $this->uniqueHash();
4056
        } else {
4057
            $uniqueId = $desired;
4058
            for ($i = 1; isset($this->usedUniqueIds[$uniqueId]); $i++) {
4059
                $uniqueId = $desired . '_' . $i;
4060
            }
4061
        }
4062
        $this->usedUniqueIds[$uniqueId] = true;
4063
        return $uniqueId;
4064
    }
4065
4066
    /*********************************************
4067
     *
4068
     * Localization and character set conversion
4069
     *
4070
     *********************************************/
4071
    /**
4072
     * Split Label function for front-end applications.
4073
     *
4074
     * @param string $input Key string. Accepts the "LLL:" prefix.
4075
     * @return string Label value, if any.
4076
     */
4077
    public function sL($input)
4078
    {
4079
        return $this->languageService->sL($input);
4080
    }
4081
4082
    /**
4083
     * Read locallang files - for frontend applications
4084
     *
4085
     * @param string $fileRef Reference to a relative filename to include.
4086
     * @return array Returns the $LOCAL_LANG array found in the file. If no array found, returns empty array.
4087
     * @deprecated since TYPO3 v9, will be removed in TYPO3 v10
4088
     */
4089
    public function readLLfile($fileRef)
4090
    {
4091
        trigger_error('This method will be removed in TYPO3 v10, as the method LanguageService->includeLLFile() can be used directly.', E_USER_DEPRECATED);
4092
        return $this->languageService->includeLLFile($fileRef, false, true);
4093
    }
4094
4095
    /**
4096
     * Returns 'locallang' label - may need initializing by initLLvars
4097
     *
4098
     * @param string $index Local_lang key for which to return label (language is determined by $this->lang)
4099
     * @param array $LOCAL_LANG The locallang array in which to search
4100
     * @return string Label value of $index key.
4101
     * @deprecated since TYPO3 v9, will be removed in TYPO3 v10, use LanguageService->getLLL() directly
4102
     */
4103
    public function getLLL($index, $LOCAL_LANG)
4104
    {
4105
        trigger_error('This method will be removed in TYPO3 v10, as the method LanguageService->getLLL() can be used directly.', E_USER_DEPRECATED);
4106
        if (isset($LOCAL_LANG[$this->lang][$index][0]['target'])) {
4107
            return $LOCAL_LANG[$this->lang][$index][0]['target'];
4108
        }
4109
        if (isset($LOCAL_LANG['default'][$index][0]['target'])) {
4110
            return $LOCAL_LANG['default'][$index][0]['target'];
4111
        }
4112
        return false;
4113
    }
4114
4115
    /**
4116
     * Initializing the getLL variables needed.
4117
     *
4118
     * @see settingLanguage()
4119
     * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.
4120
     */
4121
    public function initLLvars()
4122
    {
4123
        trigger_error('This method will be removed in TYPO3 v10, the initialization can be altered via hooks within settingLanguage().', E_USER_DEPRECATED);
4124
        $this->lang = $this->config['config']['language'] ?: 'default';
4125
        $this->setOutputLanguage($this->lang);
4126
4127
        // Rendering charset of HTML page.
4128
        if ($this->config['config']['metaCharset']) {
4129
            $this->metaCharset = trim(strtolower($this->config['config']['metaCharset']));
4130
        }
4131
    }
4132
4133
    /**
4134
     * Sets all internal measures what language the page should be rendered.
4135
     * This is not for records, but rather the HTML / charset and the locallang labels
4136
     *
4137
     * @param string $language - usually set via TypoScript config.language = dk
4138
     */
4139
    protected function setOutputLanguage($language = 'default')
4140
    {
4141
        $this->pageRenderer->setLanguage($language);
4142
        $this->languageService = GeneralUtility::makeInstance(LanguageService::class);
4143
        // Always disable debugging for TSFE
4144
        $this->languageService->debugKey = false;
4145
        $this->languageService->init($language);
4146
    }
4147
4148
    /**
4149
     * Converts input string from utf-8 to metaCharset IF the two charsets are different.
4150
     *
4151
     * @param string $content Content to be converted.
4152
     * @return string Converted content string.
4153
     * @throws \RuntimeException if an invalid charset was configured
4154
     */
4155
    public function convOutputCharset($content)
4156
    {
4157
        if ($this->metaCharset !== 'utf-8') {
4158
            /** @var CharsetConverter $charsetConverter */
4159
            $charsetConverter = GeneralUtility::makeInstance(CharsetConverter::class);
4160
            try {
4161
                $content = $charsetConverter->conv($content, 'utf-8', $this->metaCharset, true);
4162
            } catch (UnknownCharsetException $e) {
4163
                throw new \RuntimeException('Invalid config.metaCharset: ' . $e->getMessage(), 1508916185);
4164
            }
4165
        }
4166
        return $content;
4167
    }
4168
4169
    /**
4170
     * Converts the $_POST array from metaCharset (page HTML charset from input form) to utf-8 (internal processing) IF the two charsets are different.
4171
     */
4172
    public function convPOSTCharset()
4173
    {
4174
        if ($this->metaCharset !== 'utf-8' && is_array($_POST) && !empty($_POST)) {
4175
            $this->convertCharsetRecursivelyToUtf8($_POST, $this->metaCharset);
4176
            $GLOBALS['HTTP_POST_VARS'] = $_POST;
4177
        }
4178
    }
4179
4180
    /**
4181
     * Small helper function to convert charsets for arrays to UTF-8
4182
     *
4183
     * @param mixed $data given by reference (string/array usually)
4184
     * @param string $fromCharset convert FROM this charset
4185
     */
4186 View Code Duplication
    protected function convertCharsetRecursivelyToUtf8(&$data, string $fromCharset)
4187
    {
4188
        foreach ($data as $key => $value) {
4189
            if (is_array($data[$key])) {
4190
                $this->convertCharsetRecursivelyToUtf8($data[$key], $fromCharset);
4191
            } elseif (is_string($data[$key])) {
4192
                $data[$key] = mb_convert_encoding($data[$key], 'utf-8', $fromCharset);
4193
            }
4194
        }
4195
    }
4196
4197
    /**
4198
     * Calculates page cache timeout according to the records with starttime/endtime on the page.
4199
     *
4200
     * @return int Page cache timeout or PHP_INT_MAX if cannot be determined
4201
     */
4202
    protected function calculatePageCacheTimeout()
4203
    {
4204
        $result = PHP_INT_MAX;
4205
        // Get the configuration
4206
        $tablesToConsider = $this->getCurrentPageCacheConfiguration();
4207
        // Get the time, rounded to the minute (do not pollute MySQL cache!)
4208
        // It is ok that we do not take seconds into account here because this
4209
        // value will be subtracted later. So we never get the time "before"
4210
        // the cache change.
4211
        $now = $GLOBALS['ACCESS_TIME'];
4212
        // Find timeout by checking every table
4213
        foreach ($tablesToConsider as $tableDef) {
4214
            $result = min($result, $this->getFirstTimeValueForRecord($tableDef, $now));
4215
        }
4216
        // We return + 1 second just to ensure that cache is definitely regenerated
4217
        return $result === PHP_INT_MAX ? PHP_INT_MAX : $result - $now + 1;
4218
    }
4219
4220
    /**
4221
     * Obtains a list of table/pid pairs to consider for page caching.
4222
     *
4223
     * TS configuration looks like this:
4224
     *
4225
     * The cache lifetime of all pages takes starttime and endtime of news records of page 14 into account:
4226
     * config.cache.all = tt_news:14
4227
     *
4228
     * The cache lifetime of page 42 takes starttime and endtime of news records of page 15 and addresses of page 16 into account:
4229
     * config.cache.42 = tt_news:15,tt_address:16
4230
     *
4231
     * @return array Array of 'tablename:pid' pairs. There is at least a current page id in the array
4232
     * @see TypoScriptFrontendController::calculatePageCacheTimeout()
4233
     */
4234
    protected function getCurrentPageCacheConfiguration()
4235
    {
4236
        $result = ['tt_content:' . $this->id];
4237
        if (isset($this->config['config']['cache.'][$this->id])) {
4238
            $result = array_merge($result, GeneralUtility::trimExplode(',', $this->config['config']['cache.'][$this->id]));
4239
        }
4240
        if (isset($this->config['config']['cache.']['all'])) {
4241
            $result = array_merge($result, GeneralUtility::trimExplode(',', $this->config['config']['cache.']['all']));
4242
        }
4243
        return array_unique($result);
4244
    }
4245
4246
    /**
4247
     * Find the minimum starttime or endtime value in the table and pid that is greater than the current time.
4248
     *
4249
     * @param string $tableDef Table definition (format tablename:pid)
4250
     * @param int $now "Now" time value
4251
     * @throws \InvalidArgumentException
4252
     * @return int Value of the next start/stop time or PHP_INT_MAX if not found
4253
     * @see TypoScriptFrontendController::calculatePageCacheTimeout()
4254
     */
4255
    protected function getFirstTimeValueForRecord($tableDef, $now)
4256
    {
4257
        $now = (int)$now;
4258
        $result = PHP_INT_MAX;
4259
        list($tableName, $pid) = GeneralUtility::trimExplode(':', $tableDef);
4260
        if (empty($tableName) || empty($pid)) {
4261
            throw new \InvalidArgumentException('Unexpected value for parameter $tableDef. Expected <tablename>:<pid>, got \'' . htmlspecialchars($tableDef) . '\'.', 1307190365);
4262
        }
4263
4264
        $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
4265
            ->getQueryBuilderForTable($tableName);
4266
        $queryBuilder->getRestrictions()
4267
            ->removeByType(StartTimeRestriction::class)
4268
            ->removeByType(EndTimeRestriction::class);
4269
        $timeFields = [];
4270
        $timeConditions = $queryBuilder->expr()->orX();
4271
        foreach (['starttime', 'endtime'] as $field) {
4272
            if (isset($GLOBALS['TCA'][$tableName]['ctrl']['enablecolumns'][$field])) {
4273
                $timeFields[$field] = $GLOBALS['TCA'][$tableName]['ctrl']['enablecolumns'][$field];
4274
                $queryBuilder->addSelectLiteral(
4275
                    'MIN('
4276
                        . 'CASE WHEN '
4277
                        . $queryBuilder->expr()->lte(
4278
                            $timeFields[$field],
4279
                            $queryBuilder->createNamedParameter($now, \PDO::PARAM_INT)
4280
                        )
4281
                        . ' THEN NULL ELSE ' . $queryBuilder->quoteIdentifier($timeFields[$field]) . ' END'
4282
                        . ') AS ' . $queryBuilder->quoteIdentifier($timeFields[$field])
4283
                );
4284
                $timeConditions->add(
4285
                    $queryBuilder->expr()->gt(
4286
                        $timeFields[$field],
4287
                        $queryBuilder->createNamedParameter($now, \PDO::PARAM_INT)
4288
                    )
4289
                );
4290
            }
4291
        }
4292
4293
        // if starttime or endtime are defined, evaluate them
4294
        if (!empty($timeFields)) {
4295
            // find the timestamp, when the current page's content changes the next time
4296
            $row = $queryBuilder
4297
                ->from($tableName)
4298
                ->where(
4299
                    $queryBuilder->expr()->eq(
4300
                        'pid',
4301
                        $queryBuilder->createNamedParameter($pid, \PDO::PARAM_INT)
4302
                    ),
4303
                    $timeConditions
4304
                )
4305
                ->execute()
4306
                ->fetch();
4307
4308
            if ($row) {
4309
                foreach ($timeFields as $timeField => $_) {
4310
                    // if a MIN value is found, take it into account for the
4311
                    // cache lifetime we have to filter out start/endtimes < $now,
4312
                    // as the SQL query also returns rows with starttime < $now
4313
                    // and endtime > $now (and using a starttime from the past
4314
                    // would be wrong)
4315
                    if ($row[$timeField] !== null && (int)$row[$timeField] > $now) {
4316
                        $result = min($result, (int)$row[$timeField]);
4317
                    }
4318
                }
4319
            }
4320
        }
4321
4322
        return $result;
4323
    }
4324
4325
    /**
4326
     * Fetches/returns the cached contents of the sys_domain database table.
4327
     *
4328
     * @return array Domain data
4329
     */
4330
    protected function getSysDomainCache()
4331
    {
4332
        $entryIdentifier = 'core-database-sys_domain-complete';
4333
        /** @var $runtimeCache \TYPO3\CMS\Core\Cache\Frontend\AbstractFrontend */
4334
        $runtimeCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_runtime');
4335
4336
        $sysDomainData = [];
4337
        if ($runtimeCache->has($entryIdentifier)) {
4338
            $sysDomainData = $runtimeCache->get($entryIdentifier);
4339
        } else {
4340
            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_domain');
4341
            $queryBuilder->setRestrictions(GeneralUtility::makeInstance(DefaultRestrictionContainer::class));
4342
            $result = $queryBuilder
4343
                ->select('uid', 'pid', 'domainName')
4344
                ->from('sys_domain')
4345
                ->where(
4346
                    $queryBuilder->expr()->eq(
4347
                        'redirectTo',
4348
                        $queryBuilder->createNamedParameter('', \PDO::PARAM_STR)
4349
                    )
4350
                )
4351
                ->orderBy('sorting', 'ASC')
4352
                ->execute();
4353
4354
            while ($row = $result->fetch()) {
4355
                // If there is already an entry for this pid, we should not override it
4356
                // Except if it is the current domain
4357
                if (isset($sysDomainData[$row['pid']]) && !$this->domainNameMatchesCurrentRequest($row['domainName'])) {
4358
                    continue;
4359
                }
4360
4361
                // as we passed all previous checks, we save this domain for the current pid
4362
                $sysDomainData[$row['pid']] = [
4363
                    'uid' => $row['uid'],
4364
                    'pid' => $row['pid'],
4365
                    'domainName' => rtrim($row['domainName'], '/'),
4366
                ];
4367
            }
4368
            $runtimeCache->set($entryIdentifier, $sysDomainData);
4369
        }
4370
        return $sysDomainData;
4371
    }
4372
4373
    /**
4374
     * Whether the given domain name (potentially including a path segment) matches currently requested host or
4375
     * the host including the path segment
4376
     *
4377
     * @param string $domainName
4378
     * @return bool
4379
     */
4380
    public function domainNameMatchesCurrentRequest($domainName)
4381
    {
4382
        $currentDomain = GeneralUtility::getIndpEnv('HTTP_HOST');
4383
        $currentPathSegment = trim(preg_replace('|/[^/]*$|', '', GeneralUtility::getIndpEnv('SCRIPT_NAME')));
4384
        return $currentDomain === $domainName || $currentDomain . $currentPathSegment === $domainName;
4385
    }
4386
4387
    /**
4388
     * Obtains domain data for the target pid. Domain data is an array with
4389
     * 'pid' and 'domainName' members (see sys_domain table for meaning of these fields).
4390
     *
4391
     * @param int $targetPid Target page id
4392
     * @return mixed Return domain data or NULL
4393
    */
4394
    public function getDomainDataForPid($targetPid)
4395
    {
4396
        // Using array_key_exists() here, nice $result can be NULL
4397
        // (happens, if there's no domain records defined)
4398
        if (!array_key_exists($targetPid, $this->domainDataCache)) {
4399
            $result = null;
4400
            $sysDomainData = $this->getSysDomainCache();
4401
            $rootline = $this->sys_page->getRootLine($targetPid);
4402
            // walk the rootline downwards from the target page
4403
            // to the root page, until a domain record is found
4404
            foreach ($rootline as $pageInRootline) {
4405
                $pidInRootline = $pageInRootline['uid'];
4406
                if (isset($sysDomainData[$pidInRootline])) {
4407
                    $result = $sysDomainData[$pidInRootline];
4408
                    break;
4409
                }
4410
            }
4411
            $this->domainDataCache[$targetPid] = $result;
4412
        }
4413
4414
        return $this->domainDataCache[$targetPid];
4415
    }
4416
4417
    /**
4418
     * Obtains the domain name for the target pid. If there are several domains,
4419
     * the first is returned.
4420
     *
4421
     * @param int $targetPid Target page id
4422
     * @return mixed Return domain name or NULL if not found
4423
     * @deprecated will be removed in TYPO3 v10, as getDomainDataForPid could work
4424
     */
4425
    public function getDomainNameForPid($targetPid)
4426
    {
4427
        trigger_error('This method will be removed in TYPO3 v10, use $TSFE->getDomainDataForPid() instead.', E_USER_DEPRECATED);
4428
        $domainData = $this->getDomainDataForPid($targetPid);
4429
        return $domainData ? $domainData['domainName'] : null;
4430
    }
4431
4432
    /**
4433
     * Fetches the originally requested id, fallsback to $this->id
4434
     *
4435
     * @return int the originally requested page uid
4436
     * @see fetch_the_id()
4437
     */
4438
    public function getRequestedId()
4439
    {
4440
        return $this->requestedId ?: $this->id;
4441
    }
4442
4443
    /**
4444
     * Acquire a page specific lock
4445
     *
4446
     * @param string $type
4447
     * @param string $key
4448
     * @throws \InvalidArgumentException
4449
     * @throws \RuntimeException
4450
     * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
4451
     */
4452
    protected function acquireLock($type, $key)
4453
    {
4454
        $lockFactory = GeneralUtility::makeInstance(LockFactory::class);
4455
        $this->locks[$type]['accessLock'] = $lockFactory->createLocker($type);
4456
4457
        $this->locks[$type]['pageLock'] = $lockFactory->createLocker(
4458
            $key,
4459
            LockingStrategyInterface::LOCK_CAPABILITY_EXCLUSIVE | LockingStrategyInterface::LOCK_CAPABILITY_NOBLOCK
4460
        );
4461
4462
        do {
4463 View Code Duplication
            if (!$this->locks[$type]['accessLock']->acquire()) {
4464
                throw new \RuntimeException('Could not acquire access lock for "' . $type . '"".', 1294586098);
4465
            }
4466
4467
            try {
4468
                $locked = $this->locks[$type]['pageLock']->acquire(
4469
                    LockingStrategyInterface::LOCK_CAPABILITY_EXCLUSIVE | LockingStrategyInterface::LOCK_CAPABILITY_NOBLOCK
4470
                );
4471
            } catch (LockAcquireWouldBlockException $e) {
4472
                // somebody else has the lock, we keep waiting
4473
4474
                // first release the access lock
4475
                $this->locks[$type]['accessLock']->release();
4476
                // now lets make a short break (100ms) until we try again, since
4477
                // the page generation by the lock owner will take a while anyways
4478
                usleep(100000);
4479
                continue;
4480
            }
4481
            $this->locks[$type]['accessLock']->release();
4482
            if ($locked) {
4483
                break;
4484
            }
4485
            throw new \RuntimeException('Could not acquire page lock for ' . $key . '.', 1460975877);
4486
        } while (true);
4487
    }
4488
4489
    /**
4490
     * Release a page specific lock
4491
     *
4492
     * @param string $type
4493
     * @throws \InvalidArgumentException
4494
     * @throws \RuntimeException
4495
     * @throws \TYPO3\CMS\Core\Cache\Exception\NoSuchCacheException
4496
     */
4497
    protected function releaseLock($type)
4498
    {
4499
        if ($this->locks[$type]['accessLock']) {
4500 View Code Duplication
            if (!$this->locks[$type]['accessLock']->acquire()) {
4501
                throw new \RuntimeException('Could not acquire access lock for "' . $type . '"".', 1460975902);
4502
            }
4503
4504
            $this->locks[$type]['pageLock']->release();
4505
            $this->locks[$type]['pageLock']->destroy();
4506
            $this->locks[$type]['pageLock'] = null;
4507
4508
            $this->locks[$type]['accessLock']->release();
4509
            $this->locks[$type]['accessLock'] = null;
4510
        }
4511
    }
4512
4513
    /**
4514
     * Send additional headers from config.additionalHeaders
4515
     *
4516
     * @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::processOutput()
4517
     */
4518
    protected function sendAdditionalHeaders()
4519
    {
4520
        if (!isset($this->config['config']['additionalHeaders.'])) {
4521
            return;
4522
        }
4523
        ksort($this->config['config']['additionalHeaders.']);
4524
        foreach ($this->config['config']['additionalHeaders.'] as $options) {
4525
            if (!is_array($options)) {
4526
                continue;
4527
            }
4528
            $header = $options['header'] ?? '';
4529
            $header = isset($options['header.'])
4530
                ? $this->cObj->stdWrap(trim($header), $options['header.'])
4531
                : trim($header);
4532
            if ($header === '') {
4533
                continue;
4534
            }
4535
            $replace = $options['replace'] ?? '';
4536
            $replace = isset($options['replace.'])
4537
                ? $this->cObj->stdWrap($replace, $options['replace.'])
4538
                : $replace;
4539
            $httpResponseCode = $options['httpResponseCode'] ?? '';
4540
            $httpResponseCode = isset($options['httpResponseCode.'])
4541
                ? $this->cObj->stdWrap($httpResponseCode, $options['httpResponseCode.'])
4542
                : $httpResponseCode;
4543
            $httpResponseCode = (int)$httpResponseCode;
4544
4545
            header(
4546
                $header,
4547
                // "replace existing headers" is turned on by default, unless turned off
4548
                $replace !== '0',
4549
                $httpResponseCode ?: null
4550
            );
4551
        }
4552
    }
4553
4554
    /**
4555
     * Returns the current BE user.
4556
     *
4557
     * @return \TYPO3\CMS\Backend\FrontendBackendUserAuthentication
4558
     */
4559
    protected function getBackendUser()
4560
    {
4561
        return $GLOBALS['BE_USER'];
4562
    }
4563
4564
    /**
4565
     * @return TimeTracker
4566
     */
4567
    protected function getTimeTracker()
4568
    {
4569
        return GeneralUtility::makeInstance(TimeTracker::class);
4570
    }
4571
}
4572