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

TypoScriptFrontendController::getConfigArray()   F

Complexity

Conditions 20
Paths 3098

Size

Total Lines 90
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

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

1407
            $this->rootLine = $this->sys_page->getRootLine(/** @scrutinizer ignore-type */ $this->id, $this->MP);
Loading history...
1408
            if (!empty($this->rootLine)) {
1409
                $c = count($this->rootLine) - 1;
1410
                while ($c > 0) {
1411
                    // Add to page access failure history:
1412
                    $this->pageAccessFailureHistory['direct_access'][] = $this->rootLine[$c];
1413
                    // Decrease to next page in rootline and check the access to that, if OK, set as page record and ID value.
1414
                    $c--;
1415
                    $this->id = $this->rootLine[$c]['uid'];
1416
                    $this->page = $this->sys_page->getPage($this->id);
1417
                    if (!empty($this->page)) {
1418
                        break;
1419
                    }
1420
                }
1421
            }
1422
            // If still no page...
1423
            if (empty($this->page)) {
1424
                $message = 'The requested page does not exist!';
1425
                if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling']) {
1426
                    $this->pageNotFoundAndExit($message);
1427
                } else {
1428
                    $this->logger->error($message);
1429
                    throw new PageNotFoundException($message, 1301648780);
1430
                }
1431
            }
1432
        }
1433
        // Spacer is not accessible in frontend
1434
        if ($this->page['doktype'] == PageRepository::DOKTYPE_SPACER) {
1435
            $message = 'The requested page does not exist!';
1436
            if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling']) {
1437
                $this->pageNotFoundAndExit($message);
1438
            } else {
1439
                $this->logger->error($message);
1440
                throw new PageNotFoundException($message, 1301648781);
1441
            }
1442
        }
1443
        // Is the ID a link to another page??
1444
        if ($this->page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1445
            // 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.
1446
            $this->MP = '';
1447
            // saving the page so that we can check later - when we know
1448
            // about languages - whether we took the correct shortcut or
1449
            // whether a translation of the page overwrites the shortcut
1450
            // target and we need to follow the new target
1451
            $this->originalShortcutPage = $this->page;
1452
            $this->page = $this->getPageShortcut($this->page['shortcut'], $this->page['shortcut_mode'], $this->page['uid']);
1453
            $this->id = $this->page['uid'];
1454
        }
1455
        // If the page is a mountpoint which should be overlaid with the contents of the mounted page,
1456
        // it must never be accessible directly, but only in the mountpoint context. Therefore we change
1457
        // the current ID and the user is redirected by checkPageForMountpointRedirect().
1458
        if ($this->page['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT && $this->page['mount_pid_ol']) {
1459
            $this->originalMountPointPage = $this->page;
1460
            $this->page = $this->sys_page->getPage($this->page['mount_pid']);
1461
            if (empty($this->page)) {
1462
                $message = 'This page (ID ' . $this->originalMountPointPage['uid'] . ') is of type "Mount point" and '
1463
                    . 'mounts a page which is not accessible (ID ' . $this->originalMountPointPage['mount_pid'] . ').';
1464
                throw new PageNotFoundException($message, 1402043263);
1465
            }
1466
            $this->MP = $this->page['uid'] . '-' . $this->originalMountPointPage['uid'];
1467
            $this->id = $this->page['uid'];
1468
        }
1469
        // Gets the rootLine
1470
        $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1471
        // If not rootline we're off...
1472
        if (empty($this->rootLine)) {
1473
            $message = 'The requested page didn\'t have a proper connection to the tree-root!';
1474
            if ($this->checkPageUnavailableHandler()) {
1475
                $this->pageUnavailableAndExit($message);
1476
            } else {
1477
                $this->logger->error($message);
1478
                throw new ServiceUnavailableException($message, 1301648167);
1479
            }
1480
        }
1481
        // Checking for include section regarding the hidden/starttime/endtime/fe_user (that is access control of a whole subbranch!)
1482
        if ($this->checkRootlineForIncludeSection()) {
1483
            if (empty($this->rootLine)) {
1484
                $message = 'The requested page was not accessible!';
1485
                if ($this->checkPageUnavailableHandler()) {
1486
                    $this->pageUnavailableAndExit($message);
1487
                } else {
1488
                    $this->logger->warning($message);
1489
                    throw new ServiceUnavailableException($message, 1301648234);
1490
                }
1491
            } else {
1492
                $el = reset($this->rootLine);
1493
                $this->id = $el['uid'];
1494
                $this->page = $this->sys_page->getPage($this->id);
1495
                $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1496
            }
1497
        }
1498
    }
