d580ccf9112c2aedf217c709d4f9be5484d8973b
[Packages/TYPO3.CMS.git] / typo3 / sysext / frontend / Classes / Controller / TypoScriptFrontendController.php
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')) {
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;
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')
1116 || $this->doWorkspacePreview()
1117 )
1118 && (
1119 $this->whichWorkspace() === -1
1120 || $this->whichWorkspace() > 0
1121 )
1122 && !GeneralUtility::_GP('ADMCMD_noBeUser')
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);
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);
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;
1860 }
1861 array_shift($host);
1862 }
1863 return $pageUid;
1864 }
1865 return $this->sys_page->getDomainStartPage(GeneralUtility::getIndpEnv('HTTP_HOST'), GeneralUtility::getIndpEnv('SCRIPT_NAME'), GeneralUtility::getIndpEnv('REQUEST_URI'));
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;
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;
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);
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;
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) {
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']);
2493 if ($file) {
2494 $this->pageRenderer->setTemplateFile($file);
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());
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);
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);
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 }