[BUGFIX] Ensure TSconfig order is identical in BE and FE
[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\Http\Message\ResponseInterface;
19 use Psr\Log\LoggerAwareInterface;
20 use Psr\Log\LoggerAwareTrait;
21 use TYPO3\CMS\Backend\FrontendBackendUserAuthentication;
22 use TYPO3\CMS\Core\Authentication\BackendUserAuthentication;
23 use TYPO3\CMS\Core\Cache\CacheManager;
24 use TYPO3\CMS\Core\Charset\CharsetConverter;
25 use TYPO3\CMS\Core\Charset\UnknownCharsetException;
26 use TYPO3\CMS\Core\Controller\ErrorPageController;
27 use TYPO3\CMS\Core\Database\ConnectionPool;
28 use TYPO3\CMS\Core\Database\Query\QueryHelper;
29 use TYPO3\CMS\Core\Database\Query\Restriction\DefaultRestrictionContainer;
30 use TYPO3\CMS\Core\Database\Query\Restriction\DeletedRestriction;
31 use TYPO3\CMS\Core\Database\Query\Restriction\EndTimeRestriction;
32 use TYPO3\CMS\Core\Database\Query\Restriction\StartTimeRestriction;
33 use TYPO3\CMS\Core\Error\Http\PageNotFoundException;
34 use TYPO3\CMS\Core\Error\Http\ServiceUnavailableException;
35 use TYPO3\CMS\Core\Error\Http\ShortcutTargetPageNotFoundException;
36 use TYPO3\CMS\Core\Localization\LanguageService;
37 use TYPO3\CMS\Core\Locking\Exception\LockAcquireWouldBlockException;
38 use TYPO3\CMS\Core\Locking\LockFactory;
39 use TYPO3\CMS\Core\Locking\LockingStrategyInterface;
40 use TYPO3\CMS\Core\Log\LogManager;
41 use TYPO3\CMS\Core\Page\PageRenderer;
42 use TYPO3\CMS\Core\Resource\StorageRepository;
43 use TYPO3\CMS\Core\Service\DependencyOrderingService;
44 use TYPO3\CMS\Core\TimeTracker\TimeTracker;
45 use TYPO3\CMS\Core\Type\Bitmask\Permission;
46 use TYPO3\CMS\Core\TypoScript\Parser\TypoScriptParser;
47 use TYPO3\CMS\Core\TypoScript\TemplateService;
48 use TYPO3\CMS\Core\Utility\ArrayUtility;
49 use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
50 use TYPO3\CMS\Core\Utility\GeneralUtility;
51 use TYPO3\CMS\Core\Utility\HttpUtility;
52 use TYPO3\CMS\Core\Utility\MathUtility;
53 use TYPO3\CMS\Frontend\Authentication\FrontendUserAuthentication;
54 use TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer;
55 use TYPO3\CMS\Frontend\Http\UrlHandlerInterface;
56 use TYPO3\CMS\Frontend\Page\CacheHashCalculator;
57 use TYPO3\CMS\Frontend\Page\PageRepository;
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 * @deprecated since TYPO3 v9, will be removed in TYPO3 v10.
187 */
188 public $page_cache_reg1 = 0;
189
190 /**
191 * Contains the value of the current script path that activated the frontend.
192 * Typically "index.php" but by rewrite rules it could be something else! Used
193 * for Speaking Urls / Simulate Static Documents.
194 * @var string
195 */
196 public $siteScript = '';
197
198 /**
199 * The frontend user
200 *
201 * @var FrontendUserAuthentication
202 */
203 public $fe_user = '';
204
205 /**
206 * Global flag indicating that a frontend user is logged in. This is set only if
207 * a user really IS logged in. The group-list may show other groups (like added
208 * by IP filter or so) even though there is no user.
209 * @var bool
210 */
211 public $loginUser = false;
212
213 /**
214 * (RO=readonly) The group list, sorted numerically. Group '0,-1' is the default
215 * group, but other groups may be added by other means than a user being logged
216 * in though...
217 * @var string
218 */
219 public $gr_list = '';
220
221 /**
222 * Flag that indicates if a backend user is logged in!
223 * @var bool
224 */
225 public $beUserLogin = false;
226
227 /**
228 * Integer, that indicates which workspace is being previewed.
229 * Not in use anymore, as this is part of the workspace preview functionality, use $TSFE->whichWorkspace() instead.
230 * @var int
231 */
232 public $workspacePreview = 0;
233
234 /**
235 * Shows whether logins are allowed in branch
236 * @var bool
237 */
238 public $loginAllowedInBranch = true;
239
240 /**
241 * Shows specific mode (all or groups)
242 * @var string
243 */
244 public $loginAllowedInBranch_mode = '';
245
246 /**
247 * Set to backend user ID to initialize when keyword-based preview is used
248 * @var int
249 */
250 public $ADMCMD_preview_BEUSER_uid = 0;
251
252 /**
253 * Flag indication that preview is active. This is based on the login of a
254 * backend user and whether the backend user has read access to the current
255 * page.
256 * @var int
257 */
258 public $fePreview = 0;
259
260 /**
261 * Flag indicating that hidden pages should be shown, selected and so on. This
262 * goes for almost all selection of pages!
263 * @var bool
264 */
265 public $showHiddenPage = false;
266
267 /**
268 * Flag indicating that hidden records should be shown. This includes
269 * sys_template and even fe_groups in addition to all
270 * other regular content. So in effect, this includes everything except pages.
271 * @var bool
272 */
273 public $showHiddenRecords = false;
274
275 /**
276 * Value that contains the simulated usergroup if any
277 * @var int
278 */
279 public $simUserGroup = 0;
280
281 /**
282 * "CONFIG" object from TypoScript. Array generated based on the TypoScript
283 * configuration of the current page. Saved with the cached pages.
284 * @var array
285 */
286 public $config = [];
287
288 /**
289 * The TypoScript template object. Used to parse the TypoScript template
290 *
291 * @var TemplateService
292 */
293 public $tmpl = null;
294
295 /**
296 * Is set to the time-to-live time of cached pages. If FALSE, default is
297 * 60*60*24, which is 24 hours.
298 * @var bool|int
299 */
300 public $cacheTimeOutDefault = false;
301
302 /**
303 * Set internally if cached content is fetched from the database
304 * @var bool
305 * @internal
306 */
307 public $cacheContentFlag = false;
308
309 /**
310 * Set to the expire time of cached content
311 * @var int
312 */
313 public $cacheExpires = 0;
314
315 /**
316 * Set if cache headers allowing caching are sent.
317 * @var bool
318 */
319 public $isClientCachable = false;
320
321 /**
322 * Used by template fetching system. This array is an identification of
323 * the template. If $this->all is empty it's because the template-data is not
324 * cached, which it must be.
325 * @var array
326 */
327 public $all = [];
328
329 /**
330 * Toplevel - objArrayName, eg 'page'
331 * @var string
332 */
333 public $sPre = '';
334
335 /**
336 * TypoScript configuration of the page-object pointed to by sPre.
337 * $this->tmpl->setup[$this->sPre.'.']
338 * @var array
339 */
340 public $pSetup = '';
341
342 /**
343 * This hash is unique to the template, the $this->id and $this->type vars and
344 * the gr_list (list of groups). Used to get and later store the cached data
345 * @var string
346 */
347 public $newHash = '';
348
349 /**
350 * If config.ftu (Frontend Track User) is set in TypoScript for the current
351 * page, the string value of this var is substituted in the rendered source-code
352 * with the string, '&ftu=[token...]' which enables GET-method usertracking as
353 * opposed to cookie based
354 * @var string
355 */
356 public $getMethodUrlIdToken = '';
357
358 /**
359 * This flag is set before inclusion of pagegen.php IF no_cache is set. If this
360 * flag is set after the inclusion of pagegen.php, no_cache is forced to be set.
361 * This is done in order to make sure that php-code from pagegen does not falsely
362 * clear the no_cache flag.
363 * @var bool
364 */
365 public $no_cacheBeforePageGen = false;
366
367 /**
368 * This flag indicates if temporary content went into the cache during
369 * page-generation.
370 * @var mixed
371 */
372 public $tempContent = false;
373
374 /**
375 * Passed to TypoScript template class and tells it to force template rendering
376 * @var bool
377 */
378 public $forceTemplateParsing = false;
379
380 /**
381 * The array which cHash_calc is based on, see ->makeCacheHash().
382 * @var array
383 */
384 public $cHash_array = [];
385
386 /**
387 * May be set to the pagesTSconfig
388 * @var array
389 */
390 public $pagesTSconfig = '';
391
392 /**
393 * Eg. insert JS-functions in this array ($additionalHeaderData) to include them
394 * once. Use associative keys.
395 *
396 * Keys in use:
397 *
398 * used to accumulate additional HTML-code for the header-section,
399 * <head>...</head>. Insert either associative keys (like
400 * additionalHeaderData['myStyleSheet'], see reserved keys above) or num-keys
401 * (like additionalHeaderData[] = '...')
402 *
403 * @var array
404 */
405 public $additionalHeaderData = [];
406
407 /**
408 * Used to accumulate additional HTML-code for the footer-section of the template
409 * @var array
410 */
411 public $additionalFooterData = [];
412
413 /**
414 * Used to accumulate additional JavaScript-code. Works like
415 * additionalHeaderData. Reserved keys at 'openPic' and 'mouseOver'
416 *
417 * @var array
418 */
419 public $additionalJavaScript = [];
420
421 /**
422 * Used to accumulate additional Style code. Works like additionalHeaderData.
423 *
424 * @var array
425 */
426 public $additionalCSS = [];
427
428 /**
429 * @var string
430 */
431 public $JSCode;
432
433 /**
434 * @var string
435 */
436 public $inlineJS;
437
438 /**
439 * Used to accumulate DHTML-layers.
440 * @var string
441 */
442 public $divSection = '';
443
444 /**
445 * Debug flag. If TRUE special debug-output maybe be shown (which includes html-formatting).
446 * @var bool
447 */
448 public $debug = false;
449
450 /**
451 * Default internal target
452 * @var string
453 */
454 public $intTarget = '';
455
456 /**
457 * Default external target
458 * @var string
459 */
460 public $extTarget = '';
461
462 /**
463 * Default file link target
464 * @var string
465 */
466 public $fileTarget = '';
467
468 /**
469 * Keys are page ids and values are default &MP (mount point) values to set
470 * when using the linking features...)
471 * @var array
472 */
473 public $MP_defaults = [];
474
475 /**
476 * If set, typolink() function encrypts email addresses. Is set in pagegen-class.
477 * @var string|int
478 */
479 public $spamProtectEmailAddresses = 0;
480
481 /**
482 * Absolute Reference prefix
483 * @var string
484 */
485 public $absRefPrefix = '';
486
487 /**
488 * <A>-tag parameters
489 * @var string
490 */
491 public $ATagParams = '';
492
493 /**
494 * Search word regex, calculated if there has been search-words send. This is
495 * used to mark up the found search words on a page when jumped to from a link
496 * in a search-result.
497 * @var string
498 */
499 public $sWordRegEx = '';
500
501 /**
502 * Is set to the incoming array sword_list in case of a page-view jumped to from
503 * a search-result.
504 * @var string
505 */
506 public $sWordList = '';
507
508 /**
509 * A string prepared for insertion in all links on the page as url-parameters.
510 * Based on configuration in TypoScript where you defined which GET_VARS you
511 * would like to pass on.
512 * @var string
513 */
514 public $linkVars = '';
515
516 /**
517 * If set, edit icons are rendered aside content records. Must be set only if
518 * the ->beUserLogin flag is set and set_no_cache() must be called as well.
519 * @var string
520 */
521 public $displayEditIcons = '';
522
523 /**
524 * If set, edit icons are rendered aside individual fields of content. Must be
525 * set only if the ->beUserLogin flag is set and set_no_cache() must be called as
526 * well.
527 * @var string
528 */
529 public $displayFieldEditIcons = '';
530
531 /**
532 * Site language, 0 (zero) is default, int+ is uid pointing to a sys_language
533 * record. Should reflect which language menus, templates etc is displayed in
534 * (master language) - but not necessarily the content which could be falling
535 * back to default (see sys_language_content)
536 * @var int
537 */
538 public $sys_language_uid = 0;
539
540 /**
541 * Site language mode for content fall back.
542 * @var string
543 */
544 public $sys_language_mode = '';
545
546 /**
547 * Site content selection uid (can be different from sys_language_uid if content
548 * is to be selected from a fall-back language. Depends on sys_language_mode)
549 * @var int
550 */
551 public $sys_language_content = 0;
552
553 /**
554 * Site content overlay flag; If set - and sys_language_content is > 0 - ,
555 * records selected will try to look for a translation pointing to their uid. (If
556 * configured in [ctrl][languageField] / [ctrl][transOrigP...]
557 * Possible values: [0,1,hideNonTranslated]
558 * This flag is set based on TypoScript config.sys_language_overlay setting
559 *
560 * @var int|string
561 */
562 public $sys_language_contentOL = 0;
563
564 /**
565 * Is set to the iso code of the sys_language_content if that is properly defined
566 * by the sys_language record representing the sys_language_uid.
567 * @var string
568 */
569 public $sys_language_isocode = '';
570
571 /**
572 * 'Global' Storage for various applications. Keys should be 'tx_'.extKey for
573 * extensions.
574 * @var array
575 */
576 public $applicationData = [];
577
578 /**
579 * @var array
580 */
581 public $register = [];
582
583 /**
584 * Stack used for storing array and retrieving register arrays (see
585 * LOAD_REGISTER and RESTORE_REGISTER)
586 * @var array
587 */
588 public $registerStack = [];
589
590 /**
591 * Checking that the function is not called eternally. This is done by
592 * interrupting at a depth of 50
593 * @var int
594 */
595 public $cObjectDepthCounter = 50;
596
597 /**
598 * Used by RecordContentObject and ContentContentObject to ensure the a records is NOT
599 * rendered twice through it!
600 * @var array
601 */
602 public $recordRegister = [];
603
604 /**
605 * This is set to the [table]:[uid] of the latest record rendered. Note that
606 * class ContentObjectRenderer has an equal value, but that is pointing to the
607 * record delivered in the $data-array of the ContentObjectRenderer instance, if
608 * the cObjects CONTENT or RECORD created that instance
609 * @var string
610 */
611 public $currentRecord = '';
612
613 /**
614 * Used by class \TYPO3\CMS\Frontend\ContentObject\Menu\AbstractMenuContentObject
615 * to keep track of access-keys.
616 * @var array
617 */
618 public $accessKey = [];
619
620 /**
621 * Numerical array where image filenames are added if they are referenced in the
622 * rendered document. This includes only TYPO3 generated/inserted images.
623 * @var array
624 */
625 public $imagesOnPage = [];
626
627 /**
628 * Is set in ContentObjectRenderer->cImage() function to the info-array of the
629 * most recent rendered image. The information is used in ImageTextContentObject
630 * @var array
631 */
632 public $lastImageInfo = [];
633
634 /**
635 * Used to generate page-unique keys. Point is that uniqid() functions is very
636 * slow, so a unikey key is made based on this, see function uniqueHash()
637 * @var int
638 */
639 public $uniqueCounter = 0;
640
641 /**
642 * @var string
643 */
644 public $uniqueString = '';
645
646 /**
647 * This value will be used as the title for the page in the indexer (if
648 * indexing happens)
649 * @var string
650 */
651 public $indexedDocTitle = '';
652
653 /**
654 * Alternative page title (normally the title of the page record). Can be set
655 * from applications you make.
656 * @var string
657 */
658 public $altPageTitle = '';
659
660 /**
661 * The base URL set for the page header.
662 * @var string
663 */
664 public $baseUrl = '';
665
666 /**
667 * IDs we already rendered for this page (to make sure they are unique)
668 * @var array
669 */
670 private $usedUniqueIds = [];
671
672 /**
673 * Page content render object
674 *
675 * @var ContentObjectRenderer
676 */
677 public $cObj = '';
678
679 /**
680 * All page content is accumulated in this variable. See pagegen.php
681 * @var string
682 */
683 public $content = '';
684
685 /**
686 * Output charset of the websites content. This is the charset found in the
687 * header, meta tag etc. If different than utf-8 a conversion
688 * happens before output to browser. Defaults to utf-8.
689 * @var string
690 */
691 public $metaCharset = 'utf-8';
692
693 /**
694 * Set to the system language key (used on the site)
695 * @var string
696 */
697 public $lang = '';
698
699 /**
700 * Internal calculations for labels
701 *
702 * @var LanguageService
703 */
704 protected $languageService;
705
706 /**
707 * @var LockingStrategyInterface[][]
708 */
709 protected $locks = [];
710
711 /**
712 * @var PageRenderer
713 */
714 protected $pageRenderer = null;
715
716 /**
717 * The page cache object, use this to save pages to the cache and to
718 * retrieve them again
719 *
720 * @var \TYPO3\CMS\Core\Cache\Backend\AbstractBackend
721 */
722 protected $pageCache;
723
724 /**
725 * @var array
726 */
727 protected $pageCacheTags = [];
728
729 /**
730 * The cHash Service class used for cHash related functionality
731 *
732 * @var CacheHashCalculator
733 */
734 protected $cacheHash;
735
736 /**
737 * Runtime cache of domains per processed page ids.
738 *
739 * @var array
740 */
741 protected $domainDataCache = [];
742
743 /**
744 * Content type HTTP header being sent in the request.
745 * @todo Ticket: #63642 Should be refactored to a request/response model later
746 * @internal Should only be used by TYPO3 core for now
747 *
748 * @var string
749 */
750 protected $contentType = 'text/html';
751
752 /**
753 * Doctype to use
754 *
755 * @var string
756 */
757 public $xhtmlDoctype = '';
758
759 /**
760 * @var int
761 */
762 public $xhtmlVersion;
763
764 /**
765 * Originally requested id from the initial $_GET variable
766 *
767 * @var int
768 */
769 protected $requestedId;
770
771 /**
772 * Class constructor
773 * Takes a number of GET/POST input variable as arguments and stores them internally.
774 * The processing of these variables goes on later in this class.
775 * Also sets a unique string (->uniqueString) for this script instance; A md5 hash of the microtime()
776 *
777 * @param array $_ unused, previously defined to set TYPO3_CONF_VARS
778 * @param mixed $id The value of GeneralUtility::_GP('id')
779 * @param int $type The value of GeneralUtility::_GP('type')
780 * @param bool|string $no_cache The value of GeneralUtility::_GP('no_cache'), evaluated to 1/0
781 * @param string $cHash The value of GeneralUtility::_GP('cHash')
782 * @param string $_2 previously was used to define the jumpURL
783 * @param string $MP The value of GeneralUtility::_GP('MP')
784 * @see \TYPO3\CMS\Frontend\Http\RequestHandler
785 */
786 public function __construct($_ = null, $id, $type, $no_cache = '', $cHash = '', $_2 = null, $MP = '')
787 {
788 // Setting some variables:
789 $this->id = $id;
790 $this->type = $type;
791 if ($no_cache) {
792 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['disableNoCacheParameter']) {
793 $warning = '&no_cache=1 has been ignored because $TYPO3_CONF_VARS[\'FE\'][\'disableNoCacheParameter\'] is set!';
794 $this->getTimeTracker()->setTSlogMessage($warning, 2);
795 } else {
796 $warning = '&no_cache=1 has been supplied, so caching is disabled! URL: "' . GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL') . '"';
797 $this->disableCache();
798 }
799 // note: we need to instantiate the logger manually here since the injection happens after the constructor
800 GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__)->warning($warning);
801 }
802 $this->cHash = $cHash;
803 $this->MP = $GLOBALS['TYPO3_CONF_VARS']['FE']['enable_mount_pids'] ? (string)$MP : '';
804 $this->uniqueString = md5(microtime());
805 $this->initPageRenderer();
806 // Call post processing function for constructor:
807 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['tslib_fe-PostProc'] ?? [] as $_funcRef) {
808 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
809 }
810 $this->cacheHash = GeneralUtility::makeInstance(CacheHashCalculator::class);
811 $this->initCaches();
812 }
813
814 /**
815 * Initializes the page renderer object
816 */
817 protected function initPageRenderer()
818 {
819 if ($this->pageRenderer !== null) {
820 return;
821 }
822 $this->pageRenderer = GeneralUtility::makeInstance(PageRenderer::class);
823 $this->pageRenderer->setTemplateFile('EXT:frontend/Resources/Private/Templates/MainPage.html');
824 }
825
826 /**
827 * @param string $contentType
828 * @internal Should only be used by TYPO3 core for now
829 */
830 public function setContentType($contentType)
831 {
832 $this->contentType = $contentType;
833 }
834
835 /**
836 * Connect to SQL database. May exit after outputting an error message
837 * or some JavaScript redirecting to the install tool.
838 *
839 * @throws \RuntimeException
840 * @throws ServiceUnavailableException
841 */
842 public function connectToDB()
843 {
844 $connection = GeneralUtility::makeInstance(ConnectionPool::class)->getConnectionForTable('pages');
845 try {
846 $connection->connect();
847 } catch (ConnectionException $exception) {
848 // Cannot connect to current database
849 $message = 'Cannot connect to the configured database "' . $connection->getDatabase() . '"';
850 $this->logger->emergency($message, ['exception' => $exception]);
851 try {
852 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message);
853 $this->sendResponseAndExit($response);
854 } catch (ServiceUnavailableException $e) {
855 throw new ServiceUnavailableException($message, 1301648782);
856 }
857 }
858 // Call post processing function for DB connection:
859 $_params = ['pObj' => &$this];
860 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['connectToDB'] ?? [] as $_funcRef) {
861 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
862 }
863 }
864
865 /********************************************
866 *
867 * Initializing, resolving page id
868 *
869 ********************************************/
870 /**
871 * Initializes the caching system.
872 */
873 protected function initCaches()
874 {
875 $this->pageCache = GeneralUtility::makeInstance(CacheManager::class)->getCache('cache_pages');
876 }
877
878 /**
879 * Initializes the front-end login user.
880 */
881 public function initFEuser()
882 {
883 $this->fe_user = GeneralUtility::makeInstance(FrontendUserAuthentication::class);
884 // List of pid's acceptable
885 $pid = GeneralUtility::_GP('pid');
886 $this->fe_user->checkPid_value = $pid ? implode(',', GeneralUtility::intExplode(',', $pid)) : 0;
887 // Check if a session is transferred:
888 if (GeneralUtility::_GP('FE_SESSION_KEY')) {
889 $fe_sParts = explode('-', GeneralUtility::_GP('FE_SESSION_KEY'));
890 // If the session key hash check is OK:
891 if (md5($fe_sParts[0] . '/' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']) === (string)$fe_sParts[1]) {
892 $cookieName = FrontendUserAuthentication::getCookieName();
893 $_COOKIE[$cookieName] = $fe_sParts[0];
894 if (isset($_SERVER['HTTP_COOKIE'])) {
895 // See http://forge.typo3.org/issues/27740
896 $_SERVER['HTTP_COOKIE'] .= ';' . $cookieName . '=' . $fe_sParts[0];
897 }
898 $this->fe_user->forceSetCookie = true;
899 $this->fe_user->dontSetCookie = false;
900 unset($cookieName);
901 }
902 }
903 $this->fe_user->start();
904 $this->fe_user->unpack_uc();
905
906 // Call hook for possible manipulation of frontend user object
907 $_params = ['pObj' => &$this];
908 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['initFEuser'] ?? [] as $_funcRef) {
909 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
910 }
911 }
912
913 /**
914 * Initializes the front-end user groups.
915 * Sets ->loginUser and ->gr_list based on front-end user status.
916 */
917 public function initUserGroups()
918 {
919 // This affects the hidden-flag selecting the fe_groups for the user!
920 $this->fe_user->showHiddenRecords = $this->showHiddenRecords;
921 // no matter if we have an active user we try to fetch matching groups which can be set without an user (simulation for instance!)
922 $this->fe_user->fetchGroupData();
923 if (is_array($this->fe_user->user) && !empty($this->fe_user->groupData['uid'])) {
924 // global flag!
925 $this->loginUser = true;
926 // 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!
927 $this->gr_list = '0,-2';
928 $gr_array = $this->fe_user->groupData['uid'];
929 } else {
930 $this->loginUser = false;
931 // 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!
932 $this->gr_list = '0,-1';
933 if ($this->loginAllowedInBranch) {
934 // 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.
935 $gr_array = $this->fe_user->groupData['uid'];
936 } else {
937 // Set to blank since we will NOT risk any groups being set when no logins are allowed!
938 $gr_array = [];
939 }
940 }
941 // Clean up.
942 // Make unique...
943 $gr_array = array_unique($gr_array);
944 // sort
945 sort($gr_array);
946 if (!empty($gr_array) && !$this->loginAllowedInBranch_mode) {
947 $this->gr_list .= ',' . implode(',', $gr_array);
948 }
949
950 // For every 60 seconds the is_online timestamp for a logged-in user is updated
951 if ($this->loginUser) {
952 $this->fe_user->updateOnlineTimestamp();
953 }
954
955 $this->logger->debug('Valid usergroups for TSFE: ' . $this->gr_list);
956 }
957
958 /**
959 * Checking if a user is logged in or a group constellation different from "0,-1"
960 *
961 * @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!)
962 */
963 public function isUserOrGroupSet()
964 {
965 return is_array($this->fe_user->user) || $this->gr_list !== '0,-1';
966 }
967
968 /**
969 * Provides ways to bypass the '?id=[xxx]&type=[xx]' format, using either PATH_INFO or virtual HTML-documents (using Apache mod_rewrite)
970 *
971 * Two options:
972 * 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)
973 * 2) Using hook which enables features like those provided from "realurl" extension (AKA "Speaking URLs")
974 */
975 public function checkAlternativeIdMethods()
976 {
977 $this->siteScript = GeneralUtility::getIndpEnv('TYPO3_SITE_SCRIPT');
978 // Call post processing function for custom URL methods.
979 $_params = ['pObj' => &$this];
980 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkAlternativeIdMethods-PostProc'] ?? [] as $_funcRef) {
981 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
982 }
983 }
984
985 /**
986 * Clears the preview-flags, sets sim_exec_time to current time.
987 * Hidden pages must be hidden as default, $GLOBALS['SIM_EXEC_TIME'] is set to $GLOBALS['EXEC_TIME']
988 * in bootstrap initializeGlobalTimeVariables(). Alter it by adding or subtracting seconds.
989 */
990 public function clear_preview()
991 {
992 $this->showHiddenPage = false;
993 $this->showHiddenRecords = false;
994 $GLOBALS['SIM_EXEC_TIME'] = $GLOBALS['EXEC_TIME'];
995 $GLOBALS['SIM_ACCESS_TIME'] = $GLOBALS['ACCESS_TIME'];
996 $this->fePreview = 0;
997 }
998
999 /**
1000 * Checks if a backend user is logged in
1001 *
1002 * @return bool whether a backend user is logged in
1003 */
1004 public function isBackendUserLoggedIn()
1005 {
1006 return (bool)$this->beUserLogin;
1007 }
1008
1009 /**
1010 * Creates the backend user object and returns it.
1011 *
1012 * @return FrontendBackendUserAuthentication the backend user object
1013 */
1014 public function initializeBackendUser()
1015 {
1016 // PRE BE_USER HOOK
1017 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['preBeUser'] ?? [] as $_funcRef) {
1018 $_params = [];
1019 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1020 }
1021 $backendUserObject = null;
1022 // If the backend cookie is set,
1023 // we proceed and check if a backend user is logged in.
1024 if ($_COOKIE[BackendUserAuthentication::getCookieName()]) {
1025 $GLOBALS['TYPO3_MISC']['microtime_BE_USER_start'] = microtime(true);
1026 $this->getTimeTracker()->push('Back End user initialized', '');
1027 $this->beUserLogin = false;
1028 // New backend user object
1029 $backendUserObject = GeneralUtility::makeInstance(FrontendBackendUserAuthentication::class);
1030 $backendUserObject->start();
1031 $backendUserObject->unpack_uc();
1032 if (!empty($backendUserObject->user['uid'])) {
1033 $backendUserObject->fetchGroupData();
1034 }
1035 // Unset the user initialization if any setting / restriction applies
1036 if (!$backendUserObject->checkBackendAccessSettingsFromInitPhp()) {
1037 $backendUserObject = null;
1038 } elseif (!empty($backendUserObject->user['uid'])) {
1039 // If the user is active now, let the controller know
1040 $this->beUserLogin = true;
1041 } else {
1042 $backendUserObject = null;
1043 }
1044 $this->getTimeTracker()->pull();
1045 $GLOBALS['TYPO3_MISC']['microtime_BE_USER_end'] = microtime(true);
1046 }
1047 // POST BE_USER HOOK
1048 $_params = [
1049 'BE_USER' => &$backendUserObject
1050 ];
1051 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/index_ts.php']['postBeUser'] ?? [] as $_funcRef) {
1052 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1053 }
1054 return $backendUserObject;
1055 }
1056
1057 /**
1058 * Determines the id and evaluates any preview settings
1059 * Basically this function is about determining whether a backend user is logged in,
1060 * if he has read access to the page and if he's previewing the page.
1061 * That all determines which id to show and how to initialize the id.
1062 */
1063 public function determineId()
1064 {
1065 // Call pre processing function for id determination
1066 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PreProcessing'] ?? [] as $functionReference) {
1067 $parameters = ['parentObject' => $this];
1068 GeneralUtility::callUserFunction($functionReference, $parameters, $this);
1069 }
1070 // If there is a Backend login we are going to check for any preview settings
1071 $originalFrontendUserGroups = $this->applyPreviewSettings($this->getBackendUser());
1072 // If the front-end is showing a preview, caching MUST be disabled.
1073 if ($this->fePreview) {
1074 $this->disableCache();
1075 }
1076 // Now, get the id, validate access etc:
1077 $this->fetch_the_id();
1078 // Check if backend user has read access to this page. If not, recalculate the id.
1079 if ($this->beUserLogin && $this->fePreview && !$this->getBackendUser()->doesUserHaveAccess($this->page, Permission::PAGE_SHOW)) {
1080 // Resetting
1081 $this->clear_preview();
1082 $this->fe_user->user[$this->fe_user->usergroup_column] = $originalFrontendUserGroups;
1083 // Fetching the id again, now with the preview settings reset.
1084 $this->fetch_the_id();
1085 }
1086 // Checks if user logins are blocked for a certain branch and if so, will unset user login and re-fetch ID.
1087 $this->loginAllowedInBranch = $this->checkIfLoginAllowedInBranch();
1088 // Logins are not allowed:
1089 if (!$this->loginAllowedInBranch) {
1090 // Only if there is a login will we run this...
1091 if ($this->isUserOrGroupSet()) {
1092 if ($this->loginAllowedInBranch_mode === 'all') {
1093 // Clear out user and group:
1094 $this->fe_user->hideActiveLogin();
1095 $this->gr_list = '0,-1';
1096 } else {
1097 $this->gr_list = '0,-2';
1098 }
1099 // Fetching the id again, now with the preview settings reset.
1100 $this->fetch_the_id();
1101 }
1102 }
1103 // Final cleaning.
1104 // Make sure it's an integer
1105 $this->id = ($this->contentPid = (int)$this->id);
1106 // Make sure it's an integer
1107 $this->type = (int)$this->type;
1108 // Call post processing function for id determination:
1109 $_params = ['pObj' => &$this];
1110 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['determineId-PostProc'] ?? [] as $_funcRef) {
1111 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1112 }
1113 }
1114
1115 /**
1116 * Evaluates admin panel or workspace settings to see if
1117 * visibility settings like
1118 * - $fePreview
1119 * - $showHiddenPage
1120 * - $showHiddenRecords
1121 * - $simUserGroup
1122 * should be applied to the current object.
1123 *
1124 * @param FrontendBackendUserAuthentication $backendUser
1125 * @return string|null null if no changes to the current frontend usergroups have been made, otherwise the original list of frontend usergroups
1126 * @private do not use this in your extension code.
1127 */
1128 protected function applyPreviewSettings($backendUser = null)
1129 {
1130 if (!$backendUser) {
1131 return null;
1132 }
1133 $originalFrontendUser = null;
1134 if ($this->fe_user->user) {
1135 $originalFrontendUser = $this->fe_user->user[$this->fe_user->usergroup_column];
1136 }
1137
1138 // The preview flag is set if the current page turns out to be hidden
1139 if ($this->id && $this->determineIdIsHiddenPage()) {
1140 $this->fePreview = 1;
1141 $this->showHiddenPage = true;
1142 }
1143 // The preview flag will be set if an offline workspace will be previewed
1144 if ($this->whichWorkspace() > 0) {
1145 $this->fePreview = 1;
1146 }
1147 return $this->simUserGroup ? $originalFrontendUser : null;
1148 }
1149
1150 /**
1151 * Checks if the page is hidden in the active workspace.
1152 * If it is hidden, preview flags will be set.
1153 *
1154 * @return bool
1155 */
1156 protected function determineIdIsHiddenPage()
1157 {
1158 $field = MathUtility::canBeInterpretedAsInteger($this->id) ? 'uid' : 'alias';
1159
1160 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1161 ->getQueryBuilderForTable('pages');
1162 $queryBuilder
1163 ->getRestrictions()
1164 ->removeAll()
1165 ->add(GeneralUtility::makeInstance(DeletedRestriction::class));
1166
1167 $page = $queryBuilder
1168 ->select('uid', 'hidden', 'starttime', 'endtime')
1169 ->from('pages')
1170 ->where(
1171 $queryBuilder->expr()->eq($field, $queryBuilder->createNamedParameter($this->id)),
1172 $queryBuilder->expr()->gte('pid', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT))
1173 )
1174 ->setMaxResults(1)
1175 ->execute()
1176 ->fetch();
1177
1178 if ($this->whichWorkspace() > 0) {
1179 // Fetch overlay of page if in workspace and check if it is hidden
1180 $pageSelectObject = GeneralUtility::makeInstance(PageRepository::class);
1181 $pageSelectObject->versioningPreview = true;
1182 $pageSelectObject->init(false);
1183 $targetPage = $pageSelectObject->getWorkspaceVersionOfRecord($this->whichWorkspace(), 'pages', $page['uid']);
1184 $result = $targetPage === -1 || $targetPage === -2;
1185 } else {
1186 $result = is_array($page) && ($page['hidden'] || $page['starttime'] > $GLOBALS['SIM_EXEC_TIME'] || $page['endtime'] != 0 && $page['endtime'] <= $GLOBALS['SIM_EXEC_TIME']);
1187 }
1188 return $result;
1189 }
1190
1191 /**
1192 * Resolves the page id and sets up several related properties.
1193 *
1194 * If $this->id is not set at all or is not a plain integer, the method
1195 * does it's best to set the value to an integer. Resolving is based on
1196 * this options:
1197 *
1198 * - Splitting $this->id if it contains an additional type parameter.
1199 * - Getting the id for an alias in $this->id
1200 * - Finding the domain record start page
1201 * - First visible page
1202 * - Relocating the id below the domain record if outside
1203 *
1204 * The following properties may be set up or updated:
1205 *
1206 * - id
1207 * - requestedId
1208 * - type
1209 * - domainStartPage
1210 * - sys_page
1211 * - sys_page->where_groupAccess
1212 * - sys_page->where_hid_del
1213 * - loginUser
1214 * - gr_list
1215 * - no_cache
1216 * - register['SYS_LASTCHANGED']
1217 * - pageNotFound
1218 *
1219 * Via getPageAndRootlineWithDomain()
1220 *
1221 * - rootLine
1222 * - page
1223 * - MP
1224 * - originalShortcutPage
1225 * - originalMountPointPage
1226 * - pageAccessFailureHistory['direct_access']
1227 * - pageNotFound
1228 *
1229 * @todo:
1230 *
1231 * On the first impression the method does to much. This is increased by
1232 * the fact, that is is called repeated times by the method determineId.
1233 * The reasons are manifold.
1234 *
1235 * 1.) The first part, the creation of sys_page, the type and alias
1236 * resolution don't need to be repeated. They could be separated to be
1237 * called only once.
1238 *
1239 * 2.) The user group setup could be done once on a higher level.
1240 *
1241 * 3.) The workflow of the resolution could be elaborated to be less
1242 * tangled. Maybe the check of the page id to be below the domain via the
1243 * root line doesn't need to be done each time, but for the final result
1244 * only.
1245 *
1246 * 4.) The root line does not need to be directly addressed by this class.
1247 * A root line is always related to one page. The rootline could be handled
1248 * indirectly by page objects. Page objects still don't exist.
1249 *
1250 * @throws ServiceUnavailableException
1251 * @access private
1252 */
1253 public function fetch_the_id()
1254 {
1255 $timeTracker = $this->getTimeTracker();
1256 $timeTracker->push('fetch_the_id initialize/', '');
1257 // Initialize the page-select functions.
1258 $this->sys_page = GeneralUtility::makeInstance(PageRepository::class);
1259 $this->sys_page->versioningPreview = $this->whichWorkspace() > 0 || (bool)GeneralUtility::_GP('ADMCMD_view');
1260 $this->sys_page->versioningWorkspaceId = $this->whichWorkspace();
1261 $this->sys_page->init($this->showHiddenPage);
1262 // Set the valid usergroups for FE
1263 $this->initUserGroups();
1264 // Sets sys_page where-clause
1265 $this->setSysPageWhereClause();
1266 // If $this->id is a string, it's an alias
1267 $this->checkAndSetAlias();
1268 // The id and type is set to the integer-value - just to be sure...
1269 $this->id = (int)$this->id;
1270 $this->type = (int)$this->type;
1271 $timeTracker->pull();
1272 // We find the first page belonging to the current domain
1273 $timeTracker->push('fetch_the_id domain/', '');
1274 // The page_id of the current domain
1275 $this->domainStartPage = $this->findDomainRecord($GLOBALS['TYPO3_CONF_VARS']['SYS']['recursiveDomainSearch']);
1276 if (!$this->id) {
1277 if ($this->domainStartPage) {
1278 // If the id was not previously set, set it to the id of the domain.
1279 $this->id = $this->domainStartPage;
1280 } else {
1281 // Find the first 'visible' page in that domain
1282 $theFirstPage = $this->sys_page->getFirstWebPage($this->id);
1283 if ($theFirstPage) {
1284 $this->id = $theFirstPage['uid'];
1285 } else {
1286 $message = 'No pages are found on the rootlevel!';
1287 $this->logger->alert($message);
1288 try {
1289 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message);
1290 $this->sendResponseAndExit($response);
1291 } catch (ServiceUnavailableException $e) {
1292 throw new ServiceUnavailableException($message, 1301648975);
1293 }
1294 }
1295 }
1296 }
1297 $timeTracker->pull();
1298 $timeTracker->push('fetch_the_id rootLine/', '');
1299 // We store the originally requested id
1300 $this->requestedId = $this->id;
1301 try {
1302 $this->getPageAndRootlineWithDomain($this->domainStartPage);
1303 } catch (ShortcutTargetPageNotFoundException $e) {
1304 $this->pageNotFound = 1;
1305 }
1306 $timeTracker->pull();
1307 // @todo: in the future, the check if "pageNotFound_handling" is configured should go away, but this breaks
1308 // Functional tests in workspaces currently
1309 if ($this->pageNotFound && $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling']) {
1310 $pNotFoundMsg = [
1311 1 => 'ID was not an accessible page',
1312 2 => 'Subsection was found and not accessible',
1313 3 => 'ID was outside the domain',
1314 4 => 'The requested page alias does not exist'
1315 ];
1316 $message = $pNotFoundMsg[$this->pageNotFound];
1317 if ($this->pageNotFound === 1 || $this->pageNotFound === 2) {
1318 $response = GeneralUtility::makeInstance(ErrorController::class)->accessDeniedAction($message, $this->getPageAccessFailureReasons());
1319 } else {
1320 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($message, $this->getPageAccessFailureReasons());
1321 }
1322 $this->sendResponseAndExit($response);
1323 }
1324 // Init SYS_LASTCHANGED
1325 $this->register['SYS_LASTCHANGED'] = (int)$this->page['tstamp'];
1326 if ($this->register['SYS_LASTCHANGED'] < (int)$this->page['SYS_LASTCHANGED']) {
1327 $this->register['SYS_LASTCHANGED'] = (int)$this->page['SYS_LASTCHANGED'];
1328 }
1329 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['fetchPageId-PostProcessing'] ?? [] as $functionReference) {
1330 $parameters = ['parentObject' => $this];
1331 GeneralUtility::callUserFunction($functionReference, $parameters, $this);
1332 }
1333 }
1334
1335 /**
1336 * Loads the page and root line records based on $this->id
1337 *
1338 * A final page and the matching root line are determined and loaded by
1339 * the algorithm defined by this method.
1340 *
1341 * First it loads the initial page from the page repository for $this->id.
1342 * If that can't be loaded directly, it gets the root line for $this->id.
1343 * It walks up the root line towards the root page until the page
1344 * repository can deliver a page record. (The loading restrictions of
1345 * the root line records are more liberal than that of the page record.)
1346 *
1347 * Now the page type is evaluated and handled if necessary. If the page is
1348 * a short cut, it is replaced by the target page. If the page is a mount
1349 * point in overlay mode, the page is replaced by the mounted page.
1350 *
1351 * After this potential replacements are done, the root line is loaded
1352 * (again) for this page record. It walks up the root line up to
1353 * the first viewable record.
1354 *
1355 * (While upon the first accessibility check of the root line it was done
1356 * by loading page by page from the page repository, this time the method
1357 * checkRootlineForIncludeSection() is used to find the most distant
1358 * accessible page within the root line.)
1359 *
1360 * Having found the final page id, the page record and the root line are
1361 * loaded for last time by this method.
1362 *
1363 * Exceptions may be thrown for DOKTYPE_SPACER and not loadable page records
1364 * or root lines.
1365 *
1366 * If $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'] is set,
1367 * instead of throwing an exception it's handled by a page unavailable
1368 * handler.
1369 *
1370 * May set or update this properties:
1371 *
1372 * @see TypoScriptFrontendController::$id
1373 * @see TypoScriptFrontendController::$MP
1374 * @see TypoScriptFrontendController::$page
1375 * @see TypoScriptFrontendController::$pageNotFound
1376 * @see TypoScriptFrontendController::$pageAccessFailureHistory
1377 * @see TypoScriptFrontendController::$originalMountPointPage
1378 * @see TypoScriptFrontendController::$originalShortcutPage
1379 *
1380 * @throws ServiceUnavailableException
1381 * @throws PageNotFoundException
1382 * @access private
1383 */
1384 public function getPageAndRootline()
1385 {
1386 $this->resolveTranslatedPageId();
1387 if (empty($this->page)) {
1388 // If no page, we try to find the page before in the rootLine.
1389 // Page is 'not found' in case the id itself was not an accessible page. code 1
1390 $this->pageNotFound = 1;
1391 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1392 if (!empty($this->rootLine)) {
1393 $c = count($this->rootLine) - 1;
1394 while ($c > 0) {
1395 // Add to page access failure history:
1396 $this->pageAccessFailureHistory['direct_access'][] = $this->rootLine[$c];
1397 // Decrease to next page in rootline and check the access to that, if OK, set as page record and ID value.
1398 $c--;
1399 $this->id = $this->rootLine[$c]['uid'];
1400 $this->page = $this->sys_page->getPage($this->id);
1401 if (!empty($this->page)) {
1402 break;
1403 }
1404 }
1405 }
1406 // If still no page...
1407 if (empty($this->page)) {
1408 $message = 'The requested page does not exist!';
1409 $this->logger->error($message);
1410 try {
1411 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($message, $this->getPageAccessFailureReasons());
1412 $this->sendResponseAndExit($response);
1413 } catch (PageNotFoundException $e) {
1414 throw new PageNotFoundException($message, 1301648780);
1415 }
1416 }
1417 }
1418 // Spacer is not accessible in frontend
1419 if ($this->page['doktype'] == PageRepository::DOKTYPE_SPACER) {
1420 $message = 'The requested page does not exist!';
1421 $this->logger->error($message);
1422 try {
1423 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($message, $this->getPageAccessFailureReasons());
1424 $this->sendResponseAndExit($response);
1425 } catch (PageNotFoundException $e) {
1426 throw new PageNotFoundException($message, 1301648781);
1427 }
1428 }
1429 // Is the ID a link to another page??
1430 if ($this->page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1431 // 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.
1432 $this->MP = '';
1433 // saving the page so that we can check later - when we know
1434 // about languages - whether we took the correct shortcut or
1435 // whether a translation of the page overwrites the shortcut
1436 // target and we need to follow the new target
1437 $this->originalShortcutPage = $this->page;
1438 $this->page = $this->getPageShortcut($this->page['shortcut'], $this->page['shortcut_mode'], $this->page['uid']);
1439 $this->id = $this->page['uid'];
1440 }
1441 // If the page is a mountpoint which should be overlaid with the contents of the mounted page,
1442 // it must never be accessible directly, but only in the mountpoint context. Therefore we change
1443 // the current ID and the user is redirected by checkPageForMountpointRedirect().
1444 if ($this->page['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT && $this->page['mount_pid_ol']) {
1445 $this->originalMountPointPage = $this->page;
1446 $this->page = $this->sys_page->getPage($this->page['mount_pid']);
1447 if (empty($this->page)) {
1448 $message = 'This page (ID ' . $this->originalMountPointPage['uid'] . ') is of type "Mount point" and '
1449 . 'mounts a page which is not accessible (ID ' . $this->originalMountPointPage['mount_pid'] . ').';
1450 throw new PageNotFoundException($message, 1402043263);
1451 }
1452 $this->MP = $this->page['uid'] . '-' . $this->originalMountPointPage['uid'];
1453 $this->id = $this->page['uid'];
1454 }
1455 // Gets the rootLine
1456 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1457 // If not rootline we're off...
1458 if (empty($this->rootLine)) {
1459 $message = 'The requested page didn\'t have a proper connection to the tree-root!';
1460 $this->logger->error($message);
1461 try {
1462 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message, $this->getPageAccessFailureReasons());
1463 $this->sendResponseAndExit($response);
1464 } catch (ServiceUnavailableException $e) {
1465 throw new ServiceUnavailableException($message, 1301648167);
1466 }
1467 }
1468 // Checking for include section regarding the hidden/starttime/endtime/fe_user (that is access control of a whole subbranch!)
1469 if ($this->checkRootlineForIncludeSection()) {
1470 if (empty($this->rootLine)) {
1471 $message = 'The requested page was not accessible!';
1472 try {
1473 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message, $this->getPageAccessFailureReasons());
1474 $this->sendResponseAndExit($response);
1475 } catch (ServiceUnavailableException $e) {
1476 $this->logger->warning($message);
1477 throw new ServiceUnavailableException($message, 1301648234);
1478 }
1479 } else {
1480 $el = reset($this->rootLine);
1481 $this->id = $el['uid'];
1482 $this->page = $this->sys_page->getPage($this->id);
1483 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
1484 }
1485 }
1486 }
1487
1488 /**
1489 * If $this->id contains a translated page record, this needs to be resolved to the default language
1490 * in order for all rootline functionality and access restrictions to be in place further on.
1491 *
1492 * Additionally, if a translated page is found, $this->sys_language_uid/sys_language_content is set as well.
1493 */
1494 protected function resolveTranslatedPageId()
1495 {
1496 $this->page = $this->sys_page->getPage($this->id);
1497 // Accessed a default language page record, nothing to resolve
1498 if (empty($this->page) || (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']] === 0) {
1499 return;
1500 }
1501 $this->sys_language_uid = (int)$this->page[$GLOBALS['TCA']['pages']['ctrl']['languageField']];
1502 $this->sys_language_content = $this->sys_language_uid;
1503 $this->page = $this->sys_page->getPage($this->page[$GLOBALS['TCA']['pages']['ctrl']['transOrigPointerField']]);
1504 $this->id = $this->page['uid'];
1505 // For common best-practice reasons, this is set, however, will be optional for new routing mechanisms
1506 $this->mergingWithGetVars(['L' => $this->sys_language_uid]);
1507 }
1508
1509 /**
1510 * Get page shortcut; Finds the records pointed to by input value $SC (the shortcut value)
1511 *
1512 * @param int $SC The value of the "shortcut" field from the pages record
1513 * @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
1514 * @param int $thisUid The current page UID of the page which is a shortcut
1515 * @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...)
1516 * @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.
1517 * @param bool $disableGroupCheck If true, the group check is disabled when fetching the target page (needed e.g. for menu generation)
1518 * @throws \RuntimeException
1519 * @throws ShortcutTargetPageNotFoundException
1520 * @return mixed Returns the page record of the page that the shortcut pointed to.
1521 * @access private
1522 * @see getPageAndRootline()
1523 */
1524 public function getPageShortcut($SC, $mode, $thisUid, $itera = 20, $pageLog = [], $disableGroupCheck = false)
1525 {
1526 $idArray = GeneralUtility::intExplode(',', $SC);
1527 // Find $page record depending on shortcut mode:
1528 switch ($mode) {
1529 case PageRepository::SHORTCUT_MODE_FIRST_SUBPAGE:
1530
1531 case PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE:
1532 $pageArray = $this->sys_page->getMenu($idArray[0] ? $idArray[0] : $thisUid, '*', 'sorting', 'AND pages.doktype<199 AND pages.doktype!=' . PageRepository::DOKTYPE_BE_USER_SECTION);
1533 $pO = 0;
1534 if ($mode == PageRepository::SHORTCUT_MODE_RANDOM_SUBPAGE && !empty($pageArray)) {
1535 $randval = (int)rand(0, count($pageArray) - 1);
1536 $pO = $randval;
1537 }
1538 $c = 0;
1539 $page = [];
1540 foreach ($pageArray as $pV) {
1541 if ($c === $pO) {
1542 $page = $pV;
1543 break;
1544 }
1545 $c++;
1546 }
1547 if (empty($page)) {
1548 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a subpage. ' . 'However, this page has no accessible subpages.';
1549 throw new ShortcutTargetPageNotFoundException($message, 1301648328);
1550 }
1551 break;
1552 case PageRepository::SHORTCUT_MODE_PARENT_PAGE:
1553 $parent = $this->sys_page->getPage($idArray[0] ? $idArray[0] : $thisUid, $disableGroupCheck);
1554 $page = $this->sys_page->getPage($parent['pid'], $disableGroupCheck);
1555 if (empty($page)) {
1556 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to its parent page. ' . 'However, the parent page is not accessible.';
1557 throw new ShortcutTargetPageNotFoundException($message, 1301648358);
1558 }
1559 break;
1560 default:
1561 $page = $this->sys_page->getPage($idArray[0], $disableGroupCheck);
1562 if (empty($page)) {
1563 $message = 'This page (ID ' . $thisUid . ') is of type "Shortcut" and configured to redirect to a page, which is not accessible (ID ' . $idArray[0] . ').';
1564 throw new ShortcutTargetPageNotFoundException($message, 1301648404);
1565 }
1566 }
1567 // Check if short cut page was a shortcut itself, if so look up recursively:
1568 if ($page['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
1569 if (!in_array($page['uid'], $pageLog) && $itera > 0) {
1570 $pageLog[] = $page['uid'];
1571 $page = $this->getPageShortcut($page['shortcut'], $page['shortcut_mode'], $page['uid'], $itera - 1, $pageLog, $disableGroupCheck);
1572 } else {
1573 $pageLog[] = $page['uid'];
1574 $message = 'Page shortcuts were looping in uids ' . implode(',', $pageLog) . '...!';
1575 $this->logger->error($message);
1576 throw new \RuntimeException($message, 1294587212);
1577 }
1578 }
1579 // Return resulting page:
1580 return $page;
1581 }
1582
1583 /**
1584 * Checks if visibility of the page is blocked upwards in the root line.
1585 *
1586 * If any page in the root line is blocking visibility, true is returend.
1587 *
1588 * All pages from the blocking page downwards are removed from the root
1589 * line, so that the remaning pages can be used to relocate the page up
1590 * to lowest visible page.
1591 *
1592 * The blocking feature of a page must be turned on by setting the page
1593 * record field 'extendToSubpages' to 1.
1594 *
1595 * The following fields are evaluated then:
1596 *
1597 * hidden, starttime, endtime, fe_group
1598 *
1599 * @todo Find a better name, i.e. checkVisibilityByRootLine
1600 * @todo Invert boolean return value. Return true if visible.
1601 *
1602 * @return bool
1603 * @access private
1604 */
1605 public function checkRootlineForIncludeSection(): bool
1606 {
1607 $c = count($this->rootLine);
1608 $removeTheRestFlag = false;
1609 for ($a = 0; $a < $c; $a++) {
1610 if (!$this->checkPagerecordForIncludeSection($this->rootLine[$a])) {
1611 // Add to page access failure history:
1612 $this->pageAccessFailureHistory['sub_section'][] = $this->rootLine[$a];
1613 $removeTheRestFlag = true;
1614 }
1615
1616 if ($this->rootLine[$a]['doktype'] == PageRepository::DOKTYPE_BE_USER_SECTION) {
1617 // If there is a backend user logged in, check if he has read access to the page:
1618 if ($this->beUserLogin) {
1619 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1620 ->getQueryBuilderForTable('pages');
1621
1622 $queryBuilder
1623 ->getRestrictions()
1624 ->removeAll();
1625
1626 $row = $queryBuilder
1627 ->select('uid')
1628 ->from('pages')
1629 ->where(
1630 $queryBuilder->expr()->eq(
1631 'uid',
1632 $queryBuilder->createNamedParameter($this->id, \PDO::PARAM_INT)
1633 ),
1634 $this->getBackendUser()->getPagePermsClause(Permission::PAGE_SHOW)
1635 )
1636 ->execute()
1637 ->fetch();
1638
1639 // versionOL()?
1640 if (!$row) {
1641 // 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...
1642 $removeTheRestFlag = true;
1643 }
1644 } else {
1645 // Don't go here, if there is no backend user logged in.
1646 $removeTheRestFlag = true;
1647 }
1648 }
1649 if ($removeTheRestFlag) {
1650 // Page is 'not found' in case a subsection was found and not accessible, code 2
1651 $this->pageNotFound = 2;
1652 unset($this->rootLine[$a]);
1653 break;
1654 }
1655 }
1656 return $removeTheRestFlag;
1657 }
1658
1659 /**
1660 * Checks page record for enableFields
1661 * Returns TRUE if enableFields does not disable the page record.
1662 * Takes notice of the ->showHiddenPage flag and uses SIM_ACCESS_TIME for start/endtime evaluation
1663 *
1664 * @param array $row The page record to evaluate (needs fields: hidden, starttime, endtime, fe_group)
1665 * @param bool $bypassGroupCheck Bypass group-check
1666 * @return bool TRUE, if record is viewable.
1667 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList(), checkPagerecordForIncludeSection()
1668 */
1669 public function checkEnableFields($row, $bypassGroupCheck = false)
1670 {
1671 $_params = ['pObj' => $this, 'row' => &$row, 'bypassGroupCheck' => &$bypassGroupCheck];
1672 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['hook_checkEnableFields'] ?? [] as $_funcRef) {
1673 // Call hooks: If one returns FALSE, method execution is aborted with result "This record is not available"
1674 $return = GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1675 if ($return === false) {
1676 return false;
1677 }
1678 }
1679 if ((!$row['hidden'] || $this->showHiddenPage) && $row['starttime'] <= $GLOBALS['SIM_ACCESS_TIME'] && ($row['endtime'] == 0 || $row['endtime'] > $GLOBALS['SIM_ACCESS_TIME']) && ($bypassGroupCheck || $this->checkPageGroupAccess($row))) {
1680 return true;
1681 }
1682 return false;
1683 }
1684
1685 /**
1686 * Check group access against a page record
1687 *
1688 * @param array $row The page record to evaluate (needs field: fe_group)
1689 * @param mixed $groupList List of group id's (comma list or array). Default is $this->gr_list
1690 * @return bool TRUE, if group access is granted.
1691 * @access private
1692 */
1693 public function checkPageGroupAccess($row, $groupList = null)
1694 {
1695 if ($groupList === null) {
1696 $groupList = $this->gr_list;
1697 }
1698 if (!is_array($groupList)) {
1699 $groupList = explode(',', $groupList);
1700 }
1701 $pageGroupList = explode(',', $row['fe_group'] ?: 0);
1702 return count(array_intersect($groupList, $pageGroupList)) > 0;
1703 }
1704
1705 /**
1706 * Checks if the current page of the root line is visible.
1707 *
1708 * If the field extendToSubpages is 0, access is granted,
1709 * else the fields hidden, starttime, endtime, fe_group are evaluated.
1710 *
1711 * @todo Find a better name, i.e. isVisibleRecord()
1712 *
1713 * @param array $row The page record
1714 * @return bool true if visible
1715 * @access private
1716 * @see checkEnableFields()
1717 * @see \TYPO3\CMS\Frontend\ContentObject\ContentObjectRenderer::getTreeList()
1718 * @see checkRootlineForIncludeSection()
1719 */
1720 public function checkPagerecordForIncludeSection(array $row): bool
1721 {
1722 return !$row['extendToSubpages'] || $this->checkEnableFields($row);
1723 }
1724
1725 /**
1726 * 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!)
1727 *
1728 * @return bool returns TRUE if logins are OK, otherwise FALSE (and then the login user must be unset!)
1729 */
1730 public function checkIfLoginAllowedInBranch()
1731 {
1732 // Initialize:
1733 $c = count($this->rootLine);
1734 $loginAllowed = true;
1735 // Traverse root line from root and outwards:
1736 for ($a = 0; $a < $c; $a++) {
1737 // If a value is set for login state:
1738 if ($this->rootLine[$a]['fe_login_mode'] > 0) {
1739 // Determine state from value:
1740 if ((int)$this->rootLine[$a]['fe_login_mode'] === 1) {
1741 $loginAllowed = false;
1742 $this->loginAllowedInBranch_mode = 'all';
1743 } elseif ((int)$this->rootLine[$a]['fe_login_mode'] === 3) {
1744 $loginAllowed = false;
1745 $this->loginAllowedInBranch_mode = 'groups';
1746 } else {
1747 $loginAllowed = true;
1748 }
1749 }
1750 }
1751 return $loginAllowed;
1752 }
1753
1754 /**
1755 * 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
1756 *
1757 * @return array Summary of why page access was not allowed.
1758 */
1759 public function getPageAccessFailureReasons()
1760 {
1761 $output = [];
1762 $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'] : []);
1763 if (!empty($combinedRecords)) {
1764 foreach ($combinedRecords as $k => $pagerec) {
1765 // 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
1766 // 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!
1767 if (!$k || $pagerec['extendToSubpages']) {
1768 if ($pagerec['hidden']) {
1769 $output['hidden'][$pagerec['uid']] = true;
1770 }
1771 if ($pagerec['starttime'] > $GLOBALS['SIM_ACCESS_TIME']) {
1772 $output['starttime'][$pagerec['uid']] = $pagerec['starttime'];
1773 }
1774 if ($pagerec['endtime'] != 0 && $pagerec['endtime'] <= $GLOBALS['SIM_ACCESS_TIME']) {
1775 $output['endtime'][$pagerec['uid']] = $pagerec['endtime'];
1776 }
1777 if (!$this->checkPageGroupAccess($pagerec)) {
1778 $output['fe_group'][$pagerec['uid']] = $pagerec['fe_group'];
1779 }
1780 }
1781 }
1782 }
1783 return $output;
1784 }
1785
1786 /**
1787 * Gets ->page and ->rootline information based on ->id. ->id may change during this operation.
1788 * If not inside domain, then default to first page in domain.
1789 *
1790 * @param int $domainStartPage Page uid of the page where the found domain record is (pid of the domain record)
1791 * @access private
1792 */
1793 public function getPageAndRootlineWithDomain($domainStartPage)
1794 {
1795 $this->getPageAndRootline();
1796 // 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.
1797 if ($domainStartPage && is_array($this->rootLine)) {
1798 $idFound = false;
1799 foreach ($this->rootLine as $key => $val) {
1800 if ($val['uid'] == $domainStartPage) {
1801 $idFound = true;
1802 break;
1803 }
1804 }
1805 if (!$idFound) {
1806 // Page is 'not found' in case the id was outside the domain, code 3
1807 $this->pageNotFound = 3;
1808 $this->id = $domainStartPage;
1809 // re-get the page and rootline if the id was not found.
1810 $this->getPageAndRootline();
1811 }
1812 }
1813 }
1814
1815 /**
1816 * Sets sys_page where-clause
1817 *
1818 * @access private
1819 */
1820 public function setSysPageWhereClause()
1821 {
1822 $expressionBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
1823 ->getConnectionForTable('pages')
1824 ->getExpressionBuilder();
1825 $this->sys_page->where_hid_del = ' AND ' . (string)$expressionBuilder->andX(
1826 QueryHelper::stripLogicalOperatorPrefix($this->sys_page->where_hid_del),
1827 $expressionBuilder->lt('pages.doktype', 200)
1828 );
1829 $this->sys_page->where_groupAccess = $this->sys_page->getMultipleGroupsWhereClause('pages.fe_group', 'pages');
1830 }
1831
1832 /**
1833 * Looking up a domain record based on HTTP_HOST
1834 *
1835 * @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.
1836 * @return int Returns the page id of the page where the domain record was found.
1837 * @access private
1838 */
1839 public function findDomainRecord($recursive = false)
1840 {
1841 if ($recursive) {
1842 $pageUid = 0;
1843 $host = explode('.', GeneralUtility::getIndpEnv('HTTP_HOST'));
1844 while (count($host)) {
1845 $pageUid = $this->sys_page->getDomainStartPage(implode('.', $host), GeneralUtility::getIndpEnv('SCRIPT_NAME'));
1846 if ($pageUid) {
1847 return $pageUid;
1848 }
1849 array_shift($host);
1850 }
1851 return $pageUid;
1852 }
1853 return $this->sys_page->getDomainStartPage(GeneralUtility::getIndpEnv('HTTP_HOST'), GeneralUtility::getIndpEnv('SCRIPT_NAME'));
1854 }
1855
1856 /**
1857 * Page unavailable handler for use in frontend plugins from extensions.
1858 *
1859 * @param string $reason Reason text
1860 * @param string $header HTTP header to send
1861 * @deprecated
1862 */
1863 public function pageUnavailableAndExit($reason = '', $header = '')
1864 {
1865 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1866 $header = $header ?: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling_statheader'];
1867 $this->pageUnavailableHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling'], $header, $reason);
1868 die;
1869 }
1870
1871 /**
1872 * Page-not-found handler for use in frontend plugins from extensions.
1873 *
1874 * @param string $reason Reason text
1875 * @param string $header HTTP header to send
1876 * @deprecated
1877 */
1878 public function pageNotFoundAndExit($reason = '', $header = '')
1879 {
1880 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1881 $header = $header ?: $GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling_statheader'];
1882 $this->pageNotFoundHandler($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFound_handling'], $header, $reason);
1883 die;
1884 }
1885
1886 /**
1887 * Checks whether the pageUnavailableHandler should be used. To be used, pageUnavailable_handling must be set
1888 * and devIPMask must not match the current visitor's IP address.
1889 *
1890 * @return bool TRUE/FALSE whether the pageUnavailable_handler should be used.
1891 * @deprecated
1892 */
1893 public function checkPageUnavailableHandler()
1894 {
1895 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1896 if (
1897 $GLOBALS['TYPO3_CONF_VARS']['FE']['pageUnavailable_handling']
1898 && !GeneralUtility::cmpIP(
1899 GeneralUtility::getIndpEnv('REMOTE_ADDR'),
1900 $GLOBALS['TYPO3_CONF_VARS']['SYS']['devIPmask']
1901 )
1902 ) {
1903 $checkPageUnavailableHandler = true;
1904 } else {
1905 $checkPageUnavailableHandler = false;
1906 }
1907 return $checkPageUnavailableHandler;
1908 }
1909
1910 /**
1911 * Page unavailable handler. Acts a wrapper for the pageErrorHandler method.
1912 *
1913 * @param mixed $code See ['FE']['pageUnavailable_handling'] for possible values
1914 * @param string $header If set, this is passed directly to the PHP function, header()
1915 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1916 * @deprecated
1917 */
1918 public function pageUnavailableHandler($code, $header, $reason)
1919 {
1920 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1921 $this->pageErrorHandler($code, $header, $reason);
1922 }
1923
1924 /**
1925 * Page not found handler. Acts a wrapper for the pageErrorHandler method.
1926 *
1927 * @param mixed $code See docs of ['FE']['pageNotFound_handling'] for possible values
1928 * @param string $header If set, this is passed directly to the PHP function, header()
1929 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1930 * @deprecated
1931 */
1932 public function pageNotFoundHandler($code, $header = '', $reason = '')
1933 {
1934 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
1935 $this->pageErrorHandler($code, $header, $reason);
1936 }
1937
1938 /**
1939 * Generic error page handler.
1940 * Exits.
1941 *
1942 * @param mixed $code See docs of ['FE']['pageNotFound_handling'] and ['FE']['pageUnavailable_handling'] for all possible values
1943 * @param string $header If set, this is passed directly to the PHP function, header()
1944 * @param string $reason If set, error messages will also mention this as the reason for the page-not-found.
1945 * @throws \RuntimeException
1946 * @deprecated
1947 */
1948 public function pageErrorHandler($code, $header = '', $reason = '')
1949 {
1950 trigger_error('This method will be removed in TYPO3 v10. Use TYPO3\'s ErrorController with Request/Response objects instead.', E_USER_DEPRECATED);
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 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Request parameters could not be validated (&cHash comparison failed)');
2164 $this->sendResponseAndExit($response);
2165 } else {
2166 $this->disableCache();
2167 $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);
2168 }
2169 }
2170 } elseif (is_array($GET)) {
2171 // No cHash is set, check if that is correct
2172 if ($this->cacheHash->doParametersRequireCacheHash(GeneralUtility::implodeArrayForUrl('', $GET))) {
2173 $this->reqCHash();
2174 }
2175 }
2176 }
2177
2178 /**
2179 * Will disable caching if the cHash value was not set.
2180 * 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)
2181 *
2182 * @see makeCacheHash(), \TYPO3\CMS\Frontend\Plugin\AbstractPlugin::pi_cHashCheck()
2183 */
2184 public function reqCHash()
2185 {
2186 if (!$this->cHash) {
2187 if ($GLOBALS['TYPO3_CONF_VARS']['FE']['pageNotFoundOnCHashError']) {
2188 if ($this->tempContent) {
2189 $this->clearPageCacheContent();
2190 }
2191 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Request parameters could not be validated (&cHash empty)');
2192 $this->sendResponseAndExit($response);
2193 } else {
2194 $this->disableCache();
2195 $this->getTimeTracker()->setTSlogMessage('TSFE->reqCHash(): No &cHash parameter was sent for GET vars though required so caching is disabled', 2);
2196 }
2197 }
2198 }
2199
2200 /**
2201 * Initialize the TypoScript template parser
2202 */
2203 public function initTemplate()
2204 {
2205 $this->tmpl = GeneralUtility::makeInstance(TemplateService::class);
2206 $this->tmpl->setVerbose((bool)$this->beUserLogin);
2207 $this->tmpl->init();
2208 $this->tmpl->tt_track = (bool)$this->beUserLogin;
2209 }
2210
2211 /**
2212 * See if page is in cache and get it if so
2213 * Stores the page content in $this->content if something is found.
2214 *
2215 * @throws \InvalidArgumentException
2216 * @throws \RuntimeException
2217 */
2218 public function getFromCache()
2219 {
2220 // clearing the content-variable, which will hold the pagecontent
2221 $this->content = '';
2222 // Unsetting the lowlevel config
2223 $this->config = [];
2224 $this->cacheContentFlag = false;
2225
2226 if ($this->no_cache) {
2227 return;
2228 }
2229
2230 $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2231 if (!is_array($pageSectionCacheContent)) {
2232 // Nothing in the cache, we acquire an "exclusive lock" for the key now.
2233 // We use the Registry to store this lock centrally,
2234 // but we protect the access again with a global exclusive lock to avoid race conditions
2235
2236 $this->acquireLock('pagesection', $this->id . '::' . $this->MP);
2237 //
2238 // from this point on we're the only one working on that page ($key)
2239 //
2240
2241 // query the cache again to see if the page data are there meanwhile
2242 $pageSectionCacheContent = $this->tmpl->getCurrentPageData();
2243 if (is_array($pageSectionCacheContent)) {
2244 // we have the content, nice that some other process did the work for us already
2245 $this->releaseLock('pagesection');
2246 }
2247 // We keep the lock set, because we are the ones generating the page now
2248 // and filling the cache.
2249 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2250 }
2251
2252 if (is_array($pageSectionCacheContent)) {
2253 // 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.
2254 // If this hash is not the same in here in this section and after page-generation, then the page will not be properly cached!
2255 // 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.
2256 $pageSectionCacheContent = $this->tmpl->matching($pageSectionCacheContent);
2257 ksort($pageSectionCacheContent);
2258 $this->all = $pageSectionCacheContent;
2259 }
2260 unset($pageSectionCacheContent);
2261
2262 // Look for page in cache only if a shift-reload is not sent to the server.
2263 $lockHash = $this->getLockHash();
2264 if (!$this->headerNoCache()) {
2265 if ($this->all) {
2266 // we got page section information
2267 $this->newHash = $this->getHash();
2268 $this->getTimeTracker()->push('Cache Row', '');
2269 $row = $this->getFromCache_queryRow();
2270 if (!is_array($row)) {
2271 // nothing in the cache, we acquire an exclusive lock now
2272
2273 $this->acquireLock('pages', $lockHash);
2274 //
2275 // from this point on we're the only one working on that page ($lockHash)
2276 //
2277
2278 // query the cache again to see if the data are there meanwhile
2279 $row = $this->getFromCache_queryRow();
2280 if (is_array($row)) {
2281 // we have the content, nice that some other process did the work for us
2282 $this->releaseLock('pages');
2283 }
2284 // We keep the lock set, because we are the ones generating the page now
2285 // and filling the cache.
2286 // This indicates that we have to release the lock in the Registry later in releaseLocks()
2287 }
2288 if (is_array($row)) {
2289 // we have data from cache
2290
2291 // Call hook when a page is retrieved from cache:
2292 $_params = ['pObj' => &$this, 'cache_pages_row' => &$row];
2293 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['pageLoadedFromCache'] ?? [] as $_funcRef) {
2294 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2295 }
2296 // Fetches the lowlevel config stored with the cached data
2297 $this->config = $row['cache_data'];
2298 // Getting the content
2299 $this->content = $row['content'];
2300 // Flag for temp content
2301 $this->tempContent = $row['temp_content'];
2302 // Setting flag, so we know, that some cached content has been loaded
2303 $this->cacheContentFlag = true;
2304 $this->cacheExpires = $row['expires'];
2305
2306 // Restore page title information, this is needed to generate the page title for
2307 // partially cached pages.
2308 $this->page['title'] = $row['pageTitleInfo']['title'];
2309 $this->altPageTitle = $row['pageTitleInfo']['altPageTitle'];
2310 $this->indexedDocTitle = $row['pageTitleInfo']['indexedDocTitle'];
2311
2312 if (isset($this->config['config']['debug'])) {
2313 $debugCacheTime = (bool)$this->config['config']['debug'];
2314 } else {
2315 $debugCacheTime = !empty($GLOBALS['TYPO3_CONF_VARS']['FE']['debug']);
2316 }
2317 if ($debugCacheTime) {
2318 $dateFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'];
2319 $timeFormat = $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'];
2320 $this->content .= LF . '<!-- Cached page generated ' . date($dateFormat . ' ' . $timeFormat, $row['tstamp']) . '. Expires ' . date($dateFormat . ' ' . $timeFormat, $row['expires']) . ' -->';
2321 }
2322 }
2323 $this->getTimeTracker()->pull();
2324
2325 return;
2326 }
2327 }
2328 // the user forced rebuilding the page cache or there was no pagesection information
2329 // get a lock for the page content so other processes will not interrupt the regeneration
2330 $this->acquireLock('pages', $lockHash);
2331 }
2332
2333 /**
2334 * Returning the cached version of page with hash = newHash
2335 *
2336 * @return array Cached row, if any. Otherwise void.
2337 */
2338 public function getFromCache_queryRow()
2339 {
2340 $this->getTimeTracker()->push('Cache Query', '');
2341 $row = $this->pageCache->get($this->newHash);
2342 $this->getTimeTracker()->pull();
2343 return $row;
2344 }
2345
2346 /**
2347 * Detecting if shift-reload has been clicked
2348 * Will not be called if re-generation of page happens by other reasons (for instance that the page is not in cache yet!)
2349 * Also, a backend user MUST be logged in for the shift-reload to be detected due to DoS-attack-security reasons.
2350 *
2351 * @return bool If shift-reload in client browser has been clicked, disable getting cached page (and regenerate it).
2352 */
2353 public function headerNoCache()
2354 {
2355 $disableAcquireCacheData = false;
2356 if ($this->beUserLogin) {
2357 if (strtolower($_SERVER['HTTP_CACHE_CONTROL']) === 'no-cache' || strtolower($_SERVER['HTTP_PRAGMA']) === 'no-cache') {
2358 $disableAcquireCacheData = true;
2359 }
2360 }
2361 // Call hook for possible by-pass of requiring of page cache (for recaching purpose)
2362 $_params = ['pObj' => &$this, 'disableAcquireCacheData' => &$disableAcquireCacheData];
2363 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['headerNoCache'] ?? [] as $_funcRef) {
2364 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2365 }
2366 return $disableAcquireCacheData;
2367 }
2368
2369 /**
2370 * Calculates the cache-hash
2371 * This hash is unique to the template, the variables ->id, ->type, ->gr_list (list of groups), ->MP (Mount Points) and cHash array
2372 * Used to get and later store the cached data.
2373 *
2374 * @return string MD5 hash of serialized hash base from createHashBase()
2375 * @access private
2376 * @see getFromCache(), getLockHash()
2377 */
2378 public function getHash()
2379 {
2380 return md5($this->createHashBase(false));
2381 }
2382
2383 /**
2384 * Calculates the lock-hash
2385 * This hash is unique to the above hash, except that it doesn't contain the template information in $this->all.
2386 *
2387 * @return string MD5 hash
2388 * @access private
2389 * @see getFromCache(), getHash()
2390 */
2391 public function getLockHash()
2392 {
2393 $lockHash = $this->createHashBase(true);
2394 return md5($lockHash);
2395 }
2396
2397 /**
2398 * Calculates the cache-hash (or the lock-hash)
2399 * This hash is unique to the template,
2400 * the variables ->id, ->type, ->gr_list (list of groups),
2401 * ->MP (Mount Points) and cHash array
2402 * Used to get and later store the cached data.
2403 *
2404 * @param bool $createLockHashBase Whether to create the lock hash, which doesn't contain the "this->all" (the template information)
2405 * @return string the serialized hash base
2406 */
2407 protected function createHashBase($createLockHashBase = false)
2408 {
2409 $hashParameters = [
2410 'id' => (int)$this->id,
2411 'type' => (int)$this->type,
2412 'gr_list' => (string)$this->gr_list,
2413 'MP' => (string)$this->MP,
2414 'cHash' => $this->cHash_array,
2415 'domainStartPage' => $this->domainStartPage
2416 ];
2417 // Include the template information if we shouldn't create a lock hash
2418 if (!$createLockHashBase) {
2419 $hashParameters['all'] = $this->all;
2420 }
2421 // Call hook to influence the hash calculation
2422 $_params = [
2423 'hashParameters' => &$hashParameters,
2424 'createLockHashBase' => $createLockHashBase
2425 ];
2426 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['createHashBase'] ?? [] as $_funcRef) {
2427 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2428 }
2429 return serialize($hashParameters);
2430 }
2431
2432 /**
2433 * Checks if config-array exists already but if not, gets it
2434 *
2435 * @throws ServiceUnavailableException
2436 */
2437 public function getConfigArray()
2438 {
2439 // 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
2440 if (empty($this->config) || is_array($this->config['INTincScript']) || $this->forceTemplateParsing) {
2441 $timeTracker = $this->getTimeTracker();
2442 $timeTracker->push('Parse template', '');
2443 // Force parsing, if set?:
2444 $this->tmpl->forceTemplateParsing = $this->forceTemplateParsing;
2445 // Start parsing the TS template. Might return cached version.
2446 $this->tmpl->start($this->rootLine);
2447 $timeTracker->pull();
2448 if ($this->tmpl->loaded) {
2449 $timeTracker->push('Setting the config-array', '');
2450 // toplevel - objArrayName
2451 $this->sPre = $this->tmpl->setup['types.'][$this->type];
2452 $this->pSetup = $this->tmpl->setup[$this->sPre . '.'];
2453 if (!is_array($this->pSetup)) {
2454 $message = 'The page is not configured! [type=' . $this->type . '][' . $this->sPre . '].';
2455 $this->logger->alert($message);
2456 try {
2457 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message);
2458 $this->sendResponseAndExit($response);
2459 } catch (ServiceUnavailableException $e) {
2460 $explanation = 'This means that there is no TypoScript object of type PAGE with typeNum=' . $this->type . ' configured.';
2461 throw new ServiceUnavailableException($message . ' ' . $explanation, 1294587217);
2462 }
2463 } else {
2464 if (!isset($this->config['config'])) {
2465 $this->config['config'] = [];
2466 }
2467 // Filling the config-array, first with the main "config." part
2468 if (is_array($this->tmpl->setup['config.'])) {
2469 ArrayUtility::mergeRecursiveWithOverrule($this->tmpl->setup['config.'], $this->config['config']);
2470 $this->config['config'] = $this->tmpl->setup['config.'];
2471 }
2472 // override it with the page/type-specific "config."
2473 if (is_array($this->pSetup['config.'])) {
2474 ArrayUtility::mergeRecursiveWithOverrule($this->config['config'], $this->pSetup['config.']);
2475 }
2476 // @deprecated since TYPO3 v9, can be removed in TYPO3 v10
2477 if ($this->config['config']['typolinkCheckRootline']) {
2478 $this->logDeprecatedTyposcript('config.typolinkCheckRootline', 'The functionality is always enabled since TYPO3 v9 and can be removed from your TypoScript code');
2479 }
2480 // Set default values for removeDefaultJS and inlineStyle2TempFile so CSS and JS are externalized if compatversion is higher than 4.0
2481 if (!isset($this->config['config']['removeDefaultJS'])) {
2482 $this->config['config']['removeDefaultJS'] = 'external';
2483 }
2484 if (!isset($this->config['config']['inlineStyle2TempFile'])) {
2485 $this->config['config']['inlineStyle2TempFile'] = 1;
2486 }
2487
2488 if (!isset($this->config['config']['compressJs'])) {
2489 $this->config['config']['compressJs'] = 0;
2490 }
2491 // Processing for the config_array:
2492 $this->config['rootLine'] = $this->tmpl->rootLine;
2493 // Class for render Header and Footer parts
2494 if ($this->pSetup['pageHeaderFooterTemplateFile']) {
2495 $file = $this->tmpl->getFileName($this->pSetup['pageHeaderFooterTemplateFile']);
2496 if ($file) {
2497 $this->pageRenderer->setTemplateFile($file);
2498 }
2499 }
2500 }
2501 $timeTracker->pull();
2502 } else {
2503 $message = 'No TypoScript template found!';
2504 $this->logger->alert($message);
2505 try {
2506 $response = GeneralUtility::makeInstance(ErrorController::class)->unavailableAction($message);
2507 $this->sendResponseAndExit($response);
2508 } catch (ServiceUnavailableException $e) {
2509 throw new ServiceUnavailableException($message, 1294587218);
2510 }
2511 }
2512 }
2513
2514 // No cache
2515 // Set $this->no_cache TRUE if the config.no_cache value is set!
2516 if ($this->config['config']['no_cache']) {
2517 $this->set_no_cache('config.no_cache is set');
2518 }
2519 // Merge GET with defaultGetVars
2520 if (!empty($this->config['config']['defaultGetVars.'])) {
2521 $modifiedGetVars = GeneralUtility::removeDotsFromTS($this->config['config']['defaultGetVars.']);
2522 ArrayUtility::mergeRecursiveWithOverrule($modifiedGetVars, GeneralUtility::_GET());
2523 GeneralUtility::_GETset($modifiedGetVars);
2524 }
2525 // Hook for postProcessing the configuration array
2526 $params = ['config' => &$this->config['config']];
2527 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['configArrayPostProc'] ?? [] as $funcRef) {
2528 GeneralUtility::callUserFunction($funcRef, $params, $this);
2529 }
2530 }
2531
2532 /********************************************
2533 *
2534 * Further initialization and data processing
2535 *
2536 *******************************************/
2537
2538 /**
2539 * Setting the language key that will be used by the current page.
2540 * 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.
2541 *
2542 * @access private
2543 */
2544 public function settingLanguage()
2545 {
2546 $_params = [];
2547 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_preProcess'] ?? [] as $_funcRef) {
2548 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2549 }
2550
2551 // Initialize charset settings etc.
2552 $languageKey = $this->config['config']['language'] ?? 'default';
2553 $this->lang = $languageKey;
2554 $this->setOutputLanguage($languageKey);
2555
2556 // Rendering charset of HTML page.
2557 if (isset($this->config['config']['metaCharset']) && $this->config['config']['metaCharset'] !== 'utf-8') {
2558 $this->metaCharset = $this->config['config']['metaCharset'];
2559 }
2560
2561 // Get values from TypoScript, if not set before
2562 if ($this->sys_language_uid === 0) {
2563 $this->sys_language_uid = ($this->sys_language_content = (int)$this->config['config']['sys_language_uid']);
2564 }
2565 list($this->sys_language_mode, $sys_language_content) = GeneralUtility::trimExplode(';', $this->config['config']['sys_language_mode']);
2566 $this->sys_language_contentOL = $this->config['config']['sys_language_overlay'];
2567 // If sys_language_uid is set to another language than default:
2568 if ($this->sys_language_uid > 0) {
2569 // check whether a shortcut is overwritten by a translated page
2570 // we can only do this now, as this is the place where we get
2571 // to know about translations
2572 $this->checkTranslatedShortcut();
2573 // Request the overlay record for the sys_language_uid:
2574 $olRec = $this->sys_page->getPageOverlay($this->id, $this->sys_language_uid);
2575 if (empty($olRec)) {
2576 // If no OL record exists and a foreign language is asked for...
2577 if ($this->sys_language_uid) {
2578 // If requested translation is not available:
2579 if (GeneralUtility::hideIfNotTranslated($this->page['l18n_cfg'])) {
2580 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Page is not available in the requested language.');
2581 $this->sendResponseAndExit($response);
2582 } else {
2583 switch ((string)$this->sys_language_mode) {
2584 case 'strict':
2585 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Page is not available in the requested language (strict).');
2586 $this->sendResponseAndExit($response);
2587 break;
2588 case 'content_fallback':
2589 // Setting content uid (but leaving the sys_language_uid) when a content_fallback
2590 // value was found.
2591 $fallBackOrder = GeneralUtility::trimExplode(',', $sys_language_content);
2592 foreach ($fallBackOrder as $orderValue) {
2593 if ($orderValue === '0' || $orderValue === '') {
2594 $this->sys_language_content = 0;
2595 break;
2596 }
2597 if (MathUtility::canBeInterpretedAsInteger($orderValue) && !empty($this->sys_page->getPageOverlay($this->id, (int)$orderValue))) {
2598 $this->sys_language_content = (int)$orderValue;
2599 break;
2600 }
2601 if ($orderValue === 'pageNotFound') {
2602 // The existing fallbacks have not been found, but instead of continuing
2603 // page rendering with default language, a "page not found" message should be shown
2604 // instead.
2605 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction('Page is not available in the requested language (fallbacks did not apply).');
2606 $this->sendResponseAndExit($response);
2607 }
2608 }
2609 break;
2610 case 'ignore':
2611 $this->sys_language_content = $this->sys_language_uid;
2612 break;
2613 default:
2614 // Default is that everything defaults to the default language...
2615 $this->sys_language_uid = ($this->sys_language_content = 0);
2616 }
2617 }
2618 }
2619 } else {
2620 // Setting sys_language if an overlay record was found (which it is only if a language is used)
2621 $this->page = $this->sys_page->getPageOverlay($this->page, $this->sys_language_uid);
2622 }
2623 }
2624 // Setting sys_language_uid inside sys-page:
2625 $this->sys_page->sys_language_uid = $this->sys_language_uid;
2626 // If default translation is not available:
2627 if ((!$this->sys_language_uid || !$this->sys_language_content) && GeneralUtility::hideIfDefaultLanguage($this->page['l18n_cfg'])) {
2628 $message = 'Page is not available in default language.';
2629 $this->logger->error($message);
2630 $response = GeneralUtility::makeInstance(ErrorController::class)->pageNotFoundAction($message);
2631 $this->sendResponseAndExit($response);
2632 }
2633 $this->updateRootLinesWithTranslations();
2634
2635 // Finding the ISO code for the currently selected language
2636 // fetched by the sys_language record when not fetching content from the default language
2637 if ($this->sys_language_content > 0) {
2638 // using sys_language_content because the ISO code only (currently) affect content selection from FlexForms - which should follow "sys_language_content"
2639 // Set the fourth parameter to TRUE in the next two getRawRecord() calls to
2640 // avoid versioning overlay to be applied as it generates an SQL error
2641 $sys_language_row = $this->sys_page->getRawRecord('sys_language', $this->sys_language_content, 'language_isocode,static_lang_isocode');
2642 if (is_array($sys_language_row) && !empty($sys_language_row['language_isocode'])) {
2643 $this->sys_language_isocode = $sys_language_row['language_isocode'];
2644 }
2645 // the DB value is overridden by TypoScript
2646 if (!empty($this->config['config']['sys_language_isocode'])) {
2647 $this->sys_language_isocode = $this->config['config']['sys_language_isocode'];
2648 }
2649 } else {
2650 // fallback to the TypoScript option when rendering with sys_language_uid=0
2651 // also: use "en" by default
2652 if (!empty($this->config['config']['sys_language_isocode_default'])) {
2653 $this->sys_language_isocode = $this->config['config']['sys_language_isocode_default'];
2654 } else {
2655 $this->sys_language_isocode = $languageKey !== 'default' ? $languageKey : 'en';
2656 }
2657 }
2658
2659 $_params = [];
2660 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['settingLanguage_postProcess'] ?? [] as $_funcRef) {
2661 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
2662 }
2663 }
2664
2665 /**
2666 * Updating content of the two rootLines IF the language key is set!
2667 */
2668 protected function updateRootLinesWithTranslations()
2669 {
2670 if ($this->sys_language_uid) {
2671 $this->rootLine = $this->sys_page->getRootLine($this->id, $this->MP);
2672 $this->tmpl->updateRootlineData($this->rootLine);
2673 }
2674 }
2675
2676 /**
2677 * Setting locale for frontend rendering
2678 */
2679 public function settingLocale()
2680 {
2681 // Setting locale
2682 if ($this->config['config']['locale_all']) {
2683 $availableLocales = GeneralUtility::trimExplode(',', $this->config['config']['locale_all'], true);
2684 // If LC_NUMERIC is set e.g. to 'de_DE' PHP parses float values locale-aware resulting in strings with comma
2685 // as decimal point which causes problems with value conversions - so we set all locale types except LC_NUMERIC
2686 // @see https://bugs.php.net/bug.php?id=53711
2687 $locale = setlocale(LC_COLLATE, ...$availableLocales);
2688 if ($locale) {
2689 // As str_* methods are locale aware and turkish has no upper case I
2690 // Class autoloading and other checks depending on case changing break with turkish locale LC_CTYPE
2691 // @see http://bugs.php.net/bug.php?id=35050
2692 if (substr($this->config['config']['locale_all'], 0, 2) !== 'tr') {
2693 setlocale(LC_CTYPE, ...$availableLocales);
2694 }
2695 setlocale(LC_MONETARY, ...$availableLocales);
2696 setlocale(LC_TIME, ...$availableLocales);
2697 } else {
2698 $this->getTimeTracker()->setTSlogMessage('Locale "' . htmlspecialchars($this->config['config']['locale_all']) . '" not found.', 3);
2699 }
2700 }
2701 }
2702
2703 /**
2704 * Checks whether a translated shortcut page has a different shortcut
2705 * target than the original language page.
2706 * If that is the case, things get corrected to follow that alternative
2707 * shortcut
2708 */
2709 protected function checkTranslatedShortcut()
2710 {
2711 if (!is_null($this->originalShortcutPage)) {
2712 $originalShortcutPageOverlay = $this->sys_page->getPageOverlay($this->originalShortcutPage['uid'], $this->sys_language_uid);
2713 if (!empty($originalShortcutPageOverlay['shortcut']) && $originalShortcutPageOverlay['shortcut'] != $this->id) {
2714 // the translation of the original shortcut page has a different shortcut target!
2715 // set the correct page and id
2716 $shortcut = $this->getPageShortcut($originalShortcutPageOverlay['shortcut'], $originalShortcutPageOverlay['shortcut_mode'], $originalShortcutPageOverlay['uid']);
2717 $this->id = ($this->contentPid = $shortcut['uid']);
2718 $this->page = $this->sys_page->getPage($this->id);
2719 // Fix various effects on things like menus f.e.
2720 $this->fetch_the_id();
2721 $this->tmpl->rootLine = array_reverse($this->rootLine);
2722 }
2723 }
2724 }
2725
2726 /**
2727 * Handle data submission
2728 * This is done at this point, because we need the config values
2729 */
2730 public function handleDataSubmission()
2731 {
2732 // Hook for processing data submission to extensions
2733 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['checkDataSubmission'] ?? [] as $className) {
2734 $_procObj = GeneralUtility::makeInstance($className);
2735 $_procObj->checkDataSubmission($this);
2736 }
2737 }
2738
2739 /**
2740 * Loops over all configured URL handlers and registers all active handlers in the redirect URL handler array.
2741 *
2742 * @see $activeRedirectUrlHandlers
2743 */
2744 public function initializeRedirectUrlHandlers()
2745 {
2746 $urlHandlers = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['urlProcessing']['urlHandlers'] ?? false;
2747 if (!$urlHandlers) {
2748 return;
2749 }
2750
2751 foreach ($urlHandlers as $identifier => $configuration) {
2752 if (empty($configuration) || !is_array($configuration)) {
2753 throw new \RuntimeException('Missing configuration for URL handler "' . $identifier . '".', 1442052263);
2754 }
2755 if (!is_string($configuration['handler']) || empty($configuration['handler']) || !class_exists($configuration['handler']) || !is_subclass_of($configuration['handler'], UrlHandlerInterface::class)) {
2756 throw new \RuntimeException('The URL handler "' . $identifier . '" defines an invalid provider. Ensure the class exists and implements the "' . UrlHandlerInterface::class . '".', 1442052249);
2757 }
2758 }
2759
2760 $orderedHandlers = GeneralUtility::makeInstance(DependencyOrderingService::class)->orderByDependencies($urlHandlers);
2761
2762 foreach ($orderedHandlers as $configuration) {
2763 /** @var UrlHandlerInterface $urlHandler */
2764 $urlHandler = GeneralUtility::makeInstance($configuration['handler']);
2765 if ($urlHandler->canHandleCurrentUrl()) {
2766 $this->activeUrlHandlers[] = $urlHandler;
2767 }
2768 }
2769 }
2770
2771 /**
2772 * Loops over all registered URL handlers and lets them process the current URL.
2773 *
2774 * If no handler has stopped the current process (e.g. by redirecting) and a
2775 * the redirectUrl propert is not empty, the user will be redirected to this URL.
2776 *
2777 * @internal Should be called by the FrontendRequestHandler only.
2778 * @return ResponseInterface|null
2779 */
2780 public function redirectToExternalUrl()
2781 {
2782 foreach ($this->activeUrlHandlers as $redirectHandler) {
2783 $response = $redirectHandler->handle();
2784 if ($response instanceof ResponseInterface) {
2785 return $response;
2786 }
2787 }
2788
2789 if (!empty($this->activeUrlHandlers)) {
2790 throw new \RuntimeException('A URL handler is active but did not process the URL.', 1442305505);
2791 }
2792
2793 return null;
2794 }
2795
2796 /**
2797 * Sets the URL_ID_TOKEN in the internal var, $this->getMethodUrlIdToken
2798 * This feature allows sessions to use a GET-parameter instead of a cookie.
2799 *
2800 * @access private
2801 */
2802 public function setUrlIdToken()
2803 {
2804 if ($this->config['config']['ftu']) {
2805 $this->getMethodUrlIdToken = $GLOBALS['TYPO3_CONF_VARS']['FE']['get_url_id_token'];
2806 } else {
2807 $this->getMethodUrlIdToken = '';
2808 }
2809 }
2810
2811 /**
2812 * Calculates and sets the internal linkVars based upon the current
2813 * $_GET parameters and the setting "config.linkVars".
2814 */
2815 public function calculateLinkVars()
2816 {
2817 $this->linkVars = '';
2818 if (empty($this->config['config']['linkVars'])) {
2819 return;
2820 }
2821
2822 $linkVars = $this->splitLinkVarsString((string)$this->config['config']['linkVars']);
2823
2824 if (empty($linkVars)) {
2825 return;
2826 }
2827 $getData = GeneralUtility::_GET();
2828 foreach ($linkVars as $linkVar) {
2829 $test = $value = '';
2830 if (preg_match('/^(.*)\\((.+)\\)$/', $linkVar, $match)) {
2831 $linkVar = trim($match[1]);
2832 $test = trim($match[2]);
2833 }
2834
2835 $keys = explode('|', $linkVar);
2836 $numberOfLevels = count($keys);
2837 $rootKey = trim($keys[0]);
2838 if (!isset($getData[$rootKey])) {
2839 continue;
2840 }
2841 $value = $getData[$rootKey];
2842 for ($i = 1; $i < $numberOfLevels; $i++) {
2843 $currentKey = trim($keys[$i]);
2844 if (isset($value[$currentKey])) {
2845 $value = $value[$currentKey];
2846 } else {
2847 $value = false;
2848 break;
2849 }
2850 }
2851 if ($value !== false) {
2852 $parameterName = $keys[0];
2853 for ($i = 1; $i < $numberOfLevels; $i++) {
2854 $parameterName .= '[' . $keys[$i] . ']';
2855 }
2856 if (!is_array($value)) {
2857 $temp = rawurlencode($value);
2858 if ($test !== '' && !$this->isAllowedLinkVarValue($temp, $test)) {
2859 // Error: This value was not allowed for this key
2860 continue;
2861 }
2862 $value = '&' . $parameterName . '=' . $temp;
2863 } else {
2864 if ($test !== '' && $test !== 'array') {
2865 // Error: This key must not be an array!
2866 continue;
2867 }
2868 $value = GeneralUtility::implodeArrayForUrl($parameterName, $value);
2869 }
2870 $this->linkVars .= $value;
2871 }
2872 }
2873 }
2874
2875 /**
2876 * Split the link vars string by "," but not if the "," is inside of braces
2877 *
2878 * @param $string
2879 *
2880 * @return array
2881 */
2882 protected function splitLinkVarsString(string $string): array
2883 {
2884 $tempCommaReplacementString = '###KASPER###';
2885
2886 // replace every "," wrapped in "()" by a "unique" string
2887 $string = preg_replace_callback('/\((?>[^()]|(?R))*\)/', function ($result) use ($tempCommaReplacementString) {
2888 return str_replace(',', $tempCommaReplacementString, $result[0]);
2889 }, $string);
2890
2891 $string = GeneralUtility::trimExplode(',', $string);
2892
2893 // replace all "unique" strings back to ","
2894 return str_replace($tempCommaReplacementString, ',', $string);
2895 }
2896
2897 /**
2898 * Checks if the value defined in "config.linkVars" contains an allowed value.
2899 * Otherwise, return FALSE which means the value will not be added to any links.
2900 *
2901 * @param string $haystack The string in which to find $needle
2902 * @param string $needle The string to find in $haystack
2903 * @return bool Returns TRUE if $needle matches or is found in $haystack
2904 */
2905 protected function isAllowedLinkVarValue(string $haystack, string $needle): bool
2906 {
2907 $isAllowed = false;
2908 // Integer
2909 if ($needle === 'int' || $needle === 'integer') {
2910 if (MathUtility::canBeInterpretedAsInteger($haystack)) {
2911 $isAllowed = true;
2912 }
2913 } elseif (preg_match('/^\\/.+\\/[imsxeADSUXu]*$/', $needle)) {
2914 // Regular expression, only "//" is allowed as delimiter
2915 if (@preg_match($needle, $haystack)) {
2916 $isAllowed = true;
2917 }
2918 } elseif (strstr($needle, '-')) {
2919 // Range
2920 if (MathUtility::canBeInterpretedAsInteger($haystack)) {
2921 $range = explode('-', $needle);
2922 if ($range[0] <= $haystack && $range[1] >= $haystack) {
2923 $isAllowed = true;
2924 }
2925 }
2926 } elseif (strstr($needle, '|')) {
2927 // List
2928 // Trim the input
2929 $haystack = str_replace(' ', '', $haystack);
2930 if (strstr('|' . $needle . '|', '|' . $haystack . '|')) {
2931 $isAllowed = true;
2932 }
2933 } elseif ((string)$needle === (string)$haystack) {
2934 // String comparison
2935 $isAllowed = true;
2936 }
2937 return $isAllowed;
2938 }
2939
2940 /**
2941 * Redirect to target page if the current page is an overlaid mountpoint.
2942 *
2943 * If the current page is of type mountpoint and should be overlaid with the contents of the mountpoint page
2944 * and is accessed directly, the user will be redirected to the mountpoint context.
2945 */
2946 public function checkPageForMountpointRedirect()
2947 {
2948 if (!empty($this->originalMountPointPage) && $this->originalMountPointPage['doktype'] == PageRepository::DOKTYPE_MOUNTPOINT) {
2949 $this->redirectToCurrentPage();
2950 }
2951 }
2952
2953 /**
2954 * Redirect to target page, if the current page is a Shortcut.
2955 *
2956 * If the current page is of type shortcut and accessed directly via its URL, this function redirects to the
2957 * Shortcut target using a Location header.
2958 */
2959 public function checkPageForShortcutRedirect()
2960 {
2961 if (!empty($this->originalShortcutPage) && $this->originalShortcutPage['doktype'] == PageRepository::DOKTYPE_SHORTCUT) {
2962 $this->redirectToCurrentPage();
2963 }
2964 }
2965
2966 /**
2967 * Builds a typolink to the current page, appends the type paremeter if required
<