1499
1500
    /**
1501
     * If $this->id contains a translated page record, this needs to be resolved to the default language
1502
     * in order for all rootline functionality and access restrictions to be in place further on.
1503
     *
1504
     * Additionally, if a translated page is found, $this->sys_language_uid/sys_language_content is set as well.
1505
     */
1506
    protected function resolveTranslatedPageId()
1507
    {
1508
        $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

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

2030
            list($header, $content) = explode(CRLF . CRLF, /** @scrutinizer ignore-type */ $res, 2);
Loading history...
2031
            $content .= CRLF;
2032
            if (false === $res) {
2033
                // Last chance -- redirect
2034
                HttpUtility::redirect($code);
2035
            } else {
2036
                // Forward these response headers to the client
2037
                $forwardHeaders = [
2038
                    'Content-Type:'
2039
                ];
2040
                $headerArr = preg_split('/\\r|\\n/', $header, -1, PREG_SPLIT_NO_EMPTY);
2041
                foreach ($headerArr as $header) {
2042
                    foreach ($forwardHeaders as $h) {
2043
                        if (preg_match('/^' . $h . '/', $header)) {
2044
                            header($header);
2045
                        }
2046
                    }
2047
                }
2048
                // Put <base> if necessary
2049
                if ($checkBaseTag) {
2050
                    // If content already has <base> tag, we do not need to do anything
2051
                    if (false === stristr($content, '<base ')) {
2052
                        // Generate href for base tag
2053
                        $base = $url_parts['scheme'] . '://';
2054
                        if ($url_parts['user'] != '') {
2055
                            $base .= $url_parts['user'];
2056
                            if ($url_parts['pass'] != '') {
2057
                                $base .= ':' . $url_parts['pass'];
2058
                            }
2059
                            $base .= '@';
2060
                        }
2061
                        $base .= $url_parts['host'];
2062
                        // Add path portion skipping possible file name
2063
                        $base .= preg_replace('/(.*\\/)[^\\/]*/', '${1}', $url_parts['path']);
2064
                        // Put it into content (generate also <head> if necessary)
2065
                        $replacement = LF . '<base href="' . htmlentities($base) . '" />' . LF;
2066
                        if (stristr($content, '<head>')) {
2067
                            $content = preg_replace('/(<head>)/i', '\\1' . $replacement, $content);
2068
                        } else {
2069
                            $content = preg_replace('/(<html[^>]*>)/i', '\\1<head>' . $replacement . '</head>', $content);
2070
                        }
2071
                    }
2072
                }
2073
                // Output the content
2074
                echo $content;
2075
            }
2076
        } else {
2077
            echo GeneralUtility::makeInstance(ErrorPageController::class)->errorAction(
2078
                'Page Not Found',
2079
                $reason ? 'Reason: ' . $reason : 'Page cannot be found.'
2080
            );
2081
        }
2082
        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...
2083
    }
2084
2085
    /**
2086
     * Fetches the integer page id for a page alias.
2087
     * 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
2088
     *
2089
     * @access private
2090
     */
2091
    public function checkAndSetAlias()
2092
    {
2093
        if ($this->id && !MathUtility::canBeInterpretedAsInteger($this->id)) {
2094
            $aid = $this->sys_page->getPageIdFromAlias($this->id);
2095
            if ($aid) {
2096
                $this->id = $aid;
2097
            } else {
2098
                $this->pageNotFound = 4;
2099
            }
2100
        }
2101
    }
2102
2103
    /**
2104
     * Merging values into the global $_GET
2105
     *
2106
     * @param array $GET_VARS Array of key/value pairs that will be merged into the current GET-vars. (Non-escaped values)
2107
     */
2108
    public function mergingWithGetVars($GET_VARS)
2109
    {
2110
        if (is_array($GET_VARS)) {
2111
            // Getting $_GET var, unescaped.
2112
            $realGet = GeneralUtility::_GET();
2113
            if (!is_array($realGet)) {
2114
                $realGet = [];
2115
            }
2116
            // Merge new values on top:
2117
            ArrayUtility::mergeRecursiveWithOverrule($realGet, $GET_VARS);
2118
            // Write values back to $_GET:
2119
            GeneralUtility::_GETset($realGet);
2120
            // Setting these specifically (like in the init-function):
2121
            if (isset($GET_VARS['type'])) {
2122
                $this->type = (int)$GET_VARS['type'];
2123
            }
2124
            if (isset($GET_VARS['cHash'])) {
2125
                $this->cHash = $GET_VARS['cHash'];
2126
            }
2127
            if (isset($GET_VARS['MP'])) {
2128
                $this->MP = $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] ? $GET_VARS['MP'] : '';
2129
            }
2130
            if (isset($GET_VARS['no_cache']) && $GET_VARS['no_cache']) {
2131
                $this->set_no_cache('no_cache is requested via GET parameter');
2132
            }
2133
        }
2134
    }
2135
2136
    /********************************************
2137
     *
2138
     * Template and caching related functions.
2139
     *
2140
     *******************************************/
2141
    /**
2142
     * Calculates a hash string based on additional parameters in the url.
2143
     *
2144
     * Calculated hash is stored in $this->cHash_array.
2145
     * This is used to cache pages with more parameters than just id and type.
2146
     *
2147
     * @see reqCHash()
2148
     */
2149
    public function makeCacheHash()
2150
    {
2151
        // No need to test anything if caching was already disabled.
2152
        if ($this->no_cache && !$GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2153
            return;
2154
        }
2155
        $GET = GeneralUtility::_GET();
2156
        if ($this->cHash && is_array($GET)) {
2157
            // Make sure we use the page uid and not the page alias
2158
            $GET['id'] = $this->id;
2159
            $this->cHash_array = $this->cacheHash->getRelevantParameters(GeneralUtility::implodeArrayForUrl('', $GET));
2160
            $cHash_calc = $this->cacheHash->calculateCacheHash($this->cHash_array);
2161
            if (!hash_equals($cHash_calc, $this->cHash)) {
2162
                if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2163
                    $this->pageNotFoundAndExit('Request parameters could not be validated (&cHash comparison failed)');
2164
                } else {
2165
                    $this->disableCache();
2166
                    $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);
2167
                }
2168
            }
2169
        } elseif (is_array($GET)) {
2170
            // No cHash is set, check if that is correct
2171
            if ($this->cacheHash->doParametersRequireCacheHash(GeneralUtility::implodeArrayForUrl('', $GET))) {
2172
                $this->reqCHash();
2173
            }
2174
        }
2175
    }
2176
2177
    /**
2178
     * Will disable caching if the cHash value was not set.
2179
     * 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)
2180
     *
2181
     * @see makeCacheHash(), \TYPO3\CMS\Frontend\Plugin\AbstractPlugin::pi_cHashCheck()
2182
     */
2183
    public function reqCHash()
2184
    {
2185
        if (!$this->cHash) {
2186
            if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2187
                if ($this->tempContent) {
2188
                    $this->clearPageCacheContent();
2189
                }
2190
                $this->pageNotFoundAndExit('Request parameters could not be validated (&cHash empty)');
2191
            } else {
2192
                $this->disableCache();
2193
                $this->getTimeTracker()->setTSlogMessage('TSFE->reqCHash(): No &cHash parameter was sent for GET vars though required so caching is disabled', 2);
2194
            }
2195
        }
2196
    }
2197
2198
    /**
2199
     * Initialize the TypoScript template parser
2200
     */
2201
    public function initTemplate()
2202
    {
2203
        $this->tmpl = GeneralUtility::makeInstance(TemplateService::class);
2204
        $this->tmpl->setVerbose((bool)$this->beUserLogin);
2205
        $this->tmpl->init();
2206
        $this->tmpl->tt_track = (bool)$this->beUserLogin;
2207
    }
2208
2209
    /**
2210
     * See if page is in cache and get it if so
2211
     * Stores the page content in $this->content if something is found.
2212
     *
2213
     * @throws \InvalidArgumentException
2214
     * @throws \RuntimeException
2215
     */
2216
    public function getFromCache()
2217
    {
2218
        // clearing the content-variable, which will hold the pagecontent
2219
        $this->content = '';
2220
        // Unsetting the lowlevel config
2221
        $this->config = [];
2222
        $this->cacheContentFlag = false;
2223
2224
        if ($this->no_cache) {
2225
            return;
2226
        }
2227
2228
        $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2229
        if (!is_array($pageSectionCacheContent)) {
2230
            // Nothing in the cache, we acquire an "exclusive lock" for the key now.
2231
            // We use the Registry to store this lock centrally,
2232
            // but we protect the access again with a global exclusive lock to avoid race conditions
2233
2234
            $this->acquireLock('pagesection', $this->id . '::' . $this->MP);
2235
            //
2236
            // from this point on we're the only one working on that page ($key)
2237
            //
2238
2239
            // query the cache again to see if the page data are there meanwhile
2240
            $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2241
            if (is_array($pageSectionCacheContent)) {
2242
                // we have the content, nice that some other process did the work for us already
2243
                $this->releaseLock('pagesection');
2244
            }
2245
            // We keep the lock set, because we are the ones generating the page now
2246
                // and filling the cache.
2247
                // This indicates that we have to release the lock in the Registry later in releaseLocks()
2248
        }
2249
2250
        if (is_array($pageSectionCacheContent)) {
2251
            // 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.
2252
            // If this hash is not the same in here in this section and after page-generation, then the page will not be properly cached!
2253
            // 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.
2254
            $pageSectionCacheContent = $this->tmpl->matching($pageSectionCacheContent);
2255
            ksort($pageSectionCacheContent);
2256
            $this->all = $pageSectionCacheContent;
2257
        }
2258
        unset($pageSectionCacheContent);
2259
2260
        // Look for page in cache only if a shift-reload is not sent to the server.
2261
        $lockHash = $this->getLockHash();
2262
        if (!$this->headerNoCache()) {
2263
            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...
2264
                // we got page section information
2265
                $this->newHash = $this->getHash();
2266
                $this->getTimeTracker()->push('Cache Row', '');
2267
                $row = $this->getFromCache_queryRow();
2268
                if (!is_array($row)) {
2269
                    // nothing in the cache, we acquire an exclusive lock now
2270
2271
                    $this->acquireLock('pages', $lockHash);
2272
                    //
2273
                    // from this point on we're the only one working on that page ($lockHash)
2274
                    //
2275
2276
                    // query the cache again to see if the data are there meanwhile
2277
                    $row = $this->getFromCache_queryRow();
2278
                    if (is_array($row)) {
2279
                        // we have the content, nice that some other process did the work for us
2280
                        $this->releaseLock('pages');
2281
                    }
2282
                    // We keep the lock set, because we are the ones generating the page now
2283
                        // and filling the cache.
2284
                        // This indicates that we have to release the lock in the Registry later in releaseLocks()
2285
                }
2286
                if (is_array($row)) {
2287
                    // we have data from cache
2288
2289
                    // Call hook when a page is retrieved from cache:
2290
                    $_params = ['pObj' => &$this, 'cache_pages_row' => &$row];
2291
                    foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'] ?? [] as $_funcRef) {
2292
                        GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2293
                    }
2294
                    // Fetches the lowlevel config stored with the cached data
2295
                    $this->config = $row['cache_data'];
2296
                    // Getting the content
2297
                    $this->content = $row['content'];
2298
                    // Flag for temp content
2299
                    $this->tempContent = $row['temp_content'];
2300
                    // Setting flag, so we know, that some cached content has been loaded
2301
                    $this->cacheContentFlag = true;
2302
                    $this->cacheExpires = $row['expires'];
2303
2304
                    // Restore page title information, this is needed to generate the page title for
2305
                    // partially cached pages.
2306
                    $this->page['title'] = $row['pageTitleInfo']['title'];
2307
                    $this->altPageTitle = $row['pageTitleInfo']['altPageTitle'];
2308
                    $this->indexedDocTitle = $row['pageTitleInfo']['indexedDocTitle'];
2309
2310
                    if (isset($this->config['config']['debug'])) {
2311
                        $debugCacheTime = (bool)$this->config['config']['debug'];
2312
                    } else {
2313
                        $debugCacheTime = !empty($GLOBALS['TYPO3_CONF_VARS']['FE']['debug']);
2314
                    }
2315
                    if ($debugCacheTime) {
2316
                        $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
2317
                        $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
2318
                        $this->content .= LF . '<!-- Cached page generated ' . date(($dateFormat . ' ' . $timeFormat), $row['tstamp']) . '. Expires ' . date(($dateFormat . ' ' . $timeFormat), $row['expires']) . ' -->';
2319
                    }
2320
                }
2321
                $this->getTimeTracker()->pull();
2322
2323
                return;
2324
            }
2325
        }
2326
        // the user forced rebuilding the page cache or there was no pagesection information
2327
        // get a lock for the page content so other processes will not interrupt the regeneration
2328
        $this->acquireLock('pages', $lockHash);
2329
    }
2330
2331
    /**
2332
     * Returning the cached version of page with hash = newHash
2333
     *
2334
     * @return array Cached row, if any. Otherwise void.
2335
     */
2336
    public function getFromCache_queryRow()
2337
    {
2338
        $this->getTimeTracker()->push('Cache Query', '');
2339
        $row = $this->pageCache->get($this->newHash);
2340
        $this->getTimeTracker()->pull();
2341
        return $row;
2342
    }
2343
2344
    /**
2345
     * Detecting if shift-reload has been clicked
2346
     * Will not be called if re-generation of page happens by other reasons (for instance that the page is not in cache yet!)
2347
     * Also, a backend user MUST be logged in for the shift-reload to be detected due to DoS-attack-security reasons.
2348
     *
2349
     * @return bool If shift-reload in client browser has been clicked, disable getting cached page (and regenerate it).
2350
     */
2351
    public function headerNoCache()
2352
    {
2353
        $disableAcquireCacheData = false;
2354
        if ($this->beUserLogin) {
2355
            if (strtolower($_SERVER['HTTP_CACHE_CONTROL']) === 'no-cache' || strtolower($_SERVER['HTTP_PRAGMA']) === 'no-cache') {
2356
                $disableAcquireCacheData = true;
2357
            }
2358
        }
2359
        // Call hook for possible by-pass of requiring of page cache (for recaching purpose)
2360
        $_params = ['pObj' => &$this, 'disableAcquireCacheData' => &$disableAcquireCacheData];
2361
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'] ?? [] as $_funcRef) {
2362
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2363
        }
2364
        return $disableAcquireCacheData;
2365
    }
2366
2367
    /**
2368
     * Calculates the cache-hash
2369
     * This hash is unique to the template, the variables ->id, ->type, ->gr_list (list of groups), ->MP (Mount Points) and cHash array
2370
     * Used to get and later store the cached data.
2371
     *
2372
     * @return string MD5 hash of serialized hash base from createHashBase()
2373
     * @access private
2374
     * @see getFromCache(), getLockHash()
2375
     */
2376
    public function getHash()
2377
    {
2378
        return md5($this->createHashBase(false));
2379
    }
2380
2381
    /**
2382
     * Calculates the lock-hash
2383
     * This hash is unique to the above hash, except that it doesn't contain the template information in $this->all.
2384
     *
2385
     * @return string MD5 hash
2386
     * @access private
2387
     * @see getFromCache(), getHash()
2388
     */
2389
    public function getLockHash()
2390
    {
2391
        $lockHash = $this->createHashBase(true);
2392
        return md5($lockHash);
2393
    }
2394
2395
    /**
2396
     * Calculates the cache-hash (or the lock-hash)
2397
     * This hash is unique to the template,
2398
     * the variables ->id, ->type, ->gr_list (list of groups),
2399
     * ->MP (Mount Points) and cHash array
2400
     * Used to get and later store the cached data.
2401
     *
2402
     * @param bool $createLockHashBase Whether to create the lock hash, which doesn't contain the "this->all" (the template information)
2403
     * @return string the serialized hash base
2404
     */
2405
    protected function createHashBase($createLockHashBase = false)
2406
    {
2407
        $hashParameters = [
2408
            'id' => (int)$this->id,
2409
            'type' => (int)$this->type,
2410
            'gr_list' => (string)$this->gr_list,
2411
            'MP' => (string)$this->MP,
2412
            'cHash' => $this->cHash_array,
2413
            'domainStartPage' => $this->domainStartPage
2414
        ];
2415
        // Include the template information if we shouldn't create a lock hash
2416
        if (!$createLockHashBase) {
2417
            $hashParameters['all'] = $this->all;
2418
        }
2419
        // Call hook to influence the hash calculation
2420
        $_params = [
2421
            'hashParameters' => &$hashParameters,
2422
            'createLockHashBase' => $createLockHashBase
2423
        ];
2424
        foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['createHashBase'] ?? [] as $_funcRef) {
2425
            GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2426
        }
2427
        return serialize($hashParameters);
2428
    }
2429
2430
    /**
2431
     * Checks if config-array exists already but if not, gets it
2432
     *
2433
     * @throws ServiceUnavailableException
2434
     */
2435
    public function getConfigArray()
2436
    {
2437
        // 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
2438
        if (empty($this->config) || is_array($this->config['INTincScript']) || $this->forceTemplateParsing) {
2439
            $timeTracker = $this->getTimeTracker();
2440
            $timeTracker->push('Parse template', '');
2441
            // Force parsing, if set?:
2442
            $this->tmpl->forceTemplateParsing = $this->forceTemplateParsing;
2443
            // Start parsing the TS template. Might return cached version.
2444
            $this->tmpl->start($this->rootLine);
2445
            $timeTracker->pull();
2446
            if ($this->tmpl->loaded) {
2447
                $timeTracker->push('Setting the config-array', '');
2448
                // toplevel - objArrayName
2449
                $this->sPre = $this->tmpl->setup['types.'][$this->type];
2450
                $this->pSetup = $this->tmpl->setup[$this->sPre . '.'];
2451
                if (!is_array($this->pSetup)) {
2452
                    $message = 'The page is not configured! [type=' . $this->type . '][' . $this->sPre . '].';
2453
                    if ($this->checkPageUnavailableHandler()) {
2454
                        $this->pageUnavailableAndExit($message);
2455
                    } else {
2456
                        $explanation = 'This means that there is no TypoScript object of type PAGE with typeNum=' . $this->type . ' configured.';
2457
                        $this->logger->alert($message);
2458
                        throw new ServiceUnavailableException($message . ' ' . $explanation, 1294587217);
2459
                    }
2460
                } else {
2461
                    if (!isset($this->config['config'])) {
2462
                        $this->config['config'] = [];
2463
                    }
2464
                    // Filling the config-array, first with the main "config." part
2465
                    if (is_array($this->tmpl->setup['config.'])) {
2466
                        ArrayUtility::mergeRecursiveWithOverrule($this->tmpl->setup['config.'], $this->config['config']);
2467
                        $this->config['config'] = $this->tmpl->setup['config.'];
2468
                    }
2469
                    // override it with the page/type-specific "config."
2470
                    if (is_array($this->pSetup['config.'])) {
2471
                        ArrayUtility::mergeRecursiveWithOverrule($this->config['config'], $this->pSetup['config.']);
2472
                    }
2473
                    // @deprecated since TYPO3 v9, can be removed in TYPO3 v10
2474
                    if ($this->config['config']['typolinkCheckRootline']) {
2475
                        $this->logDeprecatedTyposcript('config.typolinkCheckRootline', 'The functionality is always enabled since TYPO3 v9 and can be removed from your TypoScript code');
2476
                    }
2477
                    // Set default values for removeDefaultJS and inlineStyle2TempFile so CSS and JS are externalized if compatversion is higher than 4.0
2478
                    if (!isset($this->config['config']['removeDefaultJS'])) {
2479
                        $this->config['config']['removeDefaultJS'] = 'external';
2480
                    }
2481
                    if (!isset($this->config['config']['inlineStyle2TempFile'])) {
2482
                        $this->config['config']['inlineStyle2TempFile'] = 1;
2483
                    }
2484
2485
                    if (!isset($this->config['config']['compressJs'])) {
2486
                        $this->config['config']['compressJs'] = 0;
2487
                    }
2488
                    // Processing for the config_array:
2489
                    $this->config['rootLine'] = $this->tmpl->rootLine;
2490
                    // Class for render Header and Footer parts
2491
                    if ($this->pSetup['pageHeaderFooterTemplateFile']) {
2492
                        $file = $this->tmpl->getFileName($this->pSetup['pageHeaderFooterTemplateFile']);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $file is correct as $this->tmpl->getFileName...erFooterTemplateFile']) targeting TYPO3\CMS\Core\TypoScrip...eService::getFileName() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
2493
                        if ($file) {
2494
                            $this->pageRenderer->setTemplateFile($file);
0 ignored issues
show
Bug introduced by
$file of type void is incompatible with the type string expected by parameter $file of TYPO3\CMS\Core\Page\Page...erer::setTemplateFile(). ( Ignorable by Annotation )

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

2494
                            $this->pageRenderer->setTemplateFile(/** @scrutinizer ignore-type */ $file);
Loading history...
2495
                        }
2496
                    }
2497
                }
2498
                $timeTracker->pull();
2499
            } else {
2500
                if ($this->checkPageUnavailableHandler()) {
2501
                    $this->pageUnavailableAndExit('No TypoScript template found!');
2502
                } else {
2503
                    $message = 'No TypoScript template found!';
2504
                    $this->logger->alert($message);
2505
                    throw new ServiceUnavailableException($message, 1294587218);
2506
                }
2507
            }
2508
        }
2509
2510
        // No cache
2511
        // Set $this->no_cache TRUE if the config.no_cache value is set!
2512
        if ($this->config['config']['no_cache']) {
2513
            $this->set_no_cache('config.no_cache is set');
2514
        }
2515
        // Merge GET with defaultGetVars
2516
        if (!empty($this->config['config']['defaultGetVars.'])) {
2517
            $modifiedGetVars = GeneralUtility::removeDotsFromTS($this->config['config']['defaultGetVars.']);
2518
            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

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

2663
            $this->rootLine = $this->sys_page->getRootLine(/** @scrutinizer ignore-type */ $this->id, $this->MP);
Loading history...
2664
            $this->tmpl->updateRootlineData($this->rootLine);
2665
        }
2666
    }
2667
2668
    /**
2669
     * Setting locale for frontend rendering
2670
     */
2671
    public function settingLocale()
2672
    {
2673
        // Setting locale
2674
        if ($this->config['config']['locale_all']) {
2675
            $availableLocales = GeneralUtility::trimExplode(',', $this->config['config']['locale_all'], true);
2676
            // If LC_NUMERIC is set e.g. to 'de_DE' PHP parses float values locale-aware resulting in strings with comma
2677
            // as decimal point which causes problems with value conversions - so we set all locale types except LC_NUMERIC
2678
            // @see https://bugs.php.net/bug.php?id=53711
2679
            $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

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

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

4147
                $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 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

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

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

